2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
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);
138 * A test suite that can contain a collection of TestCase and TestSuite objects.
139 * @param {String||Object} data The name of the test suite or an object containing
140 * a name property as well as setUp and tearDown methods.
145 Y.Test.Suite = function (data /*:String||Object*/) {
148 * The name of the test suite.
155 * Array of test suites and
160 //initialize the properties
161 if (Y.Lang.isString(data)){
163 } else if (Y.Lang.isObject(data)){
164 Y.mix(this, data, true);
168 if (this.name === ""){
169 this.name = "testSuite" + Y.guid();
174 Y.Test.Suite.prototype = {
177 * Adds a test suite or test case to the test suite.
178 * @param {Y.Test.Suite||Y.Test.Case} testObject The test suite or test case to add.
182 add : function (testObject /*:Y.Test.Suite*/) {
183 if (testObject instanceof Y.Test.Suite || testObject instanceof Y.Test.Case) {
184 this.items.push(testObject);
189 //-------------------------------------------------------------------------
191 //-------------------------------------------------------------------------
194 * Function to run before each test is executed.
198 setUp : function () {
202 * Function to run after each test is executed.
206 tearDown: function () {
213 * Runs test suites and test cases, providing events to allowing for the
214 * interpretation of test results.
219 Y.Test.Runner = (function(){
222 * A node in the test tree structure. May represent a TestSuite, TestCase, or
224 * @param {Variant} testObject A TestSuite, TestCase, or the name of a test function.
229 function TestNode(testObject){
232 * The TestSuite, TestCase, or test function represented by this node.
234 * @property testObject
236 this.testObject = testObject;
239 * Pointer to this node's first child.
241 * @property firstChild
243 this.firstChild = null;
246 * Pointer to this node's last child.
248 * @property lastChild
250 this.lastChild = null;
253 * Pointer to this node's parent.
260 * Pointer to this node's next sibling.
267 * Test results for this test object.
279 if (testObject instanceof Y.Test.Suite){
280 this.results.type = "testsuite";
281 this.results.name = testObject.name;
282 } else if (testObject instanceof Y.Test.Case){
283 this.results.type = "testcase";
284 this.results.name = testObject.name;
289 TestNode.prototype = {
292 * Appends a new test object (TestSuite, TestCase, or test function name) as a child
294 * @param {Variant} testObject A TestSuite, TestCase, or the name of a test function.
297 appendChild : function (testObject){
298 var node = new TestNode(testObject);
299 if (this.firstChild === null){
300 this.firstChild = this.lastChild = node;
302 this.lastChild.next = node;
303 this.lastChild = node;
311 * Runs test suites and test cases, providing events to allowing for the
312 * interpretation of test results.
317 function TestRunner(){
319 //inherit from EventProvider
320 TestRunner.superclass.constructor.apply(this,arguments);
323 * Suite on which to attach all TestSuites and TestCases to be run.
325 * @property masterSuite
329 this.masterSuite /*:Y.Test.Suite*/ = new Y.Test.Suite("YUI Test Results");
332 * Pointer to the current node in the test tree.
341 * Pointer to the root node in the test tree.
350 * Indicates if the TestRunner will log events or not.
359 * Indicates if the TestRunner is waiting as a result of
360 * wait() being called.
366 this._waiting = false;
370 this.TEST_CASE_BEGIN_EVENT,
371 this.TEST_CASE_COMPLETE_EVENT,
372 this.TEST_SUITE_BEGIN_EVENT,
373 this.TEST_SUITE_COMPLETE_EVENT,
374 this.TEST_PASS_EVENT,
375 this.TEST_FAIL_EVENT,
376 this.TEST_IGNORE_EVENT,
380 for (var i=0; i < events.length; i++){
381 this.subscribe(events[i], this._logEvent, this, true);
386 Y.extend(TestRunner, Y.Event.Target, {
388 //-------------------------------------------------------------------------
390 //-------------------------------------------------------------------------
393 * Fires when a test case is opened but before the first
395 * @event testcasebegin
398 TEST_CASE_BEGIN_EVENT : "testcasebegin",
401 * Fires when all tests in a test case have been executed.
402 * @event testcasecomplete
405 TEST_CASE_COMPLETE_EVENT : "testcasecomplete",
408 * Fires when a test suite is opened but before the first
410 * @event testsuitebegin
413 TEST_SUITE_BEGIN_EVENT : "testsuitebegin",
416 * Fires when all test cases in a test suite have been
418 * @event testsuitecomplete
421 TEST_SUITE_COMPLETE_EVENT : "testsuitecomplete",
424 * Fires when a test has passed.
428 TEST_PASS_EVENT : "pass",
431 * Fires when a test has failed.
435 TEST_FAIL_EVENT : "fail",
438 * Fires when a test has been ignored.
442 TEST_IGNORE_EVENT : "ignore",
445 * Fires when all test suites and test cases have been completed.
449 COMPLETE_EVENT : "complete",
452 * Fires when the run() method is called.
456 BEGIN_EVENT : "begin",
458 //-------------------------------------------------------------------------
459 // Logging-Related Methods
460 //-------------------------------------------------------------------------
464 * Disable logging via Y.log(). Test output will not be visible unless
465 * TestRunner events are subscribed to.
467 * @method disableLogging
470 disableLogging: function(){
475 * Enable logging via Y.log(). Test output is published and can be read via
478 * @method enableLogging
481 enableLogging: function(){
486 * Logs TestRunner events using Y.log().
487 * @param {Object} event The event object for the event.
493 _logEvent: function(event){
497 var messageType = "";
500 case this.BEGIN_EVENT:
501 message = "Testing began at " + (new Date()).toString() + ".";
502 messageType = "info";
505 case this.COMPLETE_EVENT:
506 message = "Testing completed at " + (new Date()).toString() + ".\nPassed:" +
507 event.results.passed + " Failed:" + event.results.failed + " Total:" + event.results.total;
508 messageType = "info";
511 case this.TEST_FAIL_EVENT:
512 message = event.testName + ": failed.\n" + event.error.getMessage();
513 messageType = "fail";
516 case this.TEST_IGNORE_EVENT:
517 message = event.testName + ": ignored.";
518 messageType = "ignore";
521 case this.TEST_PASS_EVENT:
522 message = event.testName + ": passed.";
523 messageType = "pass";
526 case this.TEST_SUITE_BEGIN_EVENT:
527 message = "Test suite \"" + event.testSuite.name + "\" started.";
528 messageType = "info";
531 case this.TEST_SUITE_COMPLETE_EVENT:
532 message = "Test suite \"" + event.testSuite.name + "\" completed.\nPassed:" +
533 event.results.passed + " Failed:" + event.results.failed + " Total:" + event.results.total;
534 messageType = "info";
537 case this.TEST_CASE_BEGIN_EVENT:
538 message = "Test case \"" + event.testCase.name + "\" started.";
539 messageType = "info";
542 case this.TEST_CASE_COMPLETE_EVENT:
543 message = "Test case \"" + event.testCase.name + "\" completed.\nPassed:" +
544 event.results.passed + " Failed:" + event.results.failed + " Total:" + event.results.total;
545 messageType = "info";
548 message = "Unexpected event " + event.type;
552 //only log if required
554 Y.log(message, messageType, "TestRunner");
558 //-------------------------------------------------------------------------
559 // Test Tree-Related Methods
560 //-------------------------------------------------------------------------
563 * Adds a test case to the test tree as a child of the specified node.
564 * @param {TestNode} parentNode The node to add the test case to as a child.
565 * @param {Y.Test.Case} testCase The test case to add.
569 * @method _addTestCaseToTestTree
571 _addTestCaseToTestTree : function (parentNode, testCase /*:Y.Test.Case*/){
574 var node = parentNode.appendChild(testCase),
578 //iterate over the items in the test case
579 for (prop in testCase){
580 if ((prop.indexOf("test") === 0 || (prop.toLowerCase().indexOf("should") > -1 && prop.indexOf(" ") > -1 ))&& Y.Lang.isFunction(testCase[prop])){
581 node.appendChild(prop);
588 * Adds a test suite to the test tree as a child of the specified node.
589 * @param {TestNode} parentNode The node to add the test suite to as a child.
590 * @param {Y.Test.Suite} testSuite The test suite to add.
594 * @method _addTestSuiteToTestTree
596 _addTestSuiteToTestTree : function (parentNode, testSuite /*:Y.Test.Suite*/) {
599 var node = parentNode.appendChild(testSuite);
601 //iterate over the items in the master suite
602 for (var i=0; i < testSuite.items.length; i++){
603 if (testSuite.items[i] instanceof Y.Test.Suite) {
604 this._addTestSuiteToTestTree(node, testSuite.items[i]);
605 } else if (testSuite.items[i] instanceof Y.Test.Case) {
606 this._addTestCaseToTestTree(node, testSuite.items[i]);
612 * Builds the test tree based on items in the master suite. The tree is a hierarchical
613 * representation of the test suites, test cases, and test functions. The resulting tree
614 * is stored in _root and the pointer _cur is set to the root initially.
618 * @method _buildTestTree
620 _buildTestTree : function () {
622 this._root = new TestNode(this.masterSuite);
623 this._cur = this._root;
625 //iterate over the items in the master suite
626 for (var i=0; i < this.masterSuite.items.length; i++){
627 if (this.masterSuite.items[i] instanceof Y.Test.Suite) {
628 this._addTestSuiteToTestTree(this._root, this.masterSuite.items[i]);
629 } else if (this.masterSuite.items[i] instanceof Y.Test.Case) {
630 this._addTestCaseToTestTree(this._root, this.masterSuite.items[i]);
636 //-------------------------------------------------------------------------
638 //-------------------------------------------------------------------------
641 * Handles the completion of a test object's tests. Tallies test results
642 * from one level up to the next.
643 * @param {TestNode} node The TestNode representing the test object.
645 * @method _handleTestObjectComplete
648 _handleTestObjectComplete : function (node) {
649 if (Y.Lang.isObject(node.testObject)){
650 node.parent.results.passed += node.results.passed;
651 node.parent.results.failed += node.results.failed;
652 node.parent.results.total += node.results.total;
653 node.parent.results.ignored += node.results.ignored;
654 node.parent.results[node.testObject.name] = node.results;
656 if (node.testObject instanceof Y.Test.Suite){
657 node.testObject.tearDown();
658 this.fire(this.TEST_SUITE_COMPLETE_EVENT, { testSuite: node.testObject, results: node.results});
659 } else if (node.testObject instanceof Y.Test.Case){
660 this.fire(this.TEST_CASE_COMPLETE_EVENT, { testCase: node.testObject, results: node.results});
665 //-------------------------------------------------------------------------
666 // Navigation Methods
667 //-------------------------------------------------------------------------
670 * Retrieves the next node in the test tree.
671 * @return {TestNode} The next node in the test tree or null if the end is reached.
676 _next : function () {
678 if (this._cur.firstChild) {
679 this._cur = this._cur.firstChild;
680 } else if (this._cur.next) {
681 this._cur = this._cur.next;
683 while (this._cur && !this._cur.next && this._cur !== this._root){
684 this._handleTestObjectComplete(this._cur);
685 this._cur = this._cur.parent;
688 if (this._cur == this._root){
689 this._cur.results.type = "report";
690 this._cur.results.timestamp = (new Date()).toLocaleString();
691 this._cur.results.duration = (new Date()) - this._cur.results.duration;
692 this.fire(this.COMPLETE_EVENT, { results: this._cur.results});
695 this._handleTestObjectComplete(this._cur);
696 this._cur = this._cur.next;
704 * Runs a test case or test suite, returning the results.
705 * @param {Y.Test.Case|Y.Test.Suite} testObject The test case or test suite to run.
706 * @return {Object} Results of the execution with properties passed, failed, and total.
713 //flag to indicate if the TestRunner should wait before continuing
714 var shouldWait = false;
716 //get the next test node
717 var node = this._next();
720 var testObject = node.testObject;
722 //figure out what to do
723 if (Y.Lang.isObject(testObject)){
724 if (testObject instanceof Y.Test.Suite){
725 this.fire(this.TEST_SUITE_BEGIN_EVENT, { testSuite: testObject });
727 } else if (testObject instanceof Y.Test.Case){
728 this.fire(this.TEST_CASE_BEGIN_EVENT, { testCase: testObject });
731 //some environments don't support setTimeout
732 if (typeof setTimeout != "undefined"){
733 setTimeout(function(){
734 Y.Test.Runner._run();
746 _resumeTest : function (segment) {
748 //get relevant information
749 var node = this._cur;
751 //we know there's no more waiting now
752 this._waiting = false;
754 //if there's no node, it probably means a wait() was called after resume()
756 //TODO: Handle in some way?
757 //console.log("wait() called after resume()");
758 //this.fire("error", { testCase: "(unknown)", test: "(unknown)", error: new Error("wait() called after resume()")} );
762 var testName = node.testObject;
763 var testCase /*:Y.Test.Case*/ = node.parent.testObject;
765 //cancel other waits if available
766 if (testCase.__yui_wait){
767 clearTimeout(testCase.__yui_wait);
768 delete testCase.__yui_wait;
771 //get the "should" test cases
772 var shouldFail = (testCase._should.fail || {})[testName];
773 var shouldError = (testCase._should.error || {})[testName];
775 //variable to hold whether or not the test failed
783 segment.apply(testCase);
785 //if it should fail, and it got here, then it's a fail because it didn't
787 error = new Y.Assert.ShouldFail();
789 } else if (shouldError){
790 error = new Y.Assert.ShouldError();
796 //cancel any pending waits, the test already failed
797 if (testCase.__yui_wait){
798 clearTimeout(testCase.__yui_wait);
799 delete testCase.__yui_wait;
802 //figure out what type of error it was
803 if (thrown instanceof Y.Assert.Error) {
808 } else if (thrown instanceof Y.Test.Wait){
810 if (Y.Lang.isFunction(thrown.segment)){
811 if (Y.Lang.isNumber(thrown.delay)){
813 //some environments don't support setTimeout
814 if (typeof setTimeout != "undefined"){
815 testCase.__yui_wait = setTimeout(function(){
816 Y.Test.Runner._resumeTest(thrown.segment);
818 this._waiting = true;
820 throw new Error("Asynchronous tests not supported in this environment.");
828 //first check to see if it should error
830 error = new Y.Assert.UnexpectedError(thrown);
833 //check to see what type of data we have
834 if (Y.Lang.isString(shouldError)){
836 //if it's a string, check the error message
837 if (thrown.message != shouldError){
838 error = new Y.Assert.UnexpectedError(thrown);
841 } else if (Y.Lang.isFunction(shouldError)){
843 //if it's a function, see if the error is an instance of it
844 if (!(thrown instanceof shouldError)){
845 error = new Y.Assert.UnexpectedError(thrown);
849 } else if (Y.Lang.isObject(shouldError)){
851 //if it's an object, check the instance and message
852 if (!(thrown instanceof shouldError.constructor) ||
853 thrown.message != shouldError.message){
854 error = new Y.Assert.UnexpectedError(thrown);
865 //fire appropriate event
867 this.fire(this.TEST_FAIL_EVENT, { testCase: testCase, testName: testName, error: error });
869 this.fire(this.TEST_PASS_EVENT, { testCase: testCase, testName: testName });
876 node.parent.results[testName] = {
877 result: failed ? "fail" : "pass",
878 message: error ? error.getMessage() : "Test passed",
884 node.parent.results.failed++;
886 node.parent.results.passed++;
888 node.parent.results.total++;
890 //set timeout not supported in all environments
891 if (typeof setTimeout != "undefined"){
892 setTimeout(function(){
893 Y.Test.Runner._run();
902 * Handles an error as if it occurred within the currently executing
903 * test. This is for mock methods that may be called asynchronously
904 * and therefore out of the scope of the TestRunner. Previously, this
905 * error would bubble up to the browser. Now, this method is used
906 * to tell TestRunner about the error. This should never be called
907 * by anyplace other than the Mock object.
908 * @param {Error} error The error object.
910 * @method _handleError
914 _handleError: function(error){
917 this._resumeTest(function(){
927 * Runs a single test based on the data provided in the node.
928 * @param {TestNode} node The TestNode representing the test to run.
934 _runTest : function (node) {
936 //get relevant information
937 var testName = node.testObject;
938 var testCase /*:Y.Test.Case*/ = node.parent.testObject;
939 var test = testCase[testName];
941 //get the "should" test cases
942 var shouldIgnore = (testCase._should.ignore || {})[testName];
944 //figure out if the test should be ignored or not
948 node.parent.results[testName] = {
950 message: "Test ignored",
955 node.parent.results.ignored++;
956 node.parent.results.total++;
958 this.fire(this.TEST_IGNORE_EVENT, { testCase: testCase, testName: testName });
960 //some environments don't support setTimeout
961 if (typeof setTimeout != "undefined"){
962 setTimeout(function(){
963 Y.Test.Runner._run();
974 //now call the body of the test
975 this._resumeTest(test);
980 //-------------------------------------------------------------------------
982 //-------------------------------------------------------------------------
985 * Fires events for the TestRunner. This overrides the default fire()
986 * method from EventProvider to add the type property to the data that is
987 * passed through on each event call.
988 * @param {String} type The type of event to fire.
989 * @param {Object} data (Optional) Data for the event.
994 fire : function (type, data) {
997 TestRunner.superclass.fire.call(this, type, data);
1000 //-------------------------------------------------------------------------
1002 //-------------------------------------------------------------------------
1005 * Adds a test suite or test case to the list of test objects to run.
1006 * @param testObject Either a TestCase or a TestSuite that should be run.
1011 add : function (testObject) {
1012 this.masterSuite.add(testObject);
1017 * Removes all test objects from the runner.
1022 clear : function () {
1023 this.masterSuite.items = [];
1027 * Indicates if the TestRunner is waiting for a test to resume
1028 * @return {Boolean} True if the TestRunner is waiting, false if not.
1032 isWaiting: function() {
1033 return this._waiting;
1037 * Resumes the TestRunner after wait() was called.
1038 * @param {Function} segment The function to run as the rest
1039 * of the haulted test.
1044 resume : function (segment) {
1045 this._resumeTest(segment || function(){});
1049 * Runs the test suite.
1054 run : function (testObject) {
1056 //pointer to runner to avoid scope issues
1057 var runner = Y.Test.Runner;
1059 //build the test tree
1060 runner._buildTestTree();
1062 //set when the test started
1063 runner._root.results.duration = (new Date()).valueOf();
1065 //fire the begin event
1066 runner.fire(runner.BEGIN_EVENT);
1073 return new TestRunner();
1079 * The Assert object provides functions to test JavaScript values against
1080 * known and expected results. Whenever a comparison (assertion) fails,
1081 * an error is thrown.
1089 * The number of assertions performed.
1090 * @property _asserts
1096 //-------------------------------------------------------------------------
1098 //-------------------------------------------------------------------------
1101 * Formats a message so that it can contain the original assertion message
1102 * in addition to the custom message.
1103 * @param {String} customMessage The message passed in by the developer.
1104 * @param {String} defaultMessage The message created by the error by default.
1105 * @return {String} The final error message, containing either or both.
1108 * @method _formatMessage
1110 _formatMessage : function (customMessage, defaultMessage) {
1111 var message = customMessage;
1112 if (Y.Lang.isString(customMessage) && customMessage.length > 0){
1113 return Y.Lang.substitute(customMessage, { message: defaultMessage });
1115 return defaultMessage;
1120 * Returns the number of assertions that have been performed.
1125 _getCount: function(){
1126 return this._asserts;
1130 * Increments the number of assertions that have been performed.
1131 * @method _increment
1135 _increment: function(){
1140 * Resets the number of assertions that have been performed to 0.
1149 //-------------------------------------------------------------------------
1150 // Generic Assertion Methods
1151 //-------------------------------------------------------------------------
1154 * Forces an assertion error to occur.
1155 * @param {String} message (Optional) The message to display with the failure.
1159 fail : function (message) {
1160 throw new Y.Assert.Error(Y.Assert._formatMessage(message, "Test force-failed."));
1163 //-------------------------------------------------------------------------
1164 // Equality Assertion Methods
1165 //-------------------------------------------------------------------------
1168 * Asserts that a value is equal to another. This uses the double equals sign
1169 * so type cohersion may occur.
1170 * @param {Object} expected The expected value.
1171 * @param {Object} actual The actual value to test.
1172 * @param {String} message (Optional) The message to display if the assertion fails.
1176 areEqual : function (expected, actual, message) {
1177 Y.Assert._increment();
1178 if (expected != actual) {
1179 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values should be equal."), expected, actual);
1184 * Asserts that a value is not equal to another. This uses the double equals sign
1185 * so type cohersion may occur.
1186 * @param {Object} unexpected The unexpected value.
1187 * @param {Object} actual The actual value to test.
1188 * @param {String} message (Optional) The message to display if the assertion fails.
1189 * @method areNotEqual
1192 areNotEqual : function (unexpected, actual,
1194 Y.Assert._increment();
1195 if (unexpected == actual) {
1196 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be equal."), unexpected);
1201 * Asserts that a value is not the same as another. This uses the triple equals sign
1202 * so no type cohersion may occur.
1203 * @param {Object} unexpected The unexpected value.
1204 * @param {Object} actual The actual value to test.
1205 * @param {String} message (Optional) The message to display if the assertion fails.
1206 * @method areNotSame
1209 areNotSame : function (unexpected, actual, message) {
1210 Y.Assert._increment();
1211 if (unexpected === actual) {
1212 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be the same."), unexpected);
1217 * Asserts that a value is the same as another. This uses the triple equals sign
1218 * so no type cohersion may occur.
1219 * @param {Object} expected The expected value.
1220 * @param {Object} actual The actual value to test.
1221 * @param {String} message (Optional) The message to display if the assertion fails.
1225 areSame : function (expected, actual, message) {
1226 Y.Assert._increment();
1227 if (expected !== actual) {
1228 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values should be the same."), expected, actual);
1232 //-------------------------------------------------------------------------
1233 // Boolean Assertion Methods
1234 //-------------------------------------------------------------------------
1237 * Asserts that a value is false. This uses the triple equals sign
1238 * so no type cohersion may occur.
1239 * @param {Object} actual The actual value to test.
1240 * @param {String} message (Optional) The message to display if the assertion fails.
1244 isFalse : function (actual, message) {
1245 Y.Assert._increment();
1246 if (false !== actual) {
1247 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be false."), false, actual);
1252 * Asserts that a value is true. This uses the triple equals sign
1253 * so no type cohersion may occur.
1254 * @param {Object} actual The actual value to test.
1255 * @param {String} message (Optional) The message to display if the assertion fails.
1259 isTrue : function (actual, message) {
1260 Y.Assert._increment();
1261 if (true !== actual) {
1262 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be true."), true, actual);
1267 //-------------------------------------------------------------------------
1268 // Special Value Assertion Methods
1269 //-------------------------------------------------------------------------
1272 * Asserts that a value is not a number.
1273 * @param {Object} actual The value to test.
1274 * @param {String} message (Optional) The message to display if the assertion fails.
1278 isNaN : function (actual, message){
1279 Y.Assert._increment();
1280 if (!isNaN(actual)){
1281 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be NaN."), NaN, actual);
1286 * Asserts that a value is not the special NaN value.
1287 * @param {Object} actual The value to test.
1288 * @param {String} message (Optional) The message to display if the assertion fails.
1292 isNotNaN : function (actual, message){
1293 Y.Assert._increment();
1295 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be NaN."), NaN);
1300 * Asserts that a value is not null. This uses the triple equals sign
1301 * so no type cohersion may occur.
1302 * @param {Object} actual The actual value to test.
1303 * @param {String} message (Optional) The message to display if the assertion fails.
1307 isNotNull : function (actual, message) {
1308 Y.Assert._increment();
1309 if (Y.Lang.isNull(actual)) {
1310 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be null."), null);
1315 * Asserts that a value is not undefined. This uses the triple equals sign
1316 * so no type cohersion may occur.
1317 * @param {Object} actual The actual value to test.
1318 * @param {String} message (Optional) The message to display if the assertion fails.
1319 * @method isNotUndefined
1322 isNotUndefined : function (actual, message) {
1323 Y.Assert._increment();
1324 if (Y.Lang.isUndefined(actual)) {
1325 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should not be undefined."), undefined);
1330 * Asserts that a value is null. This uses the triple equals sign
1331 * so no type cohersion may occur.
1332 * @param {Object} actual The actual value to test.
1333 * @param {String} message (Optional) The message to display if the assertion fails.
1337 isNull : function (actual, message) {
1338 Y.Assert._increment();
1339 if (!Y.Lang.isNull(actual)) {
1340 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be null."), null, actual);
1345 * Asserts that a value is undefined. This uses the triple equals sign
1346 * so no type cohersion may occur.
1347 * @param {Object} actual The actual value to test.
1348 * @param {String} message (Optional) The message to display if the assertion fails.
1349 * @method isUndefined
1352 isUndefined : function (actual, message) {
1353 Y.Assert._increment();
1354 if (!Y.Lang.isUndefined(actual)) {
1355 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be undefined."), undefined, actual);
1359 //--------------------------------------------------------------------------
1360 // Instance Assertion Methods
1361 //--------------------------------------------------------------------------
1364 * Asserts that a value is an array.
1365 * @param {Object} actual The value to test.
1366 * @param {String} message (Optional) The message to display if the assertion fails.
1370 isArray : function (actual, message) {
1371 Y.Assert._increment();
1372 if (!Y.Lang.isArray(actual)){
1373 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be an array."), actual);
1378 * Asserts that a value is a Boolean.
1379 * @param {Object} actual The value to test.
1380 * @param {String} message (Optional) The message to display if the assertion fails.
1384 isBoolean : function (actual, message) {
1385 Y.Assert._increment();
1386 if (!Y.Lang.isBoolean(actual)){
1387 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a Boolean."), actual);
1392 * Asserts that a value is a function.
1393 * @param {Object} actual The value to test.
1394 * @param {String} message (Optional) The message to display if the assertion fails.
1395 * @method isFunction
1398 isFunction : function (actual, message) {
1399 Y.Assert._increment();
1400 if (!Y.Lang.isFunction(actual)){
1401 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a function."), actual);
1406 * Asserts that a value is an instance of a particular object. This may return
1407 * incorrect results when comparing objects from one frame to constructors in
1408 * another frame. For best results, don't use in a cross-frame manner.
1409 * @param {Function} expected The function that the object should be an instance of.
1410 * @param {Object} actual The object to test.
1411 * @param {String} message (Optional) The message to display if the assertion fails.
1412 * @method isInstanceOf
1415 isInstanceOf : function (expected, actual, message) {
1416 Y.Assert._increment();
1417 if (!(actual instanceof expected)){
1418 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value isn't an instance of expected type."), expected, actual);
1423 * Asserts that a value is a number.
1424 * @param {Object} actual The value to test.
1425 * @param {String} message (Optional) The message to display if the assertion fails.
1429 isNumber : function (actual, message) {
1430 Y.Assert._increment();
1431 if (!Y.Lang.isNumber(actual)){
1432 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a number."), actual);
1437 * Asserts that a value is an object.
1438 * @param {Object} actual The value to test.
1439 * @param {String} message (Optional) The message to display if the assertion fails.
1443 isObject : function (actual, message) {
1444 Y.Assert._increment();
1445 if (!Y.Lang.isObject(actual)){
1446 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be an object."), actual);
1451 * Asserts that a value is a string.
1452 * @param {Object} actual The value to test.
1453 * @param {String} message (Optional) The message to display if the assertion fails.
1457 isString : function (actual, message) {
1458 Y.Assert._increment();
1459 if (!Y.Lang.isString(actual)){
1460 throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a string."), actual);
1465 * Asserts that a value is of a particular type.
1466 * @param {String} expectedType The expected type of the variable.
1467 * @param {Object} actualValue The actual value to test.
1468 * @param {String} message (Optional) The message to display if the assertion fails.
1472 isTypeOf : function (expectedType, actualValue, message){
1473 Y.Assert._increment();
1474 if (typeof actualValue != expectedType){
1475 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be of type " + expectedType + "."), expected, typeof actualValue);
1481 * Asserts that a given condition is true. If not, then a Y.Assert.Error object is thrown
1482 * and the test fails.
1484 * @param {Boolean} condition The condition to test.
1485 * @param {String} message The message to display if the assertion fails.
1488 Y.assert = function(condition, message){
1489 Y.Assert._increment();
1491 throw new Y.Assert.Error(Y.Assert._formatMessage(message, "Assertion failed."));
1496 * Forces an assertion error to occur. Shortcut for Y.Assert.fail().
1498 * @param {String} message (Optional) The message to display with the failure.
1501 Y.fail = Y.Assert.fail;
1503 //-----------------------------------------------------------------------------
1505 //-----------------------------------------------------------------------------
1508 * Error is thrown whenever an assertion fails. It provides methods
1509 * to more easily get at error information and also provides a base class
1510 * from which more specific assertion errors can be derived.
1512 * @param {String} message The message to display when the error occurs.
1517 Y.Assert.Error = function (message){
1520 arguments.callee.superclass.constructor.call(this, message);
1523 * Error message. Must be duplicated to ensure browser receives it.
1527 this.message = message;
1530 * The name of the error that occurred.
1534 this.name = "Assert Error";
1538 Y.extend(Y.Assert.Error, Error, {
1541 * Returns a fully formatted error for an assertion failure. This should
1542 * be overridden by all subclasses to provide specific information.
1543 * @method getMessage
1544 * @return {String} A string describing the error.
1546 getMessage : function () {
1547 return this.message;
1551 * Returns a string representation of the error.
1553 * @return {String} A string representation of the error.
1555 toString : function () {
1556 return this.name + ": " + this.getMessage();
1560 * Returns a primitive value version of the error. Same as toString().
1562 * @return {String} A primitive value version of the error.
1564 valueOf : function () {
1565 return this.toString();
1571 * ComparisonFailure is subclass of Error that is thrown whenever
1572 * a comparison between two values fails. It provides mechanisms to retrieve
1573 * both the expected and actual value.
1575 * @param {String} message The message to display when the error occurs.
1576 * @param {Object} expected The expected value.
1577 * @param {Object} actual The actual value that caused the assertion to fail.
1579 * @extends Assert.Error
1580 * @class ComparisonFailure
1583 Y.Assert.ComparisonFailure = function (message, expected, actual){
1586 arguments.callee.superclass.constructor.call(this, message);
1589 * The expected value.
1591 * @property expected
1593 this.expected = expected;
1600 this.actual = actual;
1603 * The name of the error that occurred.
1607 this.name = "ComparisonFailure";
1612 Y.extend(Y.Assert.ComparisonFailure, Y.Assert.Error, {
1615 * Returns a fully formatted error for an assertion failure. This message
1616 * provides information about the expected and actual values.
1618 * @return {String} A string describing the error.
1620 getMessage : function () {
1621 return this.message + "\nExpected: " + this.expected + " (" + (typeof this.expected) + ")" +
1622 "\nActual: " + this.actual + " (" + (typeof this.actual) + ")";
1628 * UnexpectedValue is subclass of Error that is thrown whenever
1629 * a value was unexpected in its scope. This typically means that a test
1630 * was performed to determine that a value was *not* equal to a certain
1633 * @param {String} message The message to display when the error occurs.
1634 * @param {Object} unexpected The unexpected value.
1636 * @extends Assert.Error
1637 * @class UnexpectedValue
1640 Y.Assert.UnexpectedValue = function (message, unexpected){
1643 arguments.callee.superclass.constructor.call(this, message);
1646 * The unexpected value.
1648 * @property unexpected
1650 this.unexpected = unexpected;
1653 * The name of the error that occurred.
1657 this.name = "UnexpectedValue";
1662 Y.extend(Y.Assert.UnexpectedValue, Y.Assert.Error, {
1665 * Returns a fully formatted error for an assertion failure. The message
1666 * contains information about the unexpected value that was encountered.
1667 * @method getMessage
1668 * @return {String} A string describing the error.
1670 getMessage : function () {
1671 return this.message + "\nUnexpected: " + this.unexpected + " (" + (typeof this.unexpected) + ") ";
1677 * ShouldFail is subclass of Error that is thrown whenever
1678 * a test was expected to fail but did not.
1680 * @param {String} message The message to display when the error occurs.
1682 * @extends Assert.Error
1686 Y.Assert.ShouldFail = function (message){
1689 arguments.callee.superclass.constructor.call(this, message || "This test should fail but didn't.");
1692 * The name of the error that occurred.
1696 this.name = "ShouldFail";
1701 Y.extend(Y.Assert.ShouldFail, Y.Assert.Error);
1704 * ShouldError is subclass of Error that is thrown whenever
1705 * a test is expected to throw an error but doesn't.
1707 * @param {String} message The message to display when the error occurs.
1709 * @extends Assert.Error
1710 * @class ShouldError
1713 Y.Assert.ShouldError = function (message){
1716 arguments.callee.superclass.constructor.call(this, message || "This test should have thrown an error but didn't.");
1719 * The name of the error that occurred.
1723 this.name = "ShouldError";
1728 Y.extend(Y.Assert.ShouldError, Y.Assert.Error);
1731 * UnexpectedError is subclass of Error that is thrown whenever
1732 * an error occurs within the course of a test and the test was not expected
1733 * to throw an error.
1735 * @param {Error} cause The unexpected error that caused this error to be
1738 * @extends Assert.Error
1739 * @class UnexpectedError
1742 Y.Assert.UnexpectedError = function (cause){
1745 arguments.callee.superclass.constructor.call(this, "Unexpected error: " + cause.message);
1748 * The unexpected error that occurred.
1755 * The name of the error that occurred.
1759 this.name = "UnexpectedError";
1762 * Stack information for the error (if provided).
1766 this.stack = cause.stack;
1771 Y.extend(Y.Assert.UnexpectedError, Y.Assert.Error);
1776 * The ArrayAssert object provides functions to test JavaScript array objects
1777 * for a variety of cases.
1779 * @class ArrayAssert
1786 * Asserts that a value is present in an array. This uses the triple equals
1787 * sign so no type cohersion may occur.
1788 * @param {Object} needle The value that is expected in the array.
1789 * @param {Array} haystack An array of values.
1790 * @param {String} message (Optional) The message to display if the assertion fails.
1794 contains : function (needle, haystack,
1797 Y.Assert._increment();
1799 if (Y.Array.indexOf(haystack, needle) == -1){
1800 Y.Assert.fail(Y.Assert._formatMessage(message, "Value " + needle + " (" + (typeof needle) + ") not found in array [" + haystack + "]."));
1805 * Asserts that a set of values are present in an array. This uses the triple equals
1806 * sign so no type cohersion may occur. For this assertion to pass, all values must
1808 * @param {Object[]} needles An array of values that are expected in the array.
1809 * @param {Array} haystack An array of values to check.
1810 * @param {String} message (Optional) The message to display if the assertion fails.
1811 * @method containsItems
1814 containsItems : function (needles, haystack,
1816 Y.Assert._increment();
1818 //begin checking values
1819 for (var i=0; i < needles.length; i++){
1820 if (Y.Array.indexOf(haystack, needles[i]) == -1){
1821 Y.Assert.fail(Y.Assert._formatMessage(message, "Value " + needles[i] + " (" + (typeof needles[i]) + ") not found in array [" + haystack + "]."));
1827 * Asserts that a value matching some condition is present in an array. This uses
1828 * a function to determine a match.
1829 * @param {Function} matcher A function that returns true if the items matches or false if not.
1830 * @param {Array} haystack An array of values.
1831 * @param {String} message (Optional) The message to display if the assertion fails.
1832 * @method containsMatch
1835 containsMatch : function (matcher, haystack,
1838 Y.Assert._increment();
1839 //check for valid matcher
1840 if (typeof matcher != "function"){
1841 throw new TypeError("ArrayAssert.containsMatch(): First argument must be a function.");
1844 if (!Y.Array.some(haystack, matcher)){
1845 Y.Assert.fail(Y.Assert._formatMessage(message, "No match found in array [" + haystack + "]."));
1850 * Asserts that a value is not present in an array. This uses the triple equals
1851 * Asserts that a value is not present in an array. This uses the triple equals
1852 * sign so no type cohersion may occur.
1853 * @param {Object} needle The value that is expected in the array.
1854 * @param {Array} haystack An array of values.
1855 * @param {String} message (Optional) The message to display if the assertion fails.
1856 * @method doesNotContain
1859 doesNotContain : function (needle, haystack,
1862 Y.Assert._increment();
1864 if (Y.Array.indexOf(haystack, needle) > -1){
1865 Y.Assert.fail(Y.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
1870 * Asserts that a set of values are not present in an array. This uses the triple equals
1871 * sign so no type cohersion may occur. For this assertion to pass, all values must
1873 * @param {Object[]} needles An array of values that are not expected in the array.
1874 * @param {Array} haystack An array of values to check.
1875 * @param {String} message (Optional) The message to display if the assertion fails.
1876 * @method doesNotContainItems
1879 doesNotContainItems : function (needles, haystack,
1882 Y.Assert._increment();
1884 for (var i=0; i < needles.length; i++){
1885 if (Y.Array.indexOf(haystack, needles[i]) > -1){
1886 Y.Assert.fail(Y.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
1893 * Asserts that no values matching a condition are present in an array. This uses
1894 * a function to determine a match.
1895 * @param {Function} matcher A function that returns true if the items matches or false if not.
1896 * @param {Array} haystack An array of values.
1897 * @param {String} message (Optional) The message to display if the assertion fails.
1898 * @method doesNotContainMatch
1901 doesNotContainMatch : function (matcher, haystack,
1904 Y.Assert._increment();
1906 //check for valid matcher
1907 if (typeof matcher != "function"){
1908 throw new TypeError("ArrayAssert.doesNotContainMatch(): First argument must be a function.");
1911 if (Y.Array.some(haystack, matcher)){
1912 Y.Assert.fail(Y.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
1917 * Asserts that the given value is contained in an array at the specified index.
1918 * This uses the triple equals sign so no type cohersion will occur.
1919 * @param {Object} needle The value to look for.
1920 * @param {Array} haystack The array to search in.
1921 * @param {int} index The index at which the value should exist.
1922 * @param {String} message (Optional) The message to display if the assertion fails.
1926 indexOf : function (needle, haystack, index, message) {
1928 Y.Assert._increment();
1930 //try to find the value in the array
1931 for (var i=0; i < haystack.length; i++){
1932 if (haystack[i] === needle){
1934 Y.Assert.fail(Y.Assert._formatMessage(message, "Value exists at index " + i + " but should be at index " + index + "."));
1940 //if it makes it here, it wasn't found at all
1941 Y.Assert.fail(Y.Assert._formatMessage(message, "Value doesn't exist in array [" + haystack + "]."));
1945 * Asserts that the values in an array are equal, and in the same position,
1946 * as values in another array. This uses the double equals sign
1947 * so type cohersion may occur. Note that the array objects themselves
1948 * need not be the same for this test to pass.
1949 * @param {Array} expected An array of the expected values.
1950 * @param {Array} actual Any array of the actual values.
1951 * @param {String} message (Optional) The message to display if the assertion fails.
1952 * @method itemsAreEqual
1955 itemsAreEqual : function (expected, actual,
1958 Y.Assert._increment();
1960 //first check array length
1961 if (expected.length != actual.length){
1962 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
1965 //begin checking values
1966 for (var i=0; i < expected.length; i++){
1967 if (expected[i] != actual[i]){
1968 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values in position " + i + " are not equal."), expected[i], actual[i]);
1974 * Asserts that the values in an array are equivalent, and in the same position,
1975 * as values in another array. This uses a function to determine if the values
1976 * are equivalent. Note that the array objects themselves
1977 * need not be the same for this test to pass.
1978 * @param {Array} expected An array of the expected values.
1979 * @param {Array} actual Any array of the actual values.
1980 * @param {Function} comparator A function that returns true if the values are equivalent
1982 * @param {String} message (Optional) The message to display if the assertion fails.
1984 * @method itemsAreEquivalent
1987 itemsAreEquivalent : function (expected, actual,
1988 comparator, message) {
1990 Y.Assert._increment();
1992 //make sure the comparator is valid
1993 if (typeof comparator != "function"){
1994 throw new TypeError("ArrayAssert.itemsAreEquivalent(): Third argument must be a function.");
1997 //first check array length
1998 if (expected.length != actual.length){
1999 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
2002 //begin checking values
2003 for (var i=0; i < expected.length; i++){
2004 if (!comparator(expected[i], actual[i])){
2005 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values in position " + i + " are not equivalent."), expected[i], actual[i]);
2011 * Asserts that an array is empty.
2012 * @param {Array} actual The array to test.
2013 * @param {String} message (Optional) The message to display if the assertion fails.
2017 isEmpty : function (actual, message) {
2018 Y.Assert._increment();
2019 if (actual.length > 0){
2020 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should be empty."));
2025 * Asserts that an array is not empty.
2026 * @param {Array} actual The array to test.
2027 * @param {String} message (Optional) The message to display if the assertion fails.
2028 * @method isNotEmpty
2031 isNotEmpty : function (actual, message) {
2032 Y.Assert._increment();
2033 if (actual.length === 0){
2034 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should not be empty."));
2039 * Asserts that the values in an array are the same, and in the same position,
2040 * as values in another array. This uses the triple equals sign
2041 * so no type cohersion will occur. Note that the array objects themselves
2042 * need not be the same for this test to pass.
2043 * @param {Array} expected An array of the expected values.
2044 * @param {Array} actual Any array of the actual values.
2045 * @param {String} message (Optional) The message to display if the assertion fails.
2046 * @method itemsAreSame
2049 itemsAreSame : function (expected, actual,
2052 Y.Assert._increment();
2054 //first check array length
2055 if (expected.length != actual.length){
2056 Y.Assert.fail(Y.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
2059 //begin checking values
2060 for (var i=0; i < expected.length; i++){
2061 if (expected[i] !== actual[i]){
2062 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values in position " + i + " are not the same."), expected[i], actual[i]);
2068 * Asserts that the given value is contained in an array at the specified index,
2069 * starting from the back of the array.
2070 * This uses the triple equals sign so no type cohersion will occur.
2071 * @param {Object} needle The value to look for.
2072 * @param {Array} haystack The array to search in.
2073 * @param {int} index The index at which the value should exist.
2074 * @param {String} message (Optional) The message to display if the assertion fails.
2075 * @method lastIndexOf
2078 lastIndexOf : function (needle, haystack, index, message) {
2080 //try to find the value in the array
2081 for (var i=haystack.length; i >= 0; i--){
2082 if (haystack[i] === needle){
2084 Y.Assert.fail(Y.Assert._formatMessage(message, "Value exists at index " + i + " but should be at index " + index + "."));
2090 //if it makes it here, it wasn't found at all
2091 Y.Assert.fail(Y.Assert._formatMessage(message, "Value doesn't exist in array."));
2098 * The ObjectAssert object provides functions to test JavaScript objects
2099 * for a variety of cases.
2101 * @class ObjectAssert
2106 areEqual: function(expected, actual, message) {
2107 Y.Assert._increment();
2108 Y.Object.each(expected, function(value, name){
2109 if (expected[name] != actual[name]){
2110 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values should be equal for property " + name), expected[name], actual[name]);
2116 * Asserts that an object has a property with the given name.
2117 * @param {String} propertyName The name of the property to test.
2118 * @param {Object} object The object to search.
2119 * @param {String} message (Optional) The message to display if the assertion fails.
2123 hasKey: function (propertyName, object, message) {
2124 Y.Assert._increment();
2125 if (!Y.Object.hasKey(object, propertyName)){
2126 Y.fail(Y.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object."));
2131 * Asserts that an object has all properties of a reference object.
2132 * @param {Array} properties An array of property names that should be on the object.
2133 * @param {Object} object The object to search.
2134 * @param {String} message (Optional) The message to display if the assertion fails.
2138 hasKeys: function (properties, object, message) {
2139 Y.Assert._increment();
2140 for (var i=0; i < properties.length; i++){
2141 if (!Y.Object.hasKey(object, properties[i])){
2142 Y.fail(Y.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object."));
2148 * Asserts that a property with the given name exists on an object instance (not on its prototype).
2149 * @param {String} propertyName The name of the property to test.
2150 * @param {Object} object The object to search.
2151 * @param {String} message (Optional) The message to display if the assertion fails.
2155 ownsKey: function (propertyName, object, message) {
2156 Y.Assert._increment();
2157 if (!object.hasOwnProperty(propertyName)){
2158 Y.fail(Y.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object instance."));
2163 * Asserts that all properties exist on an object instance (not on its prototype).
2164 * @param {Array} properties An array of property names that should be on the object.
2165 * @param {Object} object The object to search.
2166 * @param {String} message (Optional) The message to display if the assertion fails.
2170 ownsKeys: function (properties, object, message) {
2171 Y.Assert._increment();
2172 for (var i=0; i < properties.length; i++){
2173 if (!object.hasOwnProperty(properties[i])){
2174 Y.fail(Y.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object instance."));
2180 * Asserts that an object owns no properties.
2181 * @param {Object} object The object to check.
2182 * @param {String} message (Optional) The message to display if the assertion fails.
2183 * @method ownsNoKeys
2186 ownsNoKeys : function (object, message) {
2187 Y.Assert._increment();
2189 var keys = Y.Object.keys(object);
2191 if (keys.length > 0){
2192 Y.fail(Y.Assert._formatMessage(message, "Object owns " + keys.length + " properties but should own none."));
2201 * The DateAssert object provides functions to test JavaScript Date objects
2202 * for a variety of cases.
2211 * Asserts that a date's month, day, and year are equal to another date's.
2212 * @param {Date} expected The expected date.
2213 * @param {Date} actual The actual date to test.
2214 * @param {String} message (Optional) The message to display if the assertion fails.
2215 * @method datesAreEqual
2218 datesAreEqual : function (expected, actual, message){
2219 Y.Assert._increment();
2220 if (expected instanceof Date && actual instanceof Date){
2224 if (expected.getFullYear() != actual.getFullYear()){
2225 msg = "Years should be equal.";
2229 if (expected.getMonth() != actual.getMonth()){
2230 msg = "Months should be equal.";
2233 //last, check the day of the month
2234 if (expected.getDate() != actual.getDate()){
2235 msg = "Days of month should be equal.";
2239 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, msg), expected, actual);
2242 throw new TypeError("Y.Assert.datesAreEqual(): Expected and actual values must be Date objects.");
2247 * Asserts that a date's hour, minutes, and seconds are equal to another date's.
2248 * @param {Date} expected The expected date.
2249 * @param {Date} actual The actual date to test.
2250 * @param {String} message (Optional) The message to display if the assertion fails.
2251 * @method timesAreEqual
2254 timesAreEqual : function (expected, actual, message){
2255 Y.Assert._increment();
2256 if (expected instanceof Date && actual instanceof Date){
2260 if (expected.getHours() != actual.getHours()){
2261 msg = "Hours should be equal.";
2265 if (expected.getMinutes() != actual.getMinutes()){
2266 msg = "Minutes should be equal.";
2269 //last, check the seconds
2270 if (expected.getSeconds() != actual.getSeconds()){
2271 msg = "Seconds should be equal.";
2275 throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, msg), expected, actual);
2278 throw new TypeError("DateY.AsserttimesAreEqual(): Expected and actual values must be Date objects.");
2285 Y.namespace("Test.Format");
2287 /* (intentionally not documented)
2288 * Basic XML escaping method. Replaces quotes, less-than, greater-than,
2289 * apostrophe, and ampersand characters with their corresponding entities.
2290 * @param {String} text The text to encode.
2291 * @return {String} The XML-escaped text.
2293 function xmlEscape(text){
2295 return text.replace(/[<>"'&]/g, function(value){
2297 case "<": return "<";
2298 case ">": return ">";
2299 case "\"": return """;
2300 case "'": return "'";
2301 case "&": return "&";
2308 * Returns test results formatted as a JSON string. Requires JSON utility.
2309 * @param {Object} result The results object created by TestRunner.
2310 * @return {String} A JSON-formatted string of results.
2311 * @namespace Test.Format
2315 Y.Test.Format.JSON = function(results) {
2316 return Y.JSON.stringify(results);
2320 * Returns test results formatted as an XML string.
2321 * @param {Object} result The results object created by TestRunner.
2322 * @return {String} An XML-formatted string of results.
2323 * @namespace Test.Format
2327 Y.Test.Format.XML = function(results) {
2330 var xml = "<" + results.type + " name=\"" + xmlEscape(results.name) + "\"";
2332 if (results.type == "test"){
2333 xml += " result=\"" + xmlEscape(results.result) + "\" message=\"" + xmlEscape(results.message) + "\">";
2335 xml += " passed=\"" + results.passed + "\" failed=\"" + results.failed + "\" ignored=\"" + results.ignored + "\" total=\"" + results.total + "\">";
2336 Y.Object.each(results, function(value, prop){
2337 if (l.isObject(value) && !l.isArray(value)){
2338 xml += arguments.callee(value);
2343 xml += "</" + results.type + ">";
2350 * Returns test results formatted as an XML string.
2351 * @param {Object} result The results object created by TestRunner.
2352 * @return {String} An XML-formatted string of results.
2353 * @namespace Test.Format
2357 Y.Test.Format.XML = function(results) {
2359 function serializeToXML(results){
2361 xml = "<" + results.type + " name=\"" + xmlEscape(results.name) + "\"";
2363 if (l.isNumber(results.duration)){
2364 xml += " duration=\"" + results.duration + "\"";
2367 if (results.type == "test"){
2368 xml += " result=\"" + results.result + "\" message=\"" + xmlEscape(results.message) + "\">";
2370 xml += " passed=\"" + results.passed + "\" failed=\"" + results.failed + "\" ignored=\"" + results.ignored + "\" total=\"" + results.total + "\">";
2371 Y.Object.each(results, function(value, prop){
2372 if (l.isObject(value) && !l.isArray(value)){
2373 xml += serializeToXML(value);
2378 xml += "</" + results.type + ">";
2383 return "<?xml version=\"1.0\" charset=\"UTF-8\"?>" + serializeToXML(results);
2389 * Returns test results formatted in JUnit XML format.
2390 * @param {Object} result The results object created by TestRunner.
2391 * @return {String} An XML-formatted string of results.
2392 * @namespace Test.Format
2396 Y.Test.Format.JUnitXML = function(results) {
2399 function serializeToJUnitXML(results){
2404 switch (results.type){
2405 //equivalent to testcase in JUnit
2407 if (results.result != "ignore"){
2408 xml = "<testcase name=\"" + xmlEscape(results.name) + "\">";
2409 if (results.result == "fail"){
2410 xml += "<failure message=\"" + xmlEscape(results.message) + "\"><![CDATA[" + results.message + "]]></failure>";
2412 xml+= "</testcase>";
2416 //equivalent to testsuite in JUnit
2419 xml = "<testsuite name=\"" + xmlEscape(results.name) + "\" tests=\"" + results.total + "\" failures=\"" + results.failed + "\">";
2421 Y.Object.each(results, function(value, prop){
2422 if (l.isObject(value) && !l.isArray(value)){
2423 xml += serializeToJUnitXML(value);
2427 xml += "</testsuite>";
2431 Y.Object.each(results, function(value, prop){
2432 if (l.isObject(value) && !l.isArray(value)){
2433 xml += serializeToJUnitXML(value);
2437 //skip output - no JUnit equivalent
2442 xml = "<testsuites>";
2444 Y.Object.each(results, function(value, prop){
2445 if (l.isObject(value) && !l.isArray(value)){
2446 xml += serializeToJUnitXML(value);
2450 xml += "</testsuites>";
2459 return "<?xml version=\"1.0\" charset=\"UTF-8\"?>" + serializeToJUnitXML(results);
2464 Y.namespace("Test");
2467 * An object capable of sending test results to a server.
2468 * @param {String} url The URL to submit the results to.
2469 * @param {Function} format (Optiona) A function that outputs the results in a specific format.
2470 * Default is Y.Test.Format.XML.
2475 Y.Test.Reporter = function(url, format) {
2478 * The URL to submit the data to.
2485 * The formatting function to call when submitting the data.
2489 this.format = format || Y.Test.Format.XML;
2492 * Extra fields to submit with the request.
2497 this._fields = new Object();
2500 * The form element used to submit the results.
2501 * @type HTMLFormElement
2508 * Iframe used as a target for form submission.
2509 * @type HTMLIFrameElement
2513 this._iframe = null;
2516 Y.Test.Reporter.prototype = {
2518 //restore missing constructor
2519 constructor: Y.Test.Reporter,
2522 * Adds a field to the form that submits the results.
2523 * @param {String} name The name of the field.
2524 * @param {Variant} value The value of the field.
2528 addField : function (name, value){
2529 this._fields[name] = value;
2533 * Removes all previous defined fields.
2537 clearFields : function(){
2538 this._fields = new Object();
2542 * Cleans up the memory associated with the TestReporter, removing DOM elements
2543 * that were created.
2547 destroy : function() {
2549 this._form.parentNode.removeChild(this._form);
2553 this._iframe.parentNode.removeChild(this._iframe);
2554 this._iframe = null;
2556 this._fields = null;
2560 * Sends the report to the server.
2561 * @param {Object} results The results object created by TestRunner.
2565 report : function(results){
2567 //if the form hasn't been created yet, create it
2569 this._form = document.createElement("form");
2570 this._form.method = "post";
2571 this._form.style.visibility = "hidden";
2572 this._form.style.position = "absolute";
2573 this._form.style.top = 0;
2574 document.body.appendChild(this._form);
2576 //IE won't let you assign a name using the DOM, must do it the hacky way
2578 this._iframe = document.createElement("<iframe name=\"yuiTestTarget\" />");
2580 this._iframe = document.createElement("iframe");
2581 this._iframe.name = "yuiTestTarget";
2584 this._iframe.src = "javascript:false";
2585 this._iframe.style.visibility = "hidden";
2586 this._iframe.style.position = "absolute";
2587 this._iframe.style.top = 0;
2588 document.body.appendChild(this._iframe);
2590 this._form.target = "yuiTestTarget";
2593 //set the form's action
2594 this._form.action = this.url;
2596 //remove any existing fields
2597 while(this._form.hasChildNodes()){
2598 this._form.removeChild(this._form.lastChild);
2601 //create default fields
2602 this._fields.results = this.format(results);
2603 this._fields.useragent = navigator.userAgent;
2604 this._fields.timestamp = (new Date()).toLocaleString();
2606 //add fields to the form
2607 Y.Object.each(this._fields, function(value, prop){
2608 if (typeof value != "function"){
2609 var input = document.createElement("input");
2610 input.type = "hidden";
2612 input.value = value;
2613 this._form.appendChild(input);
2617 //remove default fields
2618 delete this._fields.results;
2619 delete this._fields.useragent;
2620 delete this._fields.timestamp;
2622 if (arguments[1] !== false){
2623 this._form.submit();
2631 * Creates a new mock object.
2634 * @param {Object} template (Optional) An object whose methods
2635 * should be stubbed out on the mock object.
2637 Y.Mock = function(template){
2639 //use blank object is nothing is passed in
2640 template = template || {};
2644 //try to create mock that keeps prototype chain intact
2646 mock = Y.Object(template);
2649 Y.log("Couldn't create mock with prototype.", "warn", "Mock");
2652 //create new versions of the methods so that they don't actually do anything
2653 Y.Object.each(template, function(name){
2654 if (Y.Lang.isFunction(template[name])){
2655 mock[name] = function(){
2656 Y.Assert.fail("Method " + name + "() was called but was not expected to be.");
2666 * Assigns an expectation to a mock object. This is used to create
2667 * methods and properties on the mock object that are monitored for
2668 * calls and changes, respectively.
2669 * @param {Object} mock The object to add the expectation to.
2670 * @param {Object} expectation An object defining the expectation. For
2671 * a method, the keys "method" and "args" are required with
2672 * an optional "returns" key available. For properties, the keys
2673 * "property" and "value" are required.
2678 Y.Mock.expect = function(mock /*:Object*/, expectation /*:Object*/){
2680 //make sure there's a place to store the expectations
2681 if (!mock.__expectations) {
2682 mock.__expectations = {};
2685 //method expectation
2686 if (expectation.method){
2687 var name = expectation.method,
2688 args = expectation.args || expectation.arguments || [],
2689 result = expectation.returns,
2690 callCount = Y.Lang.isNumber(expectation.callCount) ? expectation.callCount : 1,
2691 error = expectation.error,
2692 run = expectation.run || function(){};
2695 mock.__expectations[name] = expectation;
2696 expectation.callCount = callCount;
2697 expectation.actualCallCount = 0;
2700 Y.Array.each(args, function(arg, i, array){
2701 if (!(array[i] instanceof Y.Mock.Value)){
2702 array[i] = Y.Mock.Value(Y.Assert.areSame, [arg], "Argument " + i + " of " + name + "() is incorrect.");
2706 //if the method is expected to be called
2708 mock[name] = function(){
2710 expectation.actualCallCount++;
2711 Y.Assert.areEqual(args.length, arguments.length, "Method " + name + "() passed incorrect number of arguments.");
2712 for (var i=0, len=args.length; i < len; i++){
2714 args[i].verify(arguments[i]);
2716 // Y.Assert.fail("Argument " + i + " (" + arguments[i] + ") was not expected to be used.");
2721 run.apply(this, arguments);
2727 //route through TestRunner for proper handling
2728 Y.Test.Runner._handleError(ex);
2735 //method should fail if called when not expected
2736 mock[name] = function(){
2738 Y.Assert.fail("Method " + name + "() should not have been called.");
2740 //route through TestRunner for proper handling
2741 Y.Test.Runner._handleError(ex);
2745 } else if (expectation.property){
2747 mock.__expectations[name] = expectation;
2752 * Verifies that all expectations of a mock object have been met and
2753 * throws an assertion error if not.
2754 * @param {Object} mock The object to verify..
2759 Y.Mock.verify = function(mock /*:Object*/){
2761 Y.Object.each(mock.__expectations, function(expectation){
2762 if (expectation.method) {
2763 Y.Assert.areEqual(expectation.callCount, expectation.actualCallCount, "Method " + expectation.method + "() wasn't called the expected number of times.");
2764 } else if (expectation.property){
2765 Y.Assert.areEqual(expectation.value, mock[expectation.property], "Property " + expectation.property + " wasn't set to the correct value.");
2769 //route through TestRunner for proper handling
2770 Y.Test.Runner._handleError(ex);
2774 Y.Mock.Value = function(method, originalArgs, message){
2775 if (this instanceof Y.Mock.Value){
2776 this.verify = function(value){
2777 var args = [].concat(originalArgs || []);
2780 method.apply(null, args);
2783 return new Y.Mock.Value(method, originalArgs, message);
2787 Y.Mock.Value.Any = Y.Mock.Value(function(){});
2788 Y.Mock.Value.Boolean = Y.Mock.Value(Y.Assert.isBoolean);
2789 Y.Mock.Value.Number = Y.Mock.Value(Y.Assert.isNumber);
2790 Y.Mock.Value.String = Y.Mock.Value(Y.Assert.isString);
2791 Y.Mock.Value.Object = Y.Mock.Value(Y.Assert.isObject);
2792 Y.Mock.Value.Function = Y.Mock.Value(Y.Assert.isFunction);
2796 }, '3.0.0' ,{requires:['substitute','event-base']});