2
YUI 3.10.3 (build 2fb5187)
3
Copyright 2013 Yahoo! Inc. All rights reserved.
4
Licensed under the BSD License.
5
http://yuilibrary.com/license/
8
YUI.add('test', function (Y, NAME) {
19
* The root namespace for YUI Test.
22
//So we only ever have one YUITest object that's shared
25
} else { //Ends after the YUITest definitions
27
//Make this global for back compat
38
//Using internal YUI methods here
39
YUITest.Object = Y.Object;
40
YUITest.Array = Y.Array;
47
* Simple custom event implementation.
53
YUITest.EventTarget = function(){
56
* Event handlers for the various events.
66
YUITest.EventTarget.prototype = {
69
constructor: YUITest.EventTarget,
71
//-------------------------------------------------------------------------
73
//-------------------------------------------------------------------------
76
* Adds a listener for a given event type.
77
* @param {String} type The type of event to add a listener for.
78
* @param {Function} listener The function to call when the event occurs.
82
attach: function(type, listener){
83
if (typeof this._handlers[type] == "undefined"){
84
this._handlers[type] = [];
87
this._handlers[type].push(listener);
91
* Adds a listener for a given event type.
92
* @param {String} type The type of event to add a listener for.
93
* @param {Function} listener The function to call when the event occurs.
98
subscribe: function(type, listener){
99
this.attach.apply(this, arguments);
103
* Fires an event based on the passed-in object.
104
* @param {Object|String} event An object with at least a 'type' attribute
105
* or a string indicating the event name.
109
fire: function(event){
110
if (typeof event == "string"){
111
event = { type: event };
118
throw new Error("Event object missing 'type' property.");
121
if (this._handlers[event.type] instanceof Array){
122
var handlers = this._handlers[event.type];
123
for (var i=0, len=handlers.length; i < len; i++){
124
handlers[i].call(this, event);
130
* Removes a listener for a given event type.
131
* @param {String} type The type of event to remove a listener from.
132
* @param {Function} listener The function to remove from the event.
136
detach: function(type, listener){
137
if (this._handlers[type] instanceof Array){
138
var handlers = this._handlers[type];
139
for (var i=0, len=handlers.length; i < len; i++){
140
if (handlers[i] === listener){
141
handlers.splice(i, 1);
149
* Removes a listener for a given event type.
150
* @param {String} type The type of event to remove a listener from.
151
* @param {Function} listener The function to remove from the event.
153
* @method unsubscribe
156
unsubscribe: function(type, listener){
157
this.detach.apply(this, arguments);
164
* A test suite that can contain a collection of TestCase and TestSuite objects.
165
* @param {String||Object} data The name of the test suite or an object containing
166
* a name property as well as setUp and tearDown methods.
172
YUITest.TestSuite = function (data) {
175
* The name of the test suite.
182
* Array of test suites and test cases.
189
//initialize the properties
190
if (typeof data == "string"){
192
} else if (data instanceof Object){
193
for (var prop in data){
194
if (data.hasOwnProperty(prop)){
195
this[prop] = data[prop];
201
if (this.name === "" || !this.name) {
202
this.name = YUITest.guid("testSuite_");
207
YUITest.TestSuite.prototype = {
209
//restore constructor
210
constructor: YUITest.TestSuite,
213
* Adds a test suite or test case to the test suite.
214
* @param {Test.TestSuite||YUITest.TestCase} testObject The test suite or test case to add.
218
add : function (testObject) {
219
if (testObject instanceof YUITest.TestSuite || testObject instanceof YUITest.TestCase) {
220
this.items.push(testObject);
225
//-------------------------------------------------------------------------
227
//-------------------------------------------------------------------------
230
* Function to run before each test is executed.
234
setUp : function () {
238
* Function to run after each test is executed.
242
tearDown: function () {
247
* Test case containing various tests to run.
248
* @param template An object containing any number of test methods, other methods,
249
* an optional name, and anything else the test case needs.
258
YUITest.TestCase = function (template) {
261
* Special rules for the test case. Possible subobjects
262
* are fail, for tests that should fail, and error, for
263
* tests that should throw an error.
267
//copy over all properties from the template to this object
268
for (var prop in template) {
269
this[prop] = template[prop];
272
//check for a valid name
273
if (typeof this.name != "string") {
274
this.name = YUITest.guid("testCase_");
280
YUITest.TestCase.prototype = {
282
//restore constructor
283
constructor: YUITest.TestCase,
286
* Method to call from an async init method to
287
* restart the test case. When called, returns a function
288
* that should be called when tests are ready to continue.
290
* @return {Function} The function to call as a callback.
292
callback: function(){
293
return YUITest.TestRunner.callback.apply(YUITest.TestRunner,arguments);
297
* Resumes a paused test and runs the given function.
298
* @param {Function} segment (Optional) The function to run.
299
* If omitted, the test automatically passes.
303
resume : function (segment) {
304
YUITest.TestRunner.resume(segment);
308
* Causes the test case to wait a specified amount of time and then
309
* continue executing the given code.
310
* @param {Function} segment (Optional) The function to run after the delay.
311
* If omitted, the TestRunner will wait until resume() is called.
312
* @param {int} delay (Optional) The number of milliseconds to wait before running
313
* the function. If omitted, defaults to zero.
317
wait : function (segment, delay){
319
var actualDelay = (typeof segment == "number" ? segment : delay);
320
actualDelay = (typeof actualDelay == "number" ? actualDelay : 10000);
322
if (typeof segment == "function"){
323
throw new YUITest.Wait(segment, actualDelay);
325
throw new YUITest.Wait(function(){
326
YUITest.Assert.fail("Timeout: wait() called but resume() never called.");
331
//-------------------------------------------------------------------------
333
//-------------------------------------------------------------------------
336
* Asserts that a given condition is true. If not, then a YUITest.AssertionError object is thrown
337
* and the test fails.
339
* @param {Boolean} condition The condition to test.
340
* @param {String} message The message to display if the assertion fails.
342
assert : function (condition, message){
343
YUITest.Assert._increment();
345
throw new YUITest.AssertionError(YUITest.Assert._formatMessage(message, "Assertion failed."));
350
* Forces an assertion error to occur. Shortcut for YUITest.Assert.fail().
352
* @param {String} message (Optional) The message to display with the failure.
354
fail: function (message) {
355
YUITest.Assert.fail(message);
358
//-------------------------------------------------------------------------
360
//-------------------------------------------------------------------------
363
* Function to run once before tests start to run.
364
* This executes before the first call to setUp().
372
* Function to run once after tests finish running.
373
* This executes after the last call to tearDown().
381
* Function to run before each test is executed.
385
setUp : function () {
390
* Function to run after each test is executed.
394
tearDown: function () {
399
* An object object containing test result formatting methods.
405
YUITest.TestFormat = function(){
407
/* (intentionally not documented)
408
* Basic XML escaping method. Replaces quotes, less-than, greater-than,
409
* apostrophe, and ampersand characters with their corresponding entities.
410
* @param {String} text The text to encode.
411
* @return {String} The XML-escaped text.
413
function xmlEscape(text){
415
return text.replace(/[<>"'&]/g, function(value){
417
case "<": return "<";
418
case ">": return ">";
419
case "\"": return """;
420
case "'": return "'";
421
case "&": return "&";
431
* Returns test results formatted as a JSON string. Requires JSON utility.
432
* @param {Object} result The results object created by TestRunner.
433
* @return {String} A JSON-formatted string of results.
437
JSON: function(results) {
438
return YUITest.Util.JSON.stringify(results);
442
* Returns test results formatted as an XML string.
443
* @param {Object} result The results object created by TestRunner.
444
* @return {String} An XML-formatted string of results.
448
XML: function(results) {
450
function serializeToXML(results){
451
var xml = "<" + results.type + " name=\"" + xmlEscape(results.name) + "\"";
453
if (typeof(results.duration)=="number"){
454
xml += " duration=\"" + results.duration + "\"";
457
if (results.type == "test"){
458
xml += " result=\"" + results.result + "\" message=\"" + xmlEscape(results.message) + "\">";
460
xml += " passed=\"" + results.passed + "\" failed=\"" + results.failed + "\" ignored=\"" + results.ignored + "\" total=\"" + results.total + "\">";
461
for (var prop in results){
462
if (results.hasOwnProperty(prop)){
463
if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
464
xml += serializeToXML(results[prop]);
470
xml += "</" + results.type + ">";
475
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + serializeToXML(results);
481
* Returns test results formatted in JUnit XML format.
482
* @param {Object} result The results object created by TestRunner.
483
* @return {String} An XML-formatted string of results.
487
JUnitXML: function(results) {
489
function serializeToJUnitXML(results){
492
switch (results.type){
493
//equivalent to testcase in JUnit
495
if (results.result != "ignore"){
496
xml = "<testcase name=\"" + xmlEscape(results.name) + "\" time=\"" + (results.duration/1000) + "\">";
497
if (results.result == "fail"){
498
xml += "<failure message=\"" + xmlEscape(results.message) + "\"><![CDATA[" + results.message + "]]></failure>";
504
//equivalent to testsuite in JUnit
507
xml = "<testsuite name=\"" + xmlEscape(results.name) + "\" tests=\"" + results.total + "\" failures=\"" + results.failed + "\" time=\"" + (results.duration/1000) + "\">";
509
for (var prop in results){
510
if (results.hasOwnProperty(prop)){
511
if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
512
xml += serializeToJUnitXML(results[prop]);
517
xml += "</testsuite>";
520
//no JUnit equivalent, don't output anything
522
for (var prop in results){
523
if (results.hasOwnProperty(prop)){
524
if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
525
xml += serializeToJUnitXML(results[prop]);
531
//top-level, equivalent to testsuites in JUnit
534
xml = "<testsuites>";
536
for (var prop in results){
537
if (results.hasOwnProperty(prop)){
538
if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
539
xml += serializeToJUnitXML(results[prop]);
544
xml += "</testsuites>";
553
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + serializeToJUnitXML(results);
557
* Returns test results formatted in TAP format.
558
* For more information, see <a href="http://testanything.org/">Test Anything Protocol</a>.
559
* @param {Object} result The results object created by TestRunner.
560
* @return {String} A TAP-formatted string of results.
564
TAP: function(results) {
566
var currentTestNum = 1;
568
function serializeToTAP(results){
571
switch (results.type){
574
if (results.result != "ignore"){
576
text = "ok " + (currentTestNum++) + " - " + results.name;
578
if (results.result == "fail"){
579
text = "not " + text + " - " + results.message;
584
text = "#Ignored test " + results.name + "\n";
590
text = "#Begin testcase " + results.name + "(" + results.failed + " failed of " + results.total + ")\n";
592
for (var prop in results){
593
if (results.hasOwnProperty(prop)){
594
if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
595
text += serializeToTAP(results[prop]);
600
text += "#End testcase " + results.name + "\n";
607
text = "#Begin testsuite " + results.name + "(" + results.failed + " failed of " + results.total + ")\n";
609
for (var prop in results){
610
if (results.hasOwnProperty(prop)){
611
if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
612
text += serializeToTAP(results[prop]);
617
text += "#End testsuite " + results.name + "\n";
622
for (var prop in results){
623
if (results.hasOwnProperty(prop)){
624
if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
625
text += serializeToTAP(results[prop]);
637
return "1.." + results.total + "\n" + serializeToTAP(results);
644
* An object capable of sending test results to a server.
645
* @param {String} url The URL to submit the results to.
646
* @param {Function} format (Optiona) A function that outputs the results in a specific format.
647
* Default is YUITest.TestFormat.XML.
653
YUITest.Reporter = function(url, format) {
656
* The URL to submit the data to.
663
* The formatting function to call when submitting the data.
667
this.format = format || YUITest.TestFormat.XML;
670
* Extra fields to submit with the request.
675
this._fields = new Object();
678
* The form element used to submit the results.
679
* @type HTMLFormElement
686
* Iframe used as a target for form submission.
687
* @type HTMLIFrameElement
694
YUITest.Reporter.prototype = {
696
//restore missing constructor
697
constructor: YUITest.Reporter,
700
* Adds a field to the form that submits the results.
701
* @param {String} name The name of the field.
702
* @param {Variant} value The value of the field.
706
addField : function (name, value){
707
this._fields[name] = value;
711
* Removes all previous defined fields.
713
* @method clearFields
715
clearFields : function(){
716
this._fields = new Object();
720
* Cleans up the memory associated with the TestReporter, removing DOM elements
725
destroy : function() {
727
this._form.parentNode.removeChild(this._form);
731
this._iframe.parentNode.removeChild(this._iframe);
738
* Sends the report to the server.
739
* @param {Object} results The results object created by TestRunner.
743
report : function(results){
745
//if the form hasn't been created yet, create it
747
this._form = document.createElement("form");
748
this._form.method = "post";
749
this._form.style.visibility = "hidden";
750
this._form.style.position = "absolute";
751
this._form.style.top = 0;
752
document.body.appendChild(this._form);
754
//IE won't let you assign a name using the DOM, must do it the hacky way
756
this._iframe = document.createElement("<iframe name=\"yuiTestTarget\" />");
758
this._iframe = document.createElement("iframe");
759
this._iframe.name = "yuiTestTarget";
762
this._iframe.src = "javascript:false";
763
this._iframe.style.visibility = "hidden";
764
this._iframe.style.position = "absolute";
765
this._iframe.style.top = 0;
766
document.body.appendChild(this._iframe);
768
this._form.target = "yuiTestTarget";
771
//set the form's action
772
this._form.action = this.url;
774
//remove any existing fields
775
while(this._form.hasChildNodes()){
776
this._form.removeChild(this._form.lastChild);
779
//create default fields
780
this._fields.results = this.format(results);
781
this._fields.useragent = navigator.userAgent;
782
this._fields.timestamp = (new Date()).toLocaleString();
784
//add fields to the form
785
for (var prop in this._fields){
786
var value = this._fields[prop];
787
if (this._fields.hasOwnProperty(prop) && (typeof value != "function")){
788
var input = document.createElement("input");
789
input.type = "hidden";
792
this._form.appendChild(input);
796
//remove default fields
797
delete this._fields.results;
798
delete this._fields.useragent;
799
delete this._fields.timestamp;
801
if (arguments[1] !== false){
810
* Runs test suites and test cases, providing events to allowing for the
811
* interpretation of test results.
817
YUITest.TestRunner = function(){
819
/*(intentionally not documented)
820
* Determines if any of the array of test groups appears
821
* in the given TestRunner filter.
822
* @param {Array} testGroups The array of test groups to
824
* @param {String} filter The TestRunner groups filter.
826
function inGroups(testGroups, filter){
831
for (var i=0, len=testGroups.length; i < len; i++){
832
if (filter.indexOf("," + testGroups[i] + ",") > -1){
842
* A node in the test tree structure. May represent a TestSuite, TestCase, or
844
* @param {Variant} testObject A TestSuite, TestCase, or the name of a test function.
850
function TestNode(testObject){
853
* The TestSuite, TestCase, or test function represented by this node.
855
* @property testObject
857
this.testObject = testObject;
860
* Pointer to this node's first child.
862
* @property firstChild
864
this.firstChild = null;
867
* Pointer to this node's last child.
869
* @property lastChild
871
this.lastChild = null;
874
* Pointer to this node's parent.
881
* Pointer to this node's next sibling.
888
* Test results for this test object.
892
this.results = new YUITest.Results();
895
if (testObject instanceof YUITest.TestSuite){
896
this.results.type = "testsuite";
897
this.results.name = testObject.name;
898
} else if (testObject instanceof YUITest.TestCase){
899
this.results.type = "testcase";
900
this.results.name = testObject.name;
905
TestNode.prototype = {
908
* Appends a new test object (TestSuite, TestCase, or test function name) as a child
910
* @param {Variant} testObject A TestSuite, TestCase, or the name of a test function.
912
* @method appendChild
914
appendChild : function (testObject){
915
var node = new TestNode(testObject);
916
if (this.firstChild === null){
917
this.firstChild = this.lastChild = node;
919
this.lastChild.next = node;
920
this.lastChild = node;
928
* Runs test suites and test cases, providing events to allowing for the
929
* interpretation of test results.
935
function TestRunner(){
937
//inherit from EventTarget
938
YUITest.EventTarget.call(this);
941
* Suite on which to attach all TestSuites and TestCases to be run.
942
* @type YUITest.TestSuite
943
* @property masterSuite
947
this.masterSuite = new YUITest.TestSuite(YUITest.guid('testSuite_'));
950
* Pointer to the current node in the test tree.
959
* Pointer to the root node in the test tree.
968
* Indicates if the TestRunner will log events or not.
977
* Indicates if the TestRunner is waiting as a result of
978
* wait() being called.
984
this._waiting = false;
987
* Indicates if the TestRunner is currently running tests.
993
this._running = false;
996
* Holds copy of the results object generated when all tests are
1000
* @property _lastResults
1003
this._lastResults = null;
1006
* Data object that is passed around from method to method.
1012
this._context = null;
1015
* The list of test groups to run. The list is represented
1016
* by a comma delimited string with commas at the start and
1027
TestRunner.prototype = YUITest.Util.mix(new YUITest.EventTarget(), {
1030
* If true, YUITest will not fire an error for tests with no Asserts.
1031
* @property _ignoreEmpty
1036
_ignoreEmpty: false,
1039
constructor: YUITest.TestRunner,
1041
//-------------------------------------------------------------------------
1043
//-------------------------------------------------------------------------
1046
* Fires when a test case is opened but before the first
1048
* @event testcasebegin
1051
TEST_CASE_BEGIN_EVENT : "testcasebegin",
1054
* Fires when all tests in a test case have been executed.
1055
* @event testcasecomplete
1058
TEST_CASE_COMPLETE_EVENT : "testcasecomplete",
1061
* Fires when a test suite is opened but before the first
1063
* @event testsuitebegin
1066
TEST_SUITE_BEGIN_EVENT : "testsuitebegin",
1069
* Fires when all test cases in a test suite have been
1071
* @event testsuitecomplete
1074
TEST_SUITE_COMPLETE_EVENT : "testsuitecomplete",
1077
* Fires when a test has passed.
1081
TEST_PASS_EVENT : "pass",
1084
* Fires when a test has failed.
1088
TEST_FAIL_EVENT : "fail",
1091
* Fires when a non-test method has an error.
1095
ERROR_EVENT : "error",
1098
* Fires when a test has been ignored.
1102
TEST_IGNORE_EVENT : "ignore",
1105
* Fires when all test suites and test cases have been completed.
1109
COMPLETE_EVENT : "complete",
1112
* Fires when the run() method is called.
1116
BEGIN_EVENT : "begin",
1118
//-------------------------------------------------------------------------
1119
// Test Tree-Related Methods
1120
//-------------------------------------------------------------------------
1123
* Adds a test case to the test tree as a child of the specified node.
1124
* @param {TestNode} parentNode The node to add the test case to as a child.
1125
* @param {Test.TestCase} testCase The test case to add.
1129
* @method _addTestCaseToTestTree
1131
_addTestCaseToTestTree : function (parentNode, testCase){
1133
//add the test suite
1134
var node = parentNode.appendChild(testCase),
1138
//iterate over the items in the test case
1139
for (prop in testCase){
1140
if ((prop.indexOf("test") === 0 || prop.indexOf(" ") > -1) && typeof testCase[prop] == "function"){
1141
node.appendChild(prop);
1148
* Adds a test suite to the test tree as a child of the specified node.
1149
* @param {TestNode} parentNode The node to add the test suite to as a child.
1150
* @param {Test.TestSuite} testSuite The test suite to add.
1154
* @method _addTestSuiteToTestTree
1156
_addTestSuiteToTestTree : function (parentNode, testSuite) {
1158
//add the test suite
1159
var node = parentNode.appendChild(testSuite);
1161
//iterate over the items in the master suite
1162
for (var i=0; i < testSuite.items.length; i++){
1163
if (testSuite.items[i] instanceof YUITest.TestSuite) {
1164
this._addTestSuiteToTestTree(node, testSuite.items[i]);
1165
} else if (testSuite.items[i] instanceof YUITest.TestCase) {
1166
this._addTestCaseToTestTree(node, testSuite.items[i]);
1172
* Builds the test tree based on items in the master suite. The tree is a hierarchical
1173
* representation of the test suites, test cases, and test functions. The resulting tree
1174
* is stored in _root and the pointer _cur is set to the root initially.
1178
* @method _buildTestTree
1180
_buildTestTree : function () {
1182
this._root = new TestNode(this.masterSuite);
1183
//this._cur = this._root;
1185
//iterate over the items in the master suite
1186
for (var i=0; i < this.masterSuite.items.length; i++){
1187
if (this.masterSuite.items[i] instanceof YUITest.TestSuite) {
1188
this._addTestSuiteToTestTree(this._root, this.masterSuite.items[i]);
1189
} else if (this.masterSuite.items[i] instanceof YUITest.TestCase) {
1190
this._addTestCaseToTestTree(this._root, this.masterSuite.items[i]);
1196
//-------------------------------------------------------------------------
1198
//-------------------------------------------------------------------------
1201
* Handles the completion of a test object's tests. Tallies test results
1202
* from one level up to the next.
1203
* @param {TestNode} node The TestNode representing the test object.
1205
* @method _handleTestObjectComplete
1208
_handleTestObjectComplete : function (node) {
1211
if (node && (typeof node.testObject == "object")) {
1212
parentNode = node.parent;
1215
parentNode.results.include(node.results);
1216
parentNode.results[node.testObject.name] = node.results;
1219
if (node.testObject instanceof YUITest.TestSuite){
1220
this._execNonTestMethod(node, "tearDown", false);
1221
node.results.duration = (new Date()) - node._start;
1222
this.fire({ type: this.TEST_SUITE_COMPLETE_EVENT, testSuite: node.testObject, results: node.results});
1223
} else if (node.testObject instanceof YUITest.TestCase){
1224
this._execNonTestMethod(node, "destroy", false);
1225
node.results.duration = (new Date()) - node._start;
1226
this.fire({ type: this.TEST_CASE_COMPLETE_EVENT, testCase: node.testObject, results: node.results});
1231
//-------------------------------------------------------------------------
1232
// Navigation Methods
1233
//-------------------------------------------------------------------------
1236
* Retrieves the next node in the test tree.
1237
* @return {TestNode} The next node in the test tree or null if the end is reached.
1242
_next : function () {
1244
if (this._cur === null){
1245
this._cur = this._root;
1246
} else if (this._cur.firstChild) {
1247
this._cur = this._cur.firstChild;
1248
} else if (this._cur.next) {
1249
this._cur = this._cur.next;
1251
while (this._cur && !this._cur.next && this._cur !== this._root){
1252
this._handleTestObjectComplete(this._cur);
1253
this._cur = this._cur.parent;
1256
this._handleTestObjectComplete(this._cur);
1258
if (this._cur == this._root){
1259
this._cur.results.type = "report";
1260
this._cur.results.timestamp = (new Date()).toLocaleString();
1261
this._cur.results.duration = (new Date()) - this._cur._start;
1262
this._lastResults = this._cur.results;
1263
this._running = false;
1264
this.fire({ type: this.COMPLETE_EVENT, results: this._lastResults});
1266
} else if (this._cur) {
1267
this._cur = this._cur.next;
1275
* Executes a non-test method (init, setUp, tearDown, destroy)
1276
* and traps an errors. If an error occurs, an error event is
1278
* @param {Object} node The test node in the testing tree.
1279
* @param {String} methodName The name of the method to execute.
1280
* @param {Boolean} allowAsync Determines if the method can be called asynchronously.
1281
* @return {Boolean} True if an async method was called, false if not.
1282
* @method _execNonTestMethod
1285
_execNonTestMethod: function(node, methodName, allowAsync){
1286
var testObject = node.testObject,
1287
event = { type: this.ERROR_EVENT };
1289
if (allowAsync && testObject["async:" + methodName]){
1290
testObject["async:" + methodName](this._context);
1293
testObject[methodName](this._context);
1296
node.results.errors++;
1298
event.methodName = methodName;
1299
if (testObject instanceof YUITest.TestCase){
1300
event.testCase = testObject;
1302
event.testSuite = testSuite;
1312
* Runs a test case or test suite, returning the results.
1313
* @param {Test.TestCase|YUITest.TestSuite} testObject The test case or test suite to run.
1314
* @return {Object} Results of the execution with properties passed, failed, and total.
1319
_run : function () {
1321
//flag to indicate if the TestRunner should wait before continuing
1322
var shouldWait = false;
1324
//get the next test node
1325
var node = this._next();
1327
if (node !== null) {
1329
//set flag to say the testrunner is running
1330
this._running = true;
1332
//eliminate last results
1333
this._lastResult = null;
1335
var testObject = node.testObject;
1337
//figure out what to do
1338
if (typeof testObject == "object" && testObject !== null){
1339
if (testObject instanceof YUITest.TestSuite){
1340
this.fire({ type: this.TEST_SUITE_BEGIN_EVENT, testSuite: testObject });
1341
node._start = new Date();
1342
this._execNonTestMethod(node, "setUp" ,false);
1343
} else if (testObject instanceof YUITest.TestCase){
1344
this.fire({ type: this.TEST_CASE_BEGIN_EVENT, testCase: testObject });
1345
node._start = new Date();
1347
//regular or async init
1349
if (testObject["async:init"]){
1350
testObject["async:init"](this._context);
1353
testObject.init(this._context);
1356
node.results.errors++;
1357
this.fire({ type: this.ERROR_EVENT, error: ex, testCase: testObject, methodName: "init" });
1359
if(this._execNonTestMethod(node, "init", true)){
1364
//some environments don't support setTimeout
1365
if (typeof setTimeout != "undefined"){
1366
setTimeout(function(){
1367
YUITest.TestRunner._run();
1373
this._runTest(node);
1379
_resumeTest : function (segment) {
1381
//get relevant information
1382
var node = this._cur;
1384
//we know there's no more waiting now
1385
this._waiting = false;
1387
//if there's no node, it probably means a wait() was called after resume()
1389
//TODO: Handle in some way?
1390
//console.log("wait() called after resume()");
1391
//this.fire("error", { testCase: "(unknown)", test: "(unknown)", error: new Error("wait() called after resume()")} );
1395
var testName = node.testObject;
1396
var testCase = node.parent.testObject;
1398
//cancel other waits if available
1399
if (testCase.__yui_wait){
1400
clearTimeout(testCase.__yui_wait);
1401
delete testCase.__yui_wait;
1404
//get the "should" test cases
1405
var shouldFail = testName.indexOf("fail:") === 0 ||
1406
(testCase._should.fail || {})[testName];
1407
var shouldError = (testCase._should.error || {})[testName];
1409
//variable to hold whether or not the test failed
1417
segment.call(testCase, this._context);
1419
//if the test hasn't already failed and doesn't have any asserts...
1420
if(YUITest.Assert._getCount() == 0 && !this._ignoreEmpty){
1421
throw new YUITest.AssertionError("Test has no asserts.");
1423
//if it should fail, and it got here, then it's a fail because it didn't
1424
else if (shouldFail){
1425
error = new YUITest.ShouldFail();
1427
} else if (shouldError){
1428
error = new YUITest.ShouldError();
1434
//cancel any pending waits, the test already failed
1435
if (testCase.__yui_wait){
1436
clearTimeout(testCase.__yui_wait);
1437
delete testCase.__yui_wait;
1440
//figure out what type of error it was
1441
if (thrown instanceof YUITest.AssertionError) {
1446
} else if (thrown instanceof YUITest.Wait){
1448
if (typeof thrown.segment == "function"){
1449
if (typeof thrown.delay == "number"){
1451
//some environments don't support setTimeout
1452
if (typeof setTimeout != "undefined"){
1453
testCase.__yui_wait = setTimeout(function(){
1454
YUITest.TestRunner._resumeTest(thrown.segment);
1456
this._waiting = true;
1458
throw new Error("Asynchronous tests not supported in this environment.");
1466
//first check to see if it should error
1468
error = new YUITest.UnexpectedError(thrown);
1471
//check to see what type of data we have
1472
if (typeof shouldError == "string"){
1474
//if it's a string, check the error message
1475
if (thrown.message != shouldError){
1476
error = new YUITest.UnexpectedError(thrown);
1479
} else if (typeof shouldError == "function"){
1481
//if it's a function, see if the error is an instance of it
1482
if (!(thrown instanceof shouldError)){
1483
error = new YUITest.UnexpectedError(thrown);
1487
} else if (typeof shouldError == "object" && shouldError !== null){
1489
//if it's an object, check the instance and message
1490
if (!(thrown instanceof shouldError.constructor) ||
1491
thrown.message != shouldError.message){
1492
error = new YUITest.UnexpectedError(thrown);
1503
//fire appropriate event
1505
this.fire({ type: this.TEST_FAIL_EVENT, testCase: testCase, testName: testName, error: error });
1507
this.fire({ type: this.TEST_PASS_EVENT, testCase: testCase, testName: testName });
1511
this._execNonTestMethod(node.parent, "tearDown", false);
1513
//reset the assert count
1514
YUITest.Assert._reset();
1516
//calculate duration
1517
var duration = (new Date()) - node._start;
1520
node.parent.results[testName] = {
1521
result: failed ? "fail" : "pass",
1522
message: error ? error.getMessage() : "Test passed",
1529
node.parent.results.failed++;
1531
node.parent.results.passed++;
1533
node.parent.results.total++;
1535
//set timeout not supported in all environments
1536
if (typeof setTimeout != "undefined"){
1537
setTimeout(function(){
1538
YUITest.TestRunner._run();
1547
* Handles an error as if it occurred within the currently executing
1548
* test. This is for mock methods that may be called asynchronously
1549
* and therefore out of the scope of the TestRunner. Previously, this
1550
* error would bubble up to the browser. Now, this method is used
1551
* to tell TestRunner about the error. This should never be called
1552
* by anyplace other than the Mock object.
1553
* @param {Error} error The error object.
1555
* @method _handleError
1559
_handleError: function(error){
1562
this._resumeTest(function(){
1572
* Runs a single test based on the data provided in the node.
1574
* @param {TestNode} node The TestNode representing the test to run.
1579
_runTest : function (node) {
1581
//get relevant information
1582
var testName = node.testObject,
1583
testCase = node.parent.testObject,
1584
test = testCase[testName],
1586
//get the "should" test cases
1587
shouldIgnore = testName.indexOf("ignore:") === 0 ||
1588
!inGroups(testCase.groups, this._groups) ||
1589
(testCase._should.ignore || {})[testName]; //deprecated
1591
//figure out if the test should be ignored or not
1595
node.parent.results[testName] = {
1597
message: "Test ignored",
1599
name: testName.indexOf("ignore:") === 0 ? testName.substring(7) : testName
1602
node.parent.results.ignored++;
1603
node.parent.results.total++;
1605
this.fire({ type: this.TEST_IGNORE_EVENT, testCase: testCase, testName: testName });
1607
//some environments don't support setTimeout
1608
if (typeof setTimeout != "undefined"){
1609
setTimeout(function(){
1610
YUITest.TestRunner._run();
1618
//mark the start time
1619
node._start = new Date();
1622
this._execNonTestMethod(node.parent, "setUp", false);
1624
//now call the body of the test
1625
this._resumeTest(test);
1630
//-------------------------------------------------------------------------
1632
//-------------------------------------------------------------------------
1635
* Retrieves the name of the current result set.
1636
* @return {String} The name of the result set.
1639
getName: function(){
1640
return this.masterSuite.name;
1644
* The name assigned to the master suite of the TestRunner. This is the name
1645
* that is output as the root's name when results are retrieved.
1646
* @param {String} name The name of the result set.
1650
setName: function(name){
1651
this.masterSuite.name = name;
1654
//-------------------------------------------------------------------------
1656
//-------------------------------------------------------------------------
1659
* Adds a test suite or test case to the list of test objects to run.
1660
* @param testObject Either a TestCase or a TestSuite that should be run.
1665
add : function (testObject) {
1666
this.masterSuite.add(testObject);
1671
* Removes all test objects from the runner.
1676
clear : function () {
1677
this.masterSuite = new YUITest.TestSuite(YUITest.guid('testSuite_'));
1681
* Indicates if the TestRunner is waiting for a test to resume
1682
* @return {Boolean} True if the TestRunner is waiting, false if not.
1686
isWaiting: function() {
1687
return this._waiting;
1691
* Indicates that the TestRunner is busy running tests and therefore can't
1692
* be stopped and results cannot be gathered.
1693
* @return {Boolean} True if the TestRunner is running, false if not.
1696
isRunning: function(){
1697
return this._running;
1701
* Returns the last complete results set from the TestRunner. Null is returned
1702
* if the TestRunner is running or no tests have been run.
1703
* @param {Function} format (Optional) A test format to return the results in.
1704
* @return {Object|String} Either the results object or, if a test format is
1705
* passed as the argument, a string representing the results in a specific
1707
* @method getResults
1709
getResults: function(format){
1710
if (!this._running && this._lastResults){
1711
if (typeof format == "function"){
1712
return format(this._lastResults);
1714
return this._lastResults;
1722
* Returns the coverage report for the files that have been executed.
1723
* This returns only coverage information for files that have been
1724
* instrumented using YUI Test Coverage and only those that were run
1726
* @param {Function} format (Optional) A coverage format to return results in.
1727
* @return {Object|String} Either the coverage object or, if a coverage
1728
* format is specified, a string representing the results in that format.
1729
* @method getCoverage
1731
getCoverage: function(format) {
1732
var covObject = null;
1733
if (typeof _yuitest_coverage === "object") {
1734
covObject = _yuitest_coverage;
1736
if (typeof __coverage__ === "object") {
1737
covObject = __coverage__;
1739
if (!this._running && typeof covObject == "object"){
1740
if (typeof format == "function") {
1741
return format(covObject);
1751
* Used to continue processing when a method marked with
1752
* "async:" is executed. This should not be used in test
1753
* methods, only in init(). Each argument is a string, and
1754
* when the returned function is executed, the arguments
1755
* are assigned to the context data object using the string
1756
* as the key name (value is the argument itself).
1758
* @return {Function} A callback function.
1761
callback: function(){
1762
var names = arguments,
1763
data = this._context,
1767
for (var i=0; i < arguments.length; i++){
1768
data[names[i]] = arguments[i];
1775
* Resumes the TestRunner after wait() was called.
1776
* @param {Function} segment The function to run as the rest
1777
* of the haulted test.
1782
resume : function (segment) {
1784
this._resumeTest(segment || function(){});
1786
throw new Error("resume() called without wait().");
1791
* Runs the test suite.
1792
* @param {Object|Boolean} options (Optional) Options for the runner:
1793
* <code>oldMode</code> indicates the TestRunner should work in the YUI <= 2.8 way
1794
* of internally managing test suites. <code>groups</code> is an array
1795
* of test groups indicating which tests to run.
1800
run : function (options) {
1802
options = options || {};
1804
//pointer to runner to avoid scope issues
1805
var runner = YUITest.TestRunner,
1806
oldMode = options.oldMode;
1809
//if there's only one suite on the masterSuite, move it up
1810
if (!oldMode && this.masterSuite.items.length == 1 && this.masterSuite.items[0] instanceof YUITest.TestSuite){
1811
this.masterSuite = this.masterSuite.items[0];
1814
//determine if there are any groups to filter on
1815
runner._groups = (options.groups instanceof Array) ? "," + options.groups.join(",") + "," : "";
1817
//initialize the runner
1818
runner._buildTestTree();
1819
runner._context = {};
1820
runner._root._start = new Date();
1822
//fire the begin event
1823
runner.fire(runner.BEGIN_EVENT);
1830
return new TestRunner();
1835
* The ArrayAssert object provides functions to test JavaScript array objects
1836
* for a variety of cases.
1839
* @class ArrayAssert
1843
YUITest.ArrayAssert = {
1845
//=========================================================================
1847
//=========================================================================
1850
* Simple indexOf() implementation for an array. Defers to native
1852
* @param {Array} haystack The array to search.
1853
* @param {Variant} needle The value to locate.
1854
* @return {int} The index of the needle if found or -1 if not.
1858
_indexOf: function(haystack, needle){
1859
if (haystack.indexOf){
1860
return haystack.indexOf(needle);
1862
for (var i=0; i < haystack.length; i++){
1863
if (haystack[i] === needle){
1872
* Simple some() implementation for an array. Defers to native
1874
* @param {Array} haystack The array to search.
1875
* @param {Function} matcher The function to run on each value.
1876
* @return {Boolean} True if any value, when run through the matcher,
1881
_some: function(haystack, matcher){
1883
return haystack.some(matcher);
1885
for (var i=0; i < haystack.length; i++){
1886
if (matcher(haystack[i])){
1895
* Asserts that a value is present in an array. This uses the triple equals
1896
* sign so no type coercion may occur.
1897
* @param {Object} needle The value that is expected in the array.
1898
* @param {Array} haystack An array of values.
1899
* @param {String} message (Optional) The message to display if the assertion fails.
1903
contains : function (needle, haystack,
1906
YUITest.Assert._increment();
1908
if (this._indexOf(haystack, needle) == -1){
1909
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value " + needle + " (" + (typeof needle) + ") not found in array [" + haystack + "]."));
1914
* Asserts that a set of values are present in an array. This uses the triple equals
1915
* sign so no type coercion may occur. For this assertion to pass, all values must
1917
* @param {Object[]} needles An array of values that are expected in the array.
1918
* @param {Array} haystack An array of values to check.
1919
* @param {String} message (Optional) The message to display if the assertion fails.
1920
* @method containsItems
1923
containsItems : function (needles, haystack,
1925
YUITest.Assert._increment();
1927
//begin checking values
1928
for (var i=0; i < needles.length; i++){
1929
if (this._indexOf(haystack, needles[i]) == -1){
1930
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value " + needles[i] + " (" + (typeof needles[i]) + ") not found in array [" + haystack + "]."));
1936
* Asserts that a value matching some condition is present in an array. This uses
1937
* a function to determine a match.
1938
* @param {Function} matcher A function that returns true if the items matches or false if not.
1939
* @param {Array} haystack An array of values.
1940
* @param {String} message (Optional) The message to display if the assertion fails.
1941
* @method containsMatch
1944
containsMatch : function (matcher, haystack,
1947
YUITest.Assert._increment();
1948
//check for valid matcher
1949
if (typeof matcher != "function"){
1950
throw new TypeError("ArrayAssert.containsMatch(): First argument must be a function.");
1953
if (!this._some(haystack, matcher)){
1954
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "No match found in array [" + haystack + "]."));
1959
* Asserts that a value is not present in an array. This uses the triple equals
1960
* Asserts that a value is not present in an array. This uses the triple equals
1961
* sign so no type coercion may occur.
1962
* @param {Object} needle The value that is expected in the array.
1963
* @param {Array} haystack An array of values.
1964
* @param {String} message (Optional) The message to display if the assertion fails.
1965
* @method doesNotContain
1968
doesNotContain : function (needle, haystack,
1971
YUITest.Assert._increment();
1973
if (this._indexOf(haystack, needle) > -1){
1974
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
1979
* Asserts that a set of values are not present in an array. This uses the triple equals
1980
* sign so no type coercion may occur. For this assertion to pass, all values must
1982
* @param {Object[]} needles An array of values that are not expected in the array.
1983
* @param {Array} haystack An array of values to check.
1984
* @param {String} message (Optional) The message to display if the assertion fails.
1985
* @method doesNotContainItems
1988
doesNotContainItems : function (needles, haystack,
1991
YUITest.Assert._increment();
1993
for (var i=0; i < needles.length; i++){
1994
if (this._indexOf(haystack, needles[i]) > -1){
1995
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
2002
* Asserts that no values matching a condition are present in an array. This uses
2003
* a function to determine a match.
2004
* @param {Function} matcher A function that returns true if the item matches or false if not.
2005
* @param {Array} haystack An array of values.
2006
* @param {String} message (Optional) The message to display if the assertion fails.
2007
* @method doesNotContainMatch
2010
doesNotContainMatch : function (matcher, haystack,
2013
YUITest.Assert._increment();
2015
//check for valid matcher
2016
if (typeof matcher != "function"){
2017
throw new TypeError("ArrayAssert.doesNotContainMatch(): First argument must be a function.");
2020
if (this._some(haystack, matcher)){
2021
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
2026
* Asserts that the given value is contained in an array at the specified index.
2027
* This uses the triple equals sign so no type coercion will occur.
2028
* @param {Object} needle The value to look for.
2029
* @param {Array} haystack The array to search in.
2030
* @param {int} index The index at which the value should exist.
2031
* @param {String} message (Optional) The message to display if the assertion fails.
2035
indexOf : function (needle, haystack, index, message) {
2037
YUITest.Assert._increment();
2039
//try to find the value in the array
2040
for (var i=0; i < haystack.length; i++){
2041
if (haystack[i] === needle){
2043
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value exists at index " + i + " but should be at index " + index + "."));
2049
//if it makes it here, it wasn't found at all
2050
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value doesn't exist in array [" + haystack + "]."));
2054
* Asserts that the values in an array are equal, and in the same position,
2055
* as values in another array. This uses the double equals sign
2056
* so type coercion may occur. Note that the array objects themselves
2057
* need not be the same for this test to pass.
2058
* @param {Array} expected An array of the expected values.
2059
* @param {Array} actual Any array of the actual values.
2060
* @param {String} message (Optional) The message to display if the assertion fails.
2061
* @method itemsAreEqual
2064
itemsAreEqual : function (expected, actual,
2067
YUITest.Assert._increment();
2069
//first make sure they're array-like (this can probably be improved)
2070
if (typeof expected != "object" || typeof actual != "object"){
2071
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value should be an array."));
2074
//next check array length
2075
if (expected.length != actual.length){
2076
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length + "."));
2079
//begin checking values
2080
for (var i=0; i < expected.length; i++){
2081
if (expected[i] != actual[i]){
2082
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Values in position " + i + " are not equal."), expected[i], actual[i]);
2088
* Asserts that the values in an array are equivalent, and in the same position,
2089
* as values in another array. This uses a function to determine if the values
2090
* are equivalent. Note that the array objects themselves
2091
* need not be the same for this test to pass.
2092
* @param {Array} expected An array of the expected values.
2093
* @param {Array} actual Any array of the actual values.
2094
* @param {Function} comparator A function that returns true if the values are equivalent
2096
* @param {String} message (Optional) The message to display if the assertion fails.
2098
* @method itemsAreEquivalent
2101
itemsAreEquivalent : function (expected, actual,
2102
comparator, message) {
2104
YUITest.Assert._increment();
2106
//make sure the comparator is valid
2107
if (typeof comparator != "function"){
2108
throw new TypeError("ArrayAssert.itemsAreEquivalent(): Third argument must be a function.");
2111
//first check array length
2112
if (expected.length != actual.length){
2113
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
2116
//begin checking values
2117
for (var i=0; i < expected.length; i++){
2118
if (!comparator(expected[i], actual[i])){
2119
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Values in position " + i + " are not equivalent."), expected[i], actual[i]);
2125
* Asserts that an array is empty.
2126
* @param {Array} actual The array to test.
2127
* @param {String} message (Optional) The message to display if the assertion fails.
2131
isEmpty : function (actual, message) {
2132
YUITest.Assert._increment();
2133
if (actual.length > 0){
2134
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Array should be empty."));
2139
* Asserts that an array is not empty.
2140
* @param {Array} actual The array to test.
2141
* @param {String} message (Optional) The message to display if the assertion fails.
2142
* @method isNotEmpty
2145
isNotEmpty : function (actual, message) {
2146
YUITest.Assert._increment();
2147
if (actual.length === 0){
2148
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Array should not be empty."));
2153
* Asserts that the values in an array are the same, and in the same position,
2154
* as values in another array. This uses the triple equals sign
2155
* so no type coercion will occur. Note that the array objects themselves
2156
* need not be the same for this test to pass.
2157
* @param {Array} expected An array of the expected values.
2158
* @param {Array} actual Any array of the actual values.
2159
* @param {String} message (Optional) The message to display if the assertion fails.
2160
* @method itemsAreSame
2163
itemsAreSame : function (expected, actual,
2166
YUITest.Assert._increment();
2168
//first check array length
2169
if (expected.length != actual.length){
2170
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
2173
//begin checking values
2174
for (var i=0; i < expected.length; i++){
2175
if (expected[i] !== actual[i]){
2176
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Values in position " + i + " are not the same."), expected[i], actual[i]);
2182
* Asserts that the given value is contained in an array at the specified index,
2183
* starting from the back of the array.
2184
* This uses the triple equals sign so no type coercion will occur.
2185
* @param {Object} needle The value to look for.
2186
* @param {Array} haystack The array to search in.
2187
* @param {int} index The index at which the value should exist.
2188
* @param {String} message (Optional) The message to display if the assertion fails.
2189
* @method lastIndexOf
2192
lastIndexOf : function (needle, haystack, index, message) {
2194
//try to find the value in the array
2195
for (var i=haystack.length; i >= 0; i--){
2196
if (haystack[i] === needle){
2198
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value exists at index " + i + " but should be at index " + index + "."));
2204
//if it makes it here, it wasn't found at all
2205
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Value doesn't exist in array."));
2211
* The Assert object provides functions to test JavaScript values against
2212
* known and expected results. Whenever a comparison (assertion) fails,
2213
* an error is thrown.
2222
* The number of assertions performed.
2223
* @property _asserts
2229
//-------------------------------------------------------------------------
2231
//-------------------------------------------------------------------------
2234
* Formats a message so that it can contain the original assertion message
2235
* in addition to the custom message.
2236
* @param {String} customMessage The message passed in by the developer.
2237
* @param {String} defaultMessage The message created by the error by default.
2238
* @return {String} The final error message, containing either or both.
2241
* @method _formatMessage
2243
_formatMessage : function (customMessage, defaultMessage) {
2244
if (typeof customMessage == "string" && customMessage.length > 0){
2245
return customMessage.replace("{message}", defaultMessage);
2247
return defaultMessage;
2252
* Returns the number of assertions that have been performed.
2257
_getCount: function(){
2258
return this._asserts;
2262
* Increments the number of assertions that have been performed.
2263
* @method _increment
2267
_increment: function(){
2272
* Resets the number of assertions that have been performed to 0.
2281
//-------------------------------------------------------------------------
2282
// Generic Assertion Methods
2283
//-------------------------------------------------------------------------
2286
* Forces an assertion error to occur.
2287
* @param {String} message (Optional) The message to display with the failure.
2291
fail : function (message) {
2292
throw new YUITest.AssertionError(YUITest.Assert._formatMessage(message, "Test force-failed."));
2296
* A marker that the test should pass.
2300
pass : function (message) {
2301
YUITest.Assert._increment();
2304
//-------------------------------------------------------------------------
2305
// Equality Assertion Methods
2306
//-------------------------------------------------------------------------
2309
* Asserts that a value is equal to another. This uses the double equals sign
2310
* so type coercion may occur.
2311
* @param {Object} expected The expected value.
2312
* @param {Object} actual The actual value to test.
2313
* @param {String} message (Optional) The message to display if the assertion fails.
2317
areEqual : function (expected, actual, message) {
2318
YUITest.Assert._increment();
2319
if (expected != actual) {
2320
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Values should be equal."), expected, actual);
2325
* Asserts that a value is not equal to another. This uses the double equals sign
2326
* so type coercion may occur.
2327
* @param {Object} unexpected The unexpected value.
2328
* @param {Object} actual The actual value to test.
2329
* @param {String} message (Optional) The message to display if the assertion fails.
2330
* @method areNotEqual
2333
areNotEqual : function (unexpected, actual,
2335
YUITest.Assert._increment();
2336
if (unexpected == actual) {
2337
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Values should not be equal."), unexpected);
2342
* Asserts that a value is not the same as another. This uses the triple equals sign
2343
* so no type coercion may occur.
2344
* @param {Object} unexpected The unexpected value.
2345
* @param {Object} actual The actual value to test.
2346
* @param {String} message (Optional) The message to display if the assertion fails.
2347
* @method areNotSame
2350
areNotSame : function (unexpected, actual, message) {
2351
YUITest.Assert._increment();
2352
if (unexpected === actual) {
2353
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Values should not be the same."), unexpected);
2358
* Asserts that a value is the same as another. This uses the triple equals sign
2359
* so no type coercion may occur.
2360
* @param {Object} expected The expected value.
2361
* @param {Object} actual The actual value to test.
2362
* @param {String} message (Optional) The message to display if the assertion fails.
2366
areSame : function (expected, actual, message) {
2367
YUITest.Assert._increment();
2368
if (expected !== actual) {
2369
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Values should be the same."), expected, actual);
2373
//-------------------------------------------------------------------------
2374
// Boolean Assertion Methods
2375
//-------------------------------------------------------------------------
2378
* Asserts that a value is false. This uses the triple equals sign
2379
* so no type coercion may occur.
2380
* @param {Object} actual The actual value to test.
2381
* @param {String} message (Optional) The message to display if the assertion fails.
2385
isFalse : function (actual, message) {
2386
YUITest.Assert._increment();
2387
if (false !== actual) {
2388
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be false."), false, actual);
2393
* Asserts that a value is true. This uses the triple equals sign
2394
* so no type coercion may occur.
2395
* @param {Object} actual The actual value to test.
2396
* @param {String} message (Optional) The message to display if the assertion fails.
2400
isTrue : function (actual, message) {
2401
YUITest.Assert._increment();
2402
if (true !== actual) {
2403
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be true."), true, actual);
2408
//-------------------------------------------------------------------------
2409
// Special Value Assertion Methods
2410
//-------------------------------------------------------------------------
2413
* Asserts that a value is not a number.
2414
* @param {Object} actual The value to test.
2415
* @param {String} message (Optional) The message to display if the assertion fails.
2419
isNaN : function (actual, message){
2420
YUITest.Assert._increment();
2421
if (!isNaN(actual)){
2422
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be NaN."), NaN, actual);
2427
* Asserts that a value is not the special NaN value.
2428
* @param {Object} actual The value to test.
2429
* @param {String} message (Optional) The message to display if the assertion fails.
2433
isNotNaN : function (actual, message){
2434
YUITest.Assert._increment();
2436
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Values should not be NaN."), NaN);
2441
* Asserts that a value is not null. This uses the triple equals sign
2442
* so no type coercion may occur.
2443
* @param {Object} actual The actual value to test.
2444
* @param {String} message (Optional) The message to display if the assertion fails.
2448
isNotNull : function (actual, message) {
2449
YUITest.Assert._increment();
2450
if (actual === null) {
2451
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Values should not be null."), null);
2456
* Asserts that a value is not undefined. This uses the triple equals sign
2457
* so no type coercion may occur.
2458
* @param {Object} actual The actual value to test.
2459
* @param {String} message (Optional) The message to display if the assertion fails.
2460
* @method isNotUndefined
2463
isNotUndefined : function (actual, message) {
2464
YUITest.Assert._increment();
2465
if (typeof actual == "undefined") {
2466
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Value should not be undefined."), undefined);
2471
* Asserts that a value is null. This uses the triple equals sign
2472
* so no type coercion may occur.
2473
* @param {Object} actual The actual value to test.
2474
* @param {String} message (Optional) The message to display if the assertion fails.
2478
isNull : function (actual, message) {
2479
YUITest.Assert._increment();
2480
if (actual !== null) {
2481
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be null."), null, actual);
2486
* Asserts that a value is undefined. This uses the triple equals sign
2487
* so no type coercion may occur.
2488
* @param {Object} actual The actual value to test.
2489
* @param {String} message (Optional) The message to display if the assertion fails.
2490
* @method isUndefined
2493
isUndefined : function (actual, message) {
2494
YUITest.Assert._increment();
2495
if (typeof actual != "undefined") {
2496
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be undefined."), undefined, actual);
2500
//--------------------------------------------------------------------------
2501
// Instance Assertion Methods
2502
//--------------------------------------------------------------------------
2505
* Asserts that a value is an array.
2506
* @param {Object} actual The value to test.
2507
* @param {String} message (Optional) The message to display if the assertion fails.
2511
isArray : function (actual, message) {
2512
YUITest.Assert._increment();
2513
var shouldFail = false;
2515
shouldFail = !Array.isArray(actual);
2517
shouldFail = Object.prototype.toString.call(actual) != "[object Array]";
2520
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Value should be an array."), actual);
2525
* Asserts that a value is a Boolean.
2526
* @param {Object} actual The value to test.
2527
* @param {String} message (Optional) The message to display if the assertion fails.
2531
isBoolean : function (actual, message) {
2532
YUITest.Assert._increment();
2533
if (typeof actual != "boolean"){
2534
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Value should be a Boolean."), actual);
2539
* Asserts that a value is a function.
2540
* @param {Object} actual The value to test.
2541
* @param {String} message (Optional) The message to display if the assertion fails.
2542
* @method isFunction
2545
isFunction : function (actual, message) {
2546
YUITest.Assert._increment();
2547
if (!(actual instanceof Function)){
2548
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Value should be a function."), actual);
2553
* Asserts that a value is an instance of a particular object. This may return
2554
* incorrect results when comparing objects from one frame to constructors in
2555
* another frame. For best results, don't use in a cross-frame manner.
2556
* @param {Function} expected The function that the object should be an instance of.
2557
* @param {Object} actual The object to test.
2558
* @param {String} message (Optional) The message to display if the assertion fails.
2559
* @method isInstanceOf
2562
isInstanceOf : function (expected, actual, message) {
2563
YUITest.Assert._increment();
2564
if (!(actual instanceof expected)){
2565
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value isn't an instance of expected type."), expected, actual);
2570
* Asserts that a value is a number.
2571
* @param {Object} actual The value to test.
2572
* @param {String} message (Optional) The message to display if the assertion fails.
2576
isNumber : function (actual, message) {
2577
YUITest.Assert._increment();
2578
if (typeof actual != "number"){
2579
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Value should be a number."), actual);
2584
* Asserts that a value is an object.
2585
* @param {Object} actual The value to test.
2586
* @param {String} message (Optional) The message to display if the assertion fails.
2590
isObject : function (actual, message) {
2591
YUITest.Assert._increment();
2592
if (!actual || (typeof actual != "object" && typeof actual != "function")){
2593
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Value should be an object."), actual);
2598
* Asserts that a value is a string.
2599
* @param {Object} actual The value to test.
2600
* @param {String} message (Optional) The message to display if the assertion fails.
2604
isString : function (actual, message) {
2605
YUITest.Assert._increment();
2606
if (typeof actual != "string"){
2607
throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Value should be a string."), actual);
2612
* Asserts that a value is of a particular type.
2613
* @param {String} expectedType The expected type of the variable.
2614
* @param {Object} actualValue The actual value to test.
2615
* @param {String} message (Optional) The message to display if the assertion fails.
2619
isTypeOf : function (expectedType, actualValue, message){
2620
YUITest.Assert._increment();
2621
if (typeof actualValue != expectedType){
2622
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Value should be of type " + expectedType + "."), expectedType, typeof actualValue);
2626
//--------------------------------------------------------------------------
2627
// Error Detection Methods
2628
//--------------------------------------------------------------------------
2631
* Asserts that executing a particular method should throw an error of
2632
* a specific type. This is a replacement for _should.error.
2633
* @param {String|Function|Object} expectedError If a string, this
2634
* is the error message that the error must have; if a function, this
2635
* is the constructor that should have been used to create the thrown
2636
* error; if an object, this is an instance of a particular error type
2637
* with a specific error message (both must match).
2638
* @param {Function} method The method to execute that should throw the error.
2639
* @param {String} message (Optional) The message to display if the assertion
2641
* @method throwsError
2645
throwsError: function(expectedError, method, message){
2646
YUITest.Assert._increment();
2653
//check to see what type of data we have
2654
if (typeof expectedError == "string"){
2656
//if it's a string, check the error message
2657
if (thrown.message != expectedError){
2660
} else if (typeof expectedError == "function"){
2662
//if it's a function, see if the error is an instance of it
2663
if (!(thrown instanceof expectedError)){
2667
} else if (typeof expectedError == "object" && expectedError !== null){
2669
//if it's an object, check the instance and message
2670
if (!(thrown instanceof expectedError.constructor) ||
2671
thrown.message != expectedError.message){
2675
} else { //if it gets here, the argument could be wrong
2680
throw new YUITest.UnexpectedError(thrown);
2686
//if it reaches here, the error wasn't thrown, which is a bad thing
2687
throw new YUITest.AssertionError(YUITest.Assert._formatMessage(message, "Error should have been thrown."));
2692
* Error is thrown whenever an assertion fails. It provides methods
2693
* to more easily get at error information and also provides a base class
2694
* from which more specific assertion errors can be derived.
2696
* @param {String} message The message to display when the error occurs.
2699
* @class AssertionError
2702
YUITest.AssertionError = function (message){
2705
* Error message. Must be duplicated to ensure browser receives it.
2709
this.message = message;
2712
* The name of the error that occurred.
2716
this.name = "Assert Error";
2719
YUITest.AssertionError.prototype = {
2721
//restore constructor
2722
constructor: YUITest.AssertionError,
2725
* Returns a fully formatted error for an assertion failure. This should
2726
* be overridden by all subclasses to provide specific information.
2727
* @method getMessage
2728
* @return {String} A string describing the error.
2730
getMessage : function () {
2731
return this.message;
2735
* Returns a string representation of the error.
2737
* @return {String} A string representation of the error.
2739
toString : function () {
2740
return this.name + ": " + this.getMessage();
2744
* ComparisonFailure is subclass of Error that is thrown whenever
2745
* a comparison between two values fails. It provides mechanisms to retrieve
2746
* both the expected and actual value.
2748
* @param {String} message The message to display when the error occurs.
2749
* @param {Object} expected The expected value.
2750
* @param {Object} actual The actual value that caused the assertion to fail.
2752
* @extends AssertionError
2754
* @class ComparisonFailure
2757
YUITest.ComparisonFailure = function (message, expected, actual){
2760
YUITest.AssertionError.call(this, message);
2763
* The expected value.
2765
* @property expected
2767
this.expected = expected;
2774
this.actual = actual;
2777
* The name of the error that occurred.
2781
this.name = "ComparisonFailure";
2785
//inherit from YUITest.AssertionError
2786
YUITest.ComparisonFailure.prototype = new YUITest.AssertionError;
2788
//restore constructor
2789
YUITest.ComparisonFailure.prototype.constructor = YUITest.ComparisonFailure;
2792
* Returns a fully formatted error for an assertion failure. This message
2793
* provides information about the expected and actual values.
2794
* @method getMessage
2795
* @return {String} A string describing the error.
2797
YUITest.ComparisonFailure.prototype.getMessage = function(){
2798
return this.message + "\nExpected: " + this.expected + " (" + (typeof this.expected) + ")" +
2799
"\nActual: " + this.actual + " (" + (typeof this.actual) + ")";
2802
* An object object containing coverage result formatting methods.
2805
* @class CoverageFormat
2808
YUITest.CoverageFormat = {
2811
* Returns the coverage report in JSON format. This is the straight
2812
* JSON representation of the native coverage report.
2813
* @param {Object} coverage The coverage report object.
2814
* @return {String} A JSON-formatted string of coverage data.
2816
* @namespace Test.CoverageFormat
2818
JSON: function(coverage){
2819
return YUITest.Util.JSON.stringify(coverage);
2823
* Returns the coverage report in a JSON format compatible with
2824
* Xdebug. See <a href="http://www.xdebug.com/docs/code_coverage">Xdebug Documentation</a>
2825
* for more information. Note: function coverage is not available
2827
* @param {Object} coverage The coverage report object.
2828
* @return {String} A JSON-formatted string of coverage data.
2829
* @method XdebugJSON
2830
* @namespace Test.CoverageFormat
2832
XdebugJSON: function(coverage){
2835
for (var prop in coverage){
2836
if (coverage.hasOwnProperty(prop)){
2837
report[prop] = coverage[prop].lines;
2841
return YUITest.Util.JSON.stringify(coverage);
2847
* The DateAssert object provides functions to test JavaScript Date objects
2848
* for a variety of cases.
2855
YUITest.DateAssert = {
2858
* Asserts that a date's month, day, and year are equal to another date's.
2859
* @param {Date} expected The expected date.
2860
* @param {Date} actual The actual date to test.
2861
* @param {String} message (Optional) The message to display if the assertion fails.
2862
* @method datesAreEqual
2865
datesAreEqual : function (expected, actual, message){
2866
YUITest.Assert._increment();
2867
if (expected instanceof Date && actual instanceof Date){
2871
if (expected.getFullYear() != actual.getFullYear()){
2872
msg = "Years should be equal.";
2876
if (expected.getMonth() != actual.getMonth()){
2877
msg = "Months should be equal.";
2880
//last, check the day of the month
2881
if (expected.getDate() != actual.getDate()){
2882
msg = "Days of month should be equal.";
2886
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, msg), expected, actual);
2889
throw new TypeError("YUITest.DateAssert.datesAreEqual(): Expected and actual values must be Date objects.");
2894
* Asserts that a date's hour, minutes, and seconds are equal to another date's.
2895
* @param {Date} expected The expected date.
2896
* @param {Date} actual The actual date to test.
2897
* @param {String} message (Optional) The message to display if the assertion fails.
2898
* @method timesAreEqual
2901
timesAreEqual : function (expected, actual, message){
2902
YUITest.Assert._increment();
2903
if (expected instanceof Date && actual instanceof Date){
2907
if (expected.getHours() != actual.getHours()){
2908
msg = "Hours should be equal.";
2912
if (expected.getMinutes() != actual.getMinutes()){
2913
msg = "Minutes should be equal.";
2916
//last, check the seconds
2917
if (expected.getSeconds() != actual.getSeconds()){
2918
msg = "Seconds should be equal.";
2922
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, msg), expected, actual);
2925
throw new TypeError("YUITest.DateAssert.timesAreEqual(): Expected and actual values must be Date objects.");
2930
* Creates a new mock object.
2935
* @param {Object} template (Optional) An object whose methods
2936
* should be stubbed out on the mock object.
2938
YUITest.Mock = function(template){
2940
//use blank object is nothing is passed in
2941
template = template || {};
2946
//try to create mock that keeps prototype chain intact
2947
//fails in the case of ActiveX objects
2950
f.prototype = template;
2956
//create stubs for all methods
2957
for (name in template){
2958
if (template.hasOwnProperty(name)){
2959
if (typeof template[name] == "function"){
2960
mock[name] = function(name){
2962
YUITest.Assert.fail("Method " + name + "() was called but was not expected to be.");
2974
* Assigns an expectation to a mock object. This is used to create
2975
* methods and properties on the mock object that are monitored for
2976
* calls and changes, respectively.
2977
* @param {Object} mock The object to add the expectation to.
2978
* @param {Object} expectation An object defining the expectation. For
2979
* properties, the keys "property" and "value" are required. For a
2980
* method the "method" key defines the method's name, the optional "args"
2981
* key provides an array of argument types. The "returns" key provides
2982
* an optional return value. An optional "run" key provides a function
2983
* to be used as the method body. The return value of a mocked method is
2984
* determined first by the "returns" key, then the "run" function's return
2985
* value. If neither "returns" nor "run" is provided undefined is returned.
2986
* An optional 'error' key defines an error type to be thrown in all cases.
2987
* The "callCount" key provides an optional number of times the method is
2988
* expected to be called (the default is 1).
2993
YUITest.Mock.expect = function(mock /*:Object*/, expectation /*:Object*/){
2995
//make sure there's a place to store the expectations
2996
if (!mock.__expectations) {
2997
mock.__expectations = {};
3000
//method expectation
3001
if (expectation.method){
3002
var name = expectation.method,
3003
args = expectation.args || [],
3004
result = expectation.returns,
3005
callCount = (typeof expectation.callCount == "number") ? expectation.callCount : 1,
3006
error = expectation.error,
3007
run = expectation.run || function(){},
3012
mock.__expectations[name] = expectation;
3013
expectation.callCount = callCount;
3014
expectation.actualCallCount = 0;
3017
for (i=0; i < args.length; i++){
3018
if (!(args[i] instanceof YUITest.Mock.Value)){
3019
args[i] = YUITest.Mock.Value(YUITest.Assert.areSame, [args[i]], "Argument " + i + " of " + name + "() is incorrect.");
3023
//if the method is expected to be called
3025
mock[name] = function(){
3027
expectation.actualCallCount++;
3028
YUITest.Assert.areEqual(args.length, arguments.length, "Method " + name + "() passed incorrect number of arguments.");
3029
for (var i=0, len=args.length; i < len; i++){
3030
args[i].verify(arguments[i]);
3033
runResult = run.apply(this, arguments);
3039
//route through TestRunner for proper handling
3040
YUITest.TestRunner._handleError(ex);
3043
// Any value provided for 'returns' overrides any value returned
3044
// by our 'run' function.
3045
return expectation.hasOwnProperty('returns') ? result : runResult;
3049
//method should fail if called when not expected
3050
mock[name] = function(){
3052
YUITest.Assert.fail("Method " + name + "() should not have been called.");
3054
//route through TestRunner for proper handling
3055
YUITest.TestRunner._handleError(ex);
3059
} else if (expectation.property){
3061
mock.__expectations[expectation.property] = expectation;
3066
* Verifies that all expectations of a mock object have been met and
3067
* throws an assertion error if not.
3068
* @param {Object} mock The object to verify..
3073
YUITest.Mock.verify = function(mock){
3076
for (var name in mock.__expectations){
3077
if (mock.__expectations.hasOwnProperty(name)){
3078
var expectation = mock.__expectations[name];
3079
if (expectation.method) {
3080
YUITest.Assert.areEqual(expectation.callCount, expectation.actualCallCount, "Method " + expectation.method + "() wasn't called the expected number of times.");
3081
} else if (expectation.property){
3082
YUITest.Assert.areEqual(expectation.value, mock[expectation.property], "Property " + expectation.property + " wasn't set to the correct value.");
3088
//route through TestRunner for proper handling
3089
YUITest.TestRunner._handleError(ex);
3094
* Creates a new value matcher.
3095
* @param {Function} method The function to call on the value.
3096
* @param {Array} originalArgs (Optional) Array of arguments to pass to the method.
3097
* @param {String} message (Optional) Message to display in case of failure.
3098
* @namespace Test.Mock
3103
YUITest.Mock.Value = function(method, originalArgs, message){
3104
if (this instanceof YUITest.Mock.Value){
3105
this.verify = function(value){
3106
var args = [].concat(originalArgs || []);
3109
method.apply(null, args);
3112
return new YUITest.Mock.Value(method, originalArgs, message);
3117
* Predefined matcher to match any value.
3122
YUITest.Mock.Value.Any = YUITest.Mock.Value(function(){});
3125
* Predefined matcher to match boolean values.
3130
YUITest.Mock.Value.Boolean = YUITest.Mock.Value(YUITest.Assert.isBoolean);
3133
* Predefined matcher to match number values.
3138
YUITest.Mock.Value.Number = YUITest.Mock.Value(YUITest.Assert.isNumber);
3141
* Predefined matcher to match string values.
3146
YUITest.Mock.Value.String = YUITest.Mock.Value(YUITest.Assert.isString);
3149
* Predefined matcher to match object values.
3154
YUITest.Mock.Value.Object = YUITest.Mock.Value(YUITest.Assert.isObject);
3157
* Predefined matcher to match function values.
3158
* @property Function
3162
YUITest.Mock.Value.Function = YUITest.Mock.Value(YUITest.Assert.isFunction);
3165
* The ObjectAssert object provides functions to test JavaScript objects
3166
* for a variety of cases.
3169
* @class ObjectAssert
3172
YUITest.ObjectAssert = {
3175
* Asserts that an object has all of the same properties
3176
* and property values as the other.
3177
* @param {Object} expected The object with all expected properties and values.
3178
* @param {Object} actual The object to inspect.
3179
* @param {String} message (Optional) The message to display if the assertion fails.
3184
areEqual: function(expected, actual, message) {
3185
YUITest.Assert._increment();
3187
var expectedKeys = YUITest.Object.keys(expected),
3188
actualKeys = YUITest.Object.keys(actual);
3190
//first check keys array length
3191
if (expectedKeys.length != actualKeys.length){
3192
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Object should have " + expectedKeys.length + " keys but has " + actualKeys.length));
3196
for (var name in expected){
3197
if (expected.hasOwnProperty(name)){
3198
if (expected[name] != actual[name]){
3199
throw new YUITest.ComparisonFailure(YUITest.Assert._formatMessage(message, "Values should be equal for property " + name), expected[name], actual[name]);
3206
* Asserts that an object has a property with the given name.
3207
* @param {String} propertyName The name of the property to test.
3208
* @param {Object} object The object to search.
3209
* @param {String} message (Optional) The message to display if the assertion fails.
3212
* @deprecated Use ownsOrInheritsKey() instead
3214
hasKey: function (propertyName, object, message) {
3215
YUITest.ObjectAssert.ownsOrInheritsKey(propertyName, object, message);
3219
* Asserts that an object has all properties of a reference object.
3220
* @param {Array} properties An array of property names that should be on the object.
3221
* @param {Object} object The object to search.
3222
* @param {String} message (Optional) The message to display if the assertion fails.
3225
* @deprecated Use ownsOrInheritsKeys() instead
3227
hasKeys: function (properties, object, message) {
3228
YUITest.ObjectAssert.ownsOrInheritsKeys(properties, object, message);
3232
* Asserts that a property with the given name exists on an object's prototype.
3233
* @param {String} propertyName The name of the property to test.
3234
* @param {Object} object The object to search.
3235
* @param {String} message (Optional) The message to display if the assertion fails.
3236
* @method inheritsKey
3239
inheritsKey: function (propertyName, object, message) {
3240
YUITest.Assert._increment();
3241
if (!(propertyName in object && !object.hasOwnProperty(propertyName))){
3242
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object instance."));
3247
* Asserts that all properties exist on an object prototype.
3248
* @param {Array} properties An array of property names that should be on the object.
3249
* @param {Object} object The object to search.
3250
* @param {String} message (Optional) The message to display if the assertion fails.
3251
* @method inheritsKeys
3254
inheritsKeys: function (properties, object, message) {
3255
YUITest.Assert._increment();
3256
for (var i=0; i < properties.length; i++){
3257
if (!(propertyName in object && !object.hasOwnProperty(properties[i]))){
3258
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object instance."));
3264
* Asserts that a property with the given name exists on an object instance (not on its prototype).
3265
* @param {String} propertyName The name of the property to test.
3266
* @param {Object} object The object to search.
3267
* @param {String} message (Optional) The message to display if the assertion fails.
3271
ownsKey: function (propertyName, object, message) {
3272
YUITest.Assert._increment();
3273
if (!object.hasOwnProperty(propertyName)){
3274
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object instance."));
3279
* Asserts that all properties exist on an object instance (not on its prototype).
3280
* @param {Array} properties An array of property names that should be on the object.
3281
* @param {Object} object The object to search.
3282
* @param {String} message (Optional) The message to display if the assertion fails.
3286
ownsKeys: function (properties, object, message) {
3287
YUITest.Assert._increment();
3288
for (var i=0; i < properties.length; i++){
3289
if (!object.hasOwnProperty(properties[i])){
3290
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object instance."));
3296
* Asserts that an object owns no properties.
3297
* @param {Object} object The object to check.
3298
* @param {String} message (Optional) The message to display if the assertion fails.
3299
* @method ownsNoKeys
3302
ownsNoKeys : function (object, message) {
3303
YUITest.Assert._increment();
3306
for (name in object){
3307
if (object.hasOwnProperty(name)){
3313
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Object owns " + count + " properties but should own none."));
3319
* Asserts that an object has a property with the given name.
3320
* @param {String} propertyName The name of the property to test.
3321
* @param {Object} object The object to search.
3322
* @param {String} message (Optional) The message to display if the assertion fails.
3323
* @method ownsOrInheritsKey
3326
ownsOrInheritsKey: function (propertyName, object, message) {
3327
YUITest.Assert._increment();
3328
if (!(propertyName in object)){
3329
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object."));
3334
* Asserts that an object has all properties of a reference object.
3335
* @param {Array} properties An array of property names that should be on the object.
3336
* @param {Object} object The object to search.
3337
* @param {String} message (Optional) The message to display if the assertion fails.
3338
* @method ownsOrInheritsKeys
3341
ownsOrInheritsKeys: function (properties, object, message) {
3342
YUITest.Assert._increment();
3343
for (var i=0; i < properties.length; i++){
3344
if (!(properties[i] in object)){
3345
YUITest.Assert.fail(YUITest.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object."));
3351
* Convenience type for storing and aggregating
3352
* test result information.
3358
* @param {String} name The name of the test.
3360
YUITest.Results = function(name){
3363
* Name of the test, test case, or test suite.
3370
* Number of passed tests.
3377
* Number of failed tests.
3384
* Number of errors that occur in non-test methods.
3391
* Number of ignored tests.
3398
* Number of total tests.
3405
* Amount of time (ms) it took to complete testing.
3407
* @property duration
3413
* Includes results from another results object into this one.
3414
* @param {Test.Results} result The results object to include.
3418
YUITest.Results.prototype.include = function(results){
3419
this.passed += results.passed;
3420
this.failed += results.failed;
3421
this.ignored += results.ignored;
3422
this.total += results.total;
3423
this.errors += results.errors;
3426
* ShouldError is subclass of Error that is thrown whenever
3427
* a test is expected to throw an error but doesn't.
3429
* @param {String} message The message to display when the error occurs.
3431
* @extends AssertionError
3433
* @class ShouldError
3436
YUITest.ShouldError = function (message){
3439
YUITest.AssertionError.call(this, message || "This test should have thrown an error but didn't.");
3442
* The name of the error that occurred.
3446
this.name = "ShouldError";
3450
//inherit from YUITest.AssertionError
3451
YUITest.ShouldError.prototype = new YUITest.AssertionError();
3453
//restore constructor
3454
YUITest.ShouldError.prototype.constructor = YUITest.ShouldError;
3456
* ShouldFail is subclass of AssertionError that is thrown whenever
3457
* a test was expected to fail but did not.
3459
* @param {String} message The message to display when the error occurs.
3461
* @extends YUITest.AssertionError
3466
YUITest.ShouldFail = function (message){
3469
YUITest.AssertionError.call(this, message || "This test should fail but didn't.");
3472
* The name of the error that occurred.
3476
this.name = "ShouldFail";
3480
//inherit from YUITest.AssertionError
3481
YUITest.ShouldFail.prototype = new YUITest.AssertionError();
3483
//restore constructor
3484
YUITest.ShouldFail.prototype.constructor = YUITest.ShouldFail;
3486
* UnexpectedError is subclass of AssertionError that is thrown whenever
3487
* an error occurs within the course of a test and the test was not expected
3488
* to throw an error.
3490
* @param {Error} cause The unexpected error that caused this error to be
3493
* @extends YUITest.AssertionError
3495
* @class UnexpectedError
3498
YUITest.UnexpectedError = function (cause){
3501
YUITest.AssertionError.call(this, "Unexpected error: " + cause.message);
3504
* The unexpected error that occurred.
3511
* The name of the error that occurred.
3515
this.name = "UnexpectedError";
3518
* Stack information for the error (if provided).
3522
this.stack = cause.stack;
3526
//inherit from YUITest.AssertionError
3527
YUITest.UnexpectedError.prototype = new YUITest.AssertionError();
3529
//restore constructor
3530
YUITest.UnexpectedError.prototype.constructor = YUITest.UnexpectedError;
3532
* UnexpectedValue is subclass of Error that is thrown whenever
3533
* a value was unexpected in its scope. This typically means that a test
3534
* was performed to determine that a value was *not* equal to a certain
3537
* @param {String} message The message to display when the error occurs.
3538
* @param {Object} unexpected The unexpected value.
3540
* @extends AssertionError
3542
* @class UnexpectedValue
3545
YUITest.UnexpectedValue = function (message, unexpected){
3548
YUITest.AssertionError.call(this, message);
3551
* The unexpected value.
3553
* @property unexpected
3555
this.unexpected = unexpected;
3558
* The name of the error that occurred.
3562
this.name = "UnexpectedValue";
3566
//inherit from YUITest.AssertionError
3567
YUITest.UnexpectedValue.prototype = new YUITest.AssertionError();
3569
//restore constructor
3570
YUITest.UnexpectedValue.prototype.constructor = YUITest.UnexpectedValue;
3573
* Returns a fully formatted error for an assertion failure. This message
3574
* provides information about the expected and actual values.
3575
* @method getMessage
3576
* @return {String} A string describing the error.
3578
YUITest.UnexpectedValue.prototype.getMessage = function(){
3579
return this.message + "\nUnexpected: " + this.unexpected + " (" + (typeof this.unexpected) + ") ";
3583
* Represents a stoppage in test execution to wait for an amount of time before
3585
* @param {Function} segment A function to run when the wait is over.
3586
* @param {int} delay The number of milliseconds to wait before running the code.
3593
YUITest.Wait = function (segment, delay) {
3596
* The segment of code to run when the wait is over.
3600
this.segment = (typeof segment == "function" ? segment : null);
3603
* The delay before running the segment of code.
3607
this.delay = (typeof delay == "number" ? delay : 0);
3611
//Setting up our aliases..
3613
Y.Object.each(YUITest, function(item, name) {
3614
var name = name.replace('Test', '');
3615
Y.Test[name] = item;
3618
} //End of else in top wrapper
3620
Y.Assert = YUITest.Assert;
3621
Y.Assert.Error = Y.Test.AssertionError;
3622
Y.Assert.ComparisonFailure = Y.Test.ComparisonFailure;
3623
Y.Assert.UnexpectedValue = Y.Test.UnexpectedValue;
3624
Y.Mock = Y.Test.Mock;
3625
Y.ObjectAssert = Y.Test.ObjectAssert;
3626
Y.ArrayAssert = Y.Test.ArrayAssert;
3627
Y.DateAssert = Y.Test.DateAssert;
3628
Y.Test.ResultsFormat = Y.Test.TestFormat;
3630
var itemsAreEqual = Y.Test.ArrayAssert.itemsAreEqual;
3632
Y.Test.ArrayAssert.itemsAreEqual = function(expected, actual, message) {
3633
return itemsAreEqual.call(this, Y.Array(expected), Y.Array(actual), message);
3638
* Asserts that a given condition is true. If not, then a Y.Assert.Error object is thrown
3639
* and the test fails.
3641
* @param {Boolean} condition The condition to test.
3642
* @param {String} message The message to display if the assertion fails.
3646
Y.assert = function(condition, message){
3647
Y.Assert._increment();
3649
throw new Y.Assert.Error(Y.Assert._formatMessage(message, "Assertion failed."));
3654
* Forces an assertion error to occur. Shortcut for Y.Assert.fail().
3656
* @param {String} message (Optional) The message to display with the failure.
3660
Y.fail = Y.Assert.fail;
3662
Y.Test.Runner.once = Y.Test.Runner.subscribe;
3664
Y.Test.Runner.disableLogging = function() {
3665
Y.Test.Runner._log = false;
3668
Y.Test.Runner.enableLogging = function() {
3669
Y.Test.Runner._log = true;
3672
Y.Test.Runner._ignoreEmpty = true;
3673
Y.Test.Runner._log = true;
3675
Y.Test.Runner.on = Y.Test.Runner.attach;
3677
//Only allow one instance of YUITest
3681
Y.config.win.YUITest = YUITest;
3684
YUI.YUITest = Y.Test;
3687
//Only setup the listeners once.
3688
var logEvent = function(event) {
3692
var messageType = "";
3695
case this.BEGIN_EVENT:
3696
message = "Testing began at " + (new Date()).toString() + ".";
3697
messageType = "info";
3700
case this.COMPLETE_EVENT:
3701
message = Y.Lang.sub("Testing completed at " +
3702
(new Date()).toString() + ".\n" +
3703
"Passed:{passed} Failed:{failed} " +
3704
"Total:{total} ({ignored} ignored)",
3706
messageType = "info";
3709
case this.TEST_FAIL_EVENT:
3710
message = event.testName + ": failed.\n" + event.error.getMessage();
3711
messageType = "fail";
3714
case this.TEST_IGNORE_EVENT:
3715
message = event.testName + ": ignored.";
3716
messageType = "ignore";
3719
case this.TEST_PASS_EVENT:
3720
message = event.testName + ": passed.";
3721
messageType = "pass";
3724
case this.TEST_SUITE_BEGIN_EVENT:
3725
message = "Test suite \"" + event.testSuite.name + "\" started.";
3726
messageType = "info";
3729
case this.TEST_SUITE_COMPLETE_EVENT:
3730
message = Y.Lang.sub("Test suite \"" +
3731
event.testSuite.name + "\" completed" + ".\n" +
3732
"Passed:{passed} Failed:{failed} " +
3733
"Total:{total} ({ignored} ignored)",
3735
messageType = "info";
3738
case this.TEST_CASE_BEGIN_EVENT:
3739
message = "Test case \"" + event.testCase.name + "\" started.";
3740
messageType = "info";
3743
case this.TEST_CASE_COMPLETE_EVENT:
3744
message = Y.Lang.sub("Test case \"" +
3745
event.testCase.name + "\" completed.\n" +
3746
"Passed:{passed} Failed:{failed} " +
3747
"Total:{total} ({ignored} ignored)",
3749
messageType = "info";
3752
message = "Unexpected event " + event.type;
3753
messageType = "info";
3756
if (Y.Test.Runner._log) {
3757
Y.log(message, messageType, "TestRunner");
3763
for (i in Y.Test.Runner) {
3764
name = Y.Test.Runner[i];
3765
if (i.indexOf('_EVENT') > -1) {
3766
Y.Test.Runner.subscribe(name, logEvent);
3770
} //End if for YUI.YUITest
3773
}, '3.10.3', {"requires": ["event-simulate", "event-custom", "json-stringify"]});