├── .gitignore
├── .travis.yml
├── Gruntfile.js
├── LICENSE.txt
├── README.md
├── dist
├── enum.js
└── enum.min.js
├── package.json
└── src
├── enum.js
├── lib
└── qunit
│ ├── qunit-1.19.0.css
│ └── qunit-1.19.0.js
└── test
├── test-enumjs.html
└── test-enumjs.js
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | dist/report
3 | dist/test-reports
4 | node_modules
5 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "0.12"
4 | before_script:
5 | - npm install -g grunt-cli
6 | - grunt travis
7 | script:
8 | - grunt coveralls
9 |
--------------------------------------------------------------------------------
/Gruntfile.js:
--------------------------------------------------------------------------------
1 | module.exports = function (grunt) {
2 |
3 | grunt.loadNpmTasks('grunt-contrib-requirejs');
4 | grunt.loadNpmTasks('grunt-contrib-qunit');
5 | grunt.loadNpmTasks('grunt-qunit-junit');
6 | grunt.loadNpmTasks('grunt-bg-shell');
7 | grunt.loadNpmTasks('grunt-qunit-istanbul');
8 | grunt.loadNpmTasks('grunt-coveralls');
9 |
10 | grunt.initConfig({
11 | pkg: grunt.file.readJSON('package.json'),
12 |
13 | requirejs: {
14 | compile: {
15 | options: {
16 | baseUrl: "src",
17 | name: "enum",
18 | uglify: {
19 | except: ["__"]
20 | },
21 | out: "dist/enum.min.js"
22 | }
23 | },
24 | test: {
25 | options: {
26 | baseUrl: "src",
27 | name: "enum",
28 | out: "dist/enum.js",
29 | optimize: "none"
30 | }
31 | }
32 | },
33 |
34 | qunit: {
35 | options: {
36 | '--web-security': 'no',
37 | coverage: {
38 | src: ['dist/enum.js'],
39 | instrumentedFiles: 'temp/',
40 | htmlReport: 'dist/report/coverage',
41 | lcovReport: 'dist/report/lcov',
42 | coberturaReport: 'dist/report/',
43 | linesThresholdPct: 85
44 | }
45 | },
46 | all: ['src/test/test-enumjs.html']
47 | },
48 |
49 | qunit_junit: {
50 | options: {
51 | dest: 'dist/test-reports'
52 | }
53 | },
54 |
55 | coveralls: {
56 | options: {
57 | force: false
58 | },
59 | main_target: {
60 | src: 'dist/report/lcov/lcov.info'
61 | }
62 | }
63 | });
64 |
65 | grunt.registerTask('build', ['requirejs:compile', 'requirejs:test']);
66 | grunt.registerTask('test', ['requirejs:test', 'qunit_junit', 'qunit']);
67 | grunt.registerTask('travis', ['test']);
68 | };
69 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright (c) 2015 Vivin Paliath . All rights reserved.
2 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
3 |
4 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
5 |
6 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
7 |
8 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
9 |
10 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | enumjs
7 | ======
8 |
9 | This is an attempt at realizing type-safe enums in JavaScript. I'm most familiar with the way enums work in Java, and so I modeled this library after that. JavaScript doesn't have true enums. Most workarounds to this problem involve using a map where the keys represent the enum constants, and the values are integers or string-representations of the enum constants. This is a convenient solution, but the main problem is that you don't really get any type-safety since the values are just regular JavaScript types. This means that you can't even do `instanceof` checks, and you have to resort to checking the value against all defined-values to see if it is valid.
10 |
11 | I figured there must be a better way to realize enums in JavaScript while addressing these shortcomings, and this is my attempt to do that. As far as I can tell, this works like one would expect, but I'm sure there are things I haven't considered. So here's what you get with **enumjs**:
12 |
13 | - The ability to define your own enum and its constants.
14 | - Your custom enum is its own type, and all its constants are instances of the enum itself. This means that you *can* do `instanceof` checks.
15 | - The custom enum has a `values` and a `fromName`\* method. The former returns an array of all constants defined on the enum, and the latter will attempt to return an enum consant with the same name as the string that is passed in. If one does not exist, an exception is thrown.
16 | - Each enum constant has a `name()` and an `ordinal()` method. The `name()` method returns a string representing the name of the constant (as defined), and `ordinal()` returns the position of the constant (as defined).
17 | - Once defined, the enum type and its constants are immutable.
18 |
19 | \* In Java the method is actually called `valueOf` and that's what I named it here originally as well. However, JavaScript has its own `valueOf` method on objects that does something else entirely, and I didn't want to override that behavior.
20 |
21 | This works on the browser, in Nashorn, and on Node. The library exposes a single object (called `Enum` if you're on the browser or have loaded the file in Nashorn) with a method called `define`. The signature is `Enum.define(, | )`.
22 |
23 | The current version is 1.0.2 and is available [here](https://github.com/vivin/enumjs/releases/tag/v1.0.2). The library is also available as a node package called [**node-enumjs**](https://www.npmjs.com/package/node-enumjs). To install, just run `npm install node-enumjs`. Then you can use it like so:
24 |
25 | ```javascript
26 | var Enum = require('node-enumjs');
27 | ```
28 | Examples
29 | --------
30 |
31 | ```javascript
32 | var Days = Enum.define("Days", ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]);
33 |
34 | Days.Monday instanceof Days; // true
35 |
36 | Days.Friday.name(); // "Friday"
37 | Days.Friday.ordinal(); // 4
38 |
39 | Days.Sunday === Days.Sunday; // true
40 | Days.Sunday === Days.Friday; // false
41 |
42 | Days.Sunday.toString(); // "Sunday"
43 |
44 | Days.toString() // "Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } "
45 |
46 | Days.values().map(function(e) { return e.name(); }); //["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
47 | Days.values()[4].name(); //"Friday"
48 |
49 | Days.fromName("Thursday") === Days.Thursday // true
50 | Days.fromName("Wednesday").name() // "Wednesday"
51 | Days.Friday.fromName("Saturday").name() // "Saturday"
52 | ```
53 |
54 | You can also attach behavior to each constant, just like in Java. To do that, you need to pass in a definition object that looks like this:
55 |
56 | ```javascript
57 | var Days = Enum.define("Days", {
58 | constants: {
59 | Monday: {
60 | say: function () {
61 | return this.name() + "s are bad!";
62 | }
63 | },
64 | Tuesday: {
65 | say: function () {
66 | return this.name() + "s are ok...";
67 | }
68 | },
69 | Wednesday: {
70 | say: function () {
71 | return this.name() + " is the middle of the week...";
72 | }
73 | },
74 | Thursday: {
75 | say: function () {
76 | return this.name() + "! We're getting closer to the weekend!";
77 | }
78 | },
79 | Friday: {
80 | say: function () {
81 | return this.name() + ", " + this.name() + ", Gettin' down on " + this.name() + "!";
82 | }
83 | },
84 | Saturday: {
85 | say: function () {
86 | return this.name() + "! Aw yisss time for cartoons!";
87 | }
88 | },
89 | Sunday: {
90 | say: function () {
91 | return this.name() + "! It's still the weekend!";
92 | }
93 | }
94 | }
95 | });
96 |
97 | Days.Monday.say(); // "Mondays are bad!"
98 | Days.Friday.say(); // "Friday, Friday, Gettin' down on Friday!"
99 | ```
100 |
101 | Sometimes you may want to have similar behavior that is shared among all constants. But doing that in the above manner is tedious and repetitive. Instead, you can pass in the optional attribute `methods`. All values defined in this object must be functions, and these functions will be attached to every constant of the enum. To demonstrate this, here's an example that's based on the [Planet example](https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html) from the Java documentation on enums:
102 |
103 | ```javascript
104 | var Planet = Enum.define("Planet", {
105 | constants: {
106 | MERCURY: {
107 | mass: 3.303e+23,
108 | radius: 2.4397e6
109 | },
110 | VENUS: {
111 | mass: 4.869e+24,
112 | radius: 6.0518e6
113 | },
114 | EARTH: {
115 | mass: 5.976e+24,
116 | radius: 6.37814e6
117 | },
118 | MARS: {
119 | mass: 6.421e+23,
120 | radius: 3.3972e6
121 | },
122 | JUPITER: {
123 | mass: 1.9e+27,
124 | radius: 7.1492e7
125 | },
126 | SATURN: {
127 | mass: 5.688e+26,
128 | radius: 6.0268e7
129 | },
130 | URANUS: {
131 | mass: 8.686e+25,
132 | radius: 2.5559e7
133 | },
134 | NEPTUNE: {
135 | mass: 1.024e+26,
136 | radius: 2.4746e7
137 | }
138 | },
139 | methods: {
140 | surfaceGravity: function() {
141 | var G = 6.67300E-11;
142 | return (G * this.mass) / Math.pow(this.radius, 2);
143 | },
144 | surfaceWeight: function(mass) {
145 | return mass * this.surfaceGravity();
146 | }
147 | }
148 | });
149 |
150 | var mass = 175 / Planet.EARTH.surfaceGravity();
151 | Planet.values().forEach(function(planet) {
152 | console.log("Your weight on", planet.toString(), "is", planet.surfaceWeight(mass));
153 | });
154 | ```
155 |
156 | This returns the output:
157 |
158 | ```
159 | Your weight on MERCURY is 66.10758266016366
160 | Your weight on VENUS is 158.37484247218296
161 | Your weight on EARTH is 174.99999999999997
162 | Your weight on MARS is 66.27900720649754
163 | Your weight on JUPITER is 442.8475669617546
164 | Your weight on SATURN is 186.55271929202414
165 | Your weight on URANUS is 158.39725989314937
166 | Your weight on NEPTUNE is 199.20741268219012
167 | ```
168 |
169 | That's pretty much it. Please try it out and let me know what you think, and if there are any issues, etc.
170 |
--------------------------------------------------------------------------------
/dist/enum.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @preserve
3 | * enum.js - Type-safe enums in JavaScript. Modeled after Java enums.
4 | * Version 1.0.2
5 | * Written by Vivin Paliath (http://vivin.net)
6 | * License: BSD License
7 | * Copyright (C) 2015
8 | */
9 |
10 | (function (root, factory) {
11 | if (typeof define === 'function' && define.amd) {
12 | define('enum',[], factory);
13 | } else if (typeof module === 'object' && module.exports) {
14 | module.exports = factory();
15 | } else {
16 | root.Enum = factory();
17 | }
18 | }(this, function () {
19 | /**
20 | * Function to define an enum
21 | * @param typeName - The name of the enum.
22 | * @param definition - The definition on the enum. Can be an array of strings, or an object where each key is an enum
23 | * constant, and the values are objects that describe attributes that can be attached to the associated constant.
24 | */
25 | function define(typeName, definition) {
26 |
27 | /** Check Arguments **/
28 | if (typeof typeName === "undefined") {
29 | throw new TypeError("A name is required.");
30 | }
31 |
32 | if (!/^[a-z$_][0-9a-z$_]*$/i.test(typeName)) {
33 | throw new TypeError("Invalid enum name. Enum names can only consist of numbers, letters, $, and _, and can only start with letters, $, or _.");
34 | }
35 |
36 | if(typeof definition === "undefined") {
37 | throw new TypeError("Constants are required.");
38 | }
39 |
40 | if (!(definition instanceof Array) && (Object.getPrototypeOf(definition) !== Object.prototype)) {
41 |
42 | throw new TypeError("The definition parameter must either be an array or an object.");
43 |
44 | } else if ((definition instanceof Array) && definition.length === 0) {
45 |
46 | throw new TypeError("Need to provide at least one constant.");
47 |
48 | } else if ((definition instanceof Array) && !definition.reduce(function (isString, element) {
49 | return isString && (typeof element === "string");
50 | }, true)) {
51 |
52 | throw new TypeError("One or more elements in the constant array is not a string.");
53 |
54 | } else if (Object.getPrototypeOf(definition) === Object.prototype) {
55 |
56 | definition.methods = definition.methods || {};
57 |
58 | if(typeof(definition.constants) === "undefined") {
59 |
60 | throw new TypeError("If definition is an object, it must have a constants attribute.");
61 |
62 | } else if(Object.keys(definition.constants).length === 0) {
63 |
64 | throw new TypeError("constants attribute in definition cannot be empty.");
65 |
66 | } else if(!Object.keys(definition.constants).reduce(function (isObject, constant) {
67 | return Object.getPrototypeOf(definition.constants[constant]) === Object.prototype;
68 | }, true)) {
69 |
70 | throw new TypeError("One or more values in the definition.constants object is not an object.");
71 |
72 | } else if(!Object.keys(definition.methods).reduce(function (isFunction, method) {
73 | return isFunction && (typeof definition.methods[method] === "function");
74 | }, true)) {
75 |
76 | throw new TypeError("One or more values in the definition.methods object is not a function.");
77 |
78 | }
79 | }
80 |
81 | var isArray = (definition instanceof Array);
82 | var isObject = !isArray;
83 |
84 | /** Private sentinel-object used to guard enum constructor so that no one else can create enum instances **/
85 | function __() { };
86 |
87 | /** Dynamically define a function using typeName.
88 | *
89 | * The name of the constructor for every enum constant ends up being __. This is done deliberately, so
90 | * that the dynamic function's name won't clash with anything else. For example, someone could attempt to define
91 | * an enum with typeName set to `__`. This would cause an error because it clashes with the name of the sentinel
92 | * object. However, that is not apparent to the user at all and the behavior just seems mystifying. This is also
93 | * a form of abstraction leakage, and that's not good either.
94 | */
95 | var _enum = new Function(["__"],
96 | "return function __" + typeName + "(sentinel, name, ordinal) {\n" +
97 | "\tif(!(sentinel instanceof __)) {\n" +
98 | "\t\tthrow new TypeError(\"Cannot instantiate an instance of " + typeName + ".\");\n" +
99 | "\t}\n" +
100 |
101 | "\tthis._name = name;\n" +
102 | "\tthis._ordinal = ordinal;\n" +
103 | "}\n"
104 | )(__);
105 |
106 | /** Private objects used to maintain enum instances for values(), and to look up enum instances for fromName() **/
107 | var _values = [];
108 | var _dict = {};
109 |
110 | /** Attach values() and fromName() methods to the class itself (kind of like static methods). **/
111 | Object.defineProperty(_enum, "values", {
112 | value: function () {
113 | return _values;
114 | }
115 | });
116 |
117 | Object.defineProperty(_enum, "fromName", {
118 | value: function (name) {
119 | var _constant = _dict[name];
120 | if (_constant) {
121 | return _constant;
122 | } else {
123 | throw new TypeError(typeName + " does not have a constant with name " + name + ".");
124 | }
125 | }
126 | });
127 |
128 | /**
129 | * The following methods are available to all instances of the enum. values() and fromName() need to be
130 | * available to each constant, and so we will attach them on the prototype. But really, they're just
131 | * aliases to their counterparts on the prototype.
132 | */
133 | Object.defineProperty(_enum.prototype, "values", {
134 | value: _enum.values
135 | });
136 |
137 | Object.defineProperty(_enum.prototype, "fromName", {
138 | value: _enum.fromName
139 | });
140 |
141 | Object.defineProperty(_enum.prototype, "name", {
142 | value: function () {
143 | return this._name;
144 | }
145 | });
146 |
147 | Object.defineProperty(_enum.prototype, "ordinal", {
148 | value: function () {
149 | return this._ordinal;
150 | }
151 | });
152 |
153 | Object.defineProperty(_enum.prototype, "valueOf", {
154 | value: function () {
155 | return this._name;
156 | }
157 | });
158 |
159 | Object.defineProperty(_enum.prototype, "toString", {
160 | value: function () {
161 | return this._name;
162 | }
163 | });
164 |
165 | Object.defineProperty(_enum.prototype, "toJSON", {
166 | value: function () {
167 | return this._name;
168 | }
169 | });
170 |
171 | /**
172 | * If definition was an array, we can the element values directly. Otherwise, we will have to use the keys
173 | * from the definition.constants object. At this time we can also attach any methods (if provided) to the
174 | * prototype so that they are available to every instance.
175 | */
176 | var _constants = definition;
177 | if (isObject) {
178 | _constants = Object.keys(definition.constants);
179 |
180 | Object.keys(definition.methods).forEach(function (method) {
181 | Object.defineProperty(_enum.prototype, method, {
182 | value: definition.methods[method]
183 | });
184 | });
185 | }
186 |
187 | /** Iterate over all definition, create an instance of our enum for each one, and attach it to the enum type **/
188 | _constants.forEach(function (name, ordinal) {
189 | // Create an instance of the enum
190 | var _constant = new _enum(new __(), name, ordinal);
191 |
192 | // If definition was an object, we want to attach the provided constant-attributes to the instance.
193 | if (isObject) {
194 | Object.keys(definition.constants[name]).forEach(function (attr) {
195 | Object.defineProperty(_constant, attr, {
196 | value: definition.constants[name][attr]
197 | });
198 | });
199 | }
200 |
201 | // Freeze the instance so that it cannot be modified.
202 | Object.freeze(_constant);
203 |
204 | // Attach the instance using the provided name to the enum type itself.
205 | Object.defineProperty(_enum, name, {
206 | value: _constant
207 | });
208 |
209 | // Update our private objects
210 | _values.push(_constant);
211 | _dict[name] = _constant;
212 | });
213 |
214 | /** Define a friendly toString method for the enum **/
215 | var string = typeName + " { " + _enum.values().map(function (c) {
216 | return c.name();
217 | }).join(", ") + " }";
218 |
219 | Object.defineProperty(_enum, "toString", {
220 | value: function () {
221 | return string;
222 | }
223 | });
224 |
225 | /** Freeze our private objects **/
226 | Object.freeze(_values);
227 | Object.freeze(_dict);
228 |
229 | /** Freeze the prototype on the enum and the enum itself **/
230 | Object.freeze(_enum.prototype);
231 | Object.freeze(_enum);
232 |
233 | /** Return the enume **/
234 | return _enum;
235 | }
236 |
237 | return {
238 | define: define
239 | }
240 | }));
241 |
242 |
--------------------------------------------------------------------------------
/dist/enum.min.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @preserve
3 | * enum.js - Type-safe enums in JavaScript. Modeled after Java enums.
4 | * Version 1.0.2
5 | * Written by Vivin Paliath (http://vivin.net)
6 | * License: BSD License
7 | * Copyright (C) 2015
8 | */
9 |
10 | (function(e,t){typeof define=="function"&&define.amd?define("enum",[],t):typeof module=="object"&&module.exports?module.exports=t():e.Enum=t()})(this,function(){function e(e,t){function __(){}if(typeof e=="undefined")throw new TypeError("A name is required.");if(!/^[a-z$_][0-9a-z$_]*$/i.test(e))throw new TypeError("Invalid enum name. Enum names can only consist of numbers, letters, $, and _, and can only start with letters, $, or _.");if(typeof t=="undefined")throw new TypeError("Constants are required.");if(t instanceof Array||Object.getPrototypeOf(t)===Object.prototype){if(t instanceof Array&&t.length===0)throw new TypeError("Need to provide at least one constant.");if(t instanceof Array&&!t.reduce(function(e,t){return e&&typeof t=="string"},!0))throw new TypeError("One or more elements in the constant array is not a string.");if(Object.getPrototypeOf(t)===Object.prototype){t.methods=t.methods||{};if(typeof t.constants=="undefined")throw new TypeError("If definition is an object, it must have a constants attribute.");if(Object.keys(t.constants).length===0)throw new TypeError("constants attribute in definition cannot be empty.");if(!Object.keys(t.constants).reduce(function(e,n){return Object.getPrototypeOf(t.constants[n])===Object.prototype},!0))throw new TypeError("One or more values in the definition.constants object is not an object.");if(!Object.keys(t.methods).reduce(function(e,n){return e&&typeof t.methods[n]=="function"},!0))throw new TypeError("One or more values in the definition.methods object is not a function.")}var n=t instanceof Array,r=!n,i=(new Function(["__"],"return function __"+e+"(sentinel, name, ordinal) {\n"+" if(!(sentinel instanceof __)) {\n"+' throw new TypeError("Cannot instantiate an instance of '+e+'.");\n'+" }\n"+" this._name = name;\n"+" this._ordinal = ordinal;\n"+"}\n"))(__),s=[],o={};Object.defineProperty(i,"values",{value:function(){return s}}),Object.defineProperty(i,"fromName",{value:function(t){var n=o[t];if(n)return n;throw new TypeError(e+" does not have a constant with name "+t+".")}}),Object.defineProperty(i.prototype,"values",{value:i.values}),Object.defineProperty(i.prototype,"fromName",{value:i.fromName}),Object.defineProperty(i.prototype,"name",{value:function(){return this._name}}),Object.defineProperty(i.prototype,"ordinal",{value:function(){return this._ordinal}}),Object.defineProperty(i.prototype,"valueOf",{value:function(){return this._name}}),Object.defineProperty(i.prototype,"toString",{value:function(){return this._name}}),Object.defineProperty(i.prototype,"toJSON",{value:function(){return this._name}});var u=t;r&&(u=Object.keys(t.constants),Object.keys(t.methods).forEach(function(e){Object.defineProperty(i.prototype,e,{value:t.methods[e]})})),u.forEach(function(e,n){var u=new i(new __,e,n);r&&Object.keys(t.constants[e]).forEach(function(n){Object.defineProperty(u,n,{value:t.constants[e][n]})}),Object.freeze(u),Object.defineProperty(i,e,{value:u}),s.push(u),o[e]=u});var a=e+" { "+i.values().map(function(e){return e.name()}).join(", ")+" }";return Object.defineProperty(i,"toString",{value:function(){return a}}),Object.freeze(s),Object.freeze(o),Object.freeze(i.prototype),Object.freeze(i),i}throw new TypeError("The definition parameter must either be an array or an object.")}return{define:e}});
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "node-enumjs",
3 | "version": "1.0.2",
4 | "description": "An implementation of type-safe enums in JavaScript (modeled after Java enums)",
5 | "main": "dist/enum.min.js",
6 | "scripts": {
7 | "test": "grunt travis"
8 | },
9 | "devDependencies": {
10 | "coveralls": "~2.11.4",
11 | "grunt": "~0.4.5",
12 | "grunt-qunit-istanbul": "~0.4.5",
13 | "grunt-qunit-junit": "0.3.1",
14 | "grunt-contrib-qunit": "~0.7.0",
15 | "grunt-contrib-requirejs": "~0.4.4",
16 | "grunt-bg-shell": "~2.3.1",
17 | "grunt-lib-phantomjs": "~0.7.1",
18 | "grunt-coveralls": "~1.0.0"
19 | },
20 | "repository": {
21 | "type": "git",
22 | "url": "https://github.com/vivin/enumjs/"
23 | },
24 | "keywords": [
25 | "enumjs",
26 | "node-enumjs",
27 | "enum",
28 | "enums",
29 | "enumeration",
30 | "type-safety"
31 | ],
32 | "author": "Vivin Paliath",
33 | "license": "BSD-3-Clause"
34 | }
35 |
--------------------------------------------------------------------------------
/src/enum.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @preserve
3 | * enum.js - Type-safe enums in JavaScript. Modeled after Java enums.
4 | * Version 1.0.2
5 | * Written by Vivin Paliath (http://vivin.net)
6 | * License: BSD License
7 | * Copyright (C) 2015
8 | */
9 |
10 | (function (root, factory) {
11 | if (typeof define === 'function' && define.amd) {
12 | define([], factory);
13 | } else if (typeof module === 'object' && module.exports) {
14 | module.exports = factory();
15 | } else {
16 | root.Enum = factory();
17 | }
18 | }(this, function () {
19 | /**
20 | * Function to define an enum
21 | * @param typeName - The name of the enum.
22 | * @param definition - The definition on the enum. Can be an array of strings, or an object where each key is an enum
23 | * constant, and the values are objects that describe attributes that can be attached to the associated constant.
24 | */
25 | function define(typeName, definition) {
26 |
27 | /** Check Arguments **/
28 | if (typeof typeName === "undefined") {
29 | throw new TypeError("A name is required.");
30 | }
31 |
32 | if (!/^[a-z$_][0-9a-z$_]*$/i.test(typeName)) {
33 | throw new TypeError("Invalid enum name. Enum names can only consist of numbers, letters, $, and _, and can only start with letters, $, or _.");
34 | }
35 |
36 | if(typeof definition === "undefined") {
37 | throw new TypeError("Constants are required.");
38 | }
39 |
40 | if (!(definition instanceof Array) && (Object.getPrototypeOf(definition) !== Object.prototype)) {
41 |
42 | throw new TypeError("The definition parameter must either be an array or an object.");
43 |
44 | } else if ((definition instanceof Array) && definition.length === 0) {
45 |
46 | throw new TypeError("Need to provide at least one constant.");
47 |
48 | } else if ((definition instanceof Array) && !definition.reduce(function (isString, element) {
49 | return isString && (typeof element === "string");
50 | }, true)) {
51 |
52 | throw new TypeError("One or more elements in the constant array is not a string.");
53 |
54 | } else if (Object.getPrototypeOf(definition) === Object.prototype) {
55 |
56 | definition.methods = definition.methods || {};
57 |
58 | if(typeof(definition.constants) === "undefined") {
59 |
60 | throw new TypeError("If definition is an object, it must have a constants attribute.");
61 |
62 | } else if(Object.keys(definition.constants).length === 0) {
63 |
64 | throw new TypeError("constants attribute in definition cannot be empty.");
65 |
66 | } else if(!Object.keys(definition.constants).reduce(function (isObject, constant) {
67 | return Object.getPrototypeOf(definition.constants[constant]) === Object.prototype;
68 | }, true)) {
69 |
70 | throw new TypeError("One or more values in the definition.constants object is not an object.");
71 |
72 | } else if(!Object.keys(definition.methods).reduce(function (isFunction, method) {
73 | return isFunction && (typeof definition.methods[method] === "function");
74 | }, true)) {
75 |
76 | throw new TypeError("One or more values in the definition.methods object is not a function.");
77 |
78 | }
79 | }
80 |
81 | var isArray = (definition instanceof Array);
82 | var isObject = !isArray;
83 |
84 | /** Private sentinel-object used to guard enum constructor so that no one else can create enum instances **/
85 | function __() { };
86 |
87 | /** Dynamically define a function using typeName.
88 | *
89 | * The name of the constructor for every enum constant ends up being __. This is done deliberately, so
90 | * that the dynamic function's name won't clash with anything else. For example, someone could attempt to define
91 | * an enum with typeName set to `__`. This would cause an error because it clashes with the name of the sentinel
92 | * object. However, that is not apparent to the user at all and the behavior just seems mystifying. This is also
93 | * a form of abstraction leakage, and that's not good either.
94 | */
95 | var _enum = new Function(["__"],
96 | "return function __" + typeName + "(sentinel, name, ordinal) {\n" +
97 | "\tif(!(sentinel instanceof __)) {\n" +
98 | "\t\tthrow new TypeError(\"Cannot instantiate an instance of " + typeName + ".\");\n" +
99 | "\t}\n" +
100 |
101 | "\tthis._name = name;\n" +
102 | "\tthis._ordinal = ordinal;\n" +
103 | "}\n"
104 | )(__);
105 |
106 | /** Private objects used to maintain enum instances for values(), and to look up enum instances for fromName() **/
107 | var _values = [];
108 | var _dict = {};
109 |
110 | /** Attach values() and fromName() methods to the class itself (kind of like static methods). **/
111 | Object.defineProperty(_enum, "values", {
112 | value: function () {
113 | return _values;
114 | }
115 | });
116 |
117 | Object.defineProperty(_enum, "fromName", {
118 | value: function (name) {
119 | var _constant = _dict[name];
120 | if (_constant) {
121 | return _constant;
122 | } else {
123 | throw new TypeError(typeName + " does not have a constant with name " + name + ".");
124 | }
125 | }
126 | });
127 |
128 | /**
129 | * The following methods are available to all instances of the enum. values() and fromName() need to be
130 | * available to each constant, and so we will attach them on the prototype. But really, they're just
131 | * aliases to their counterparts on the prototype.
132 | */
133 | Object.defineProperty(_enum.prototype, "values", {
134 | value: _enum.values
135 | });
136 |
137 | Object.defineProperty(_enum.prototype, "fromName", {
138 | value: _enum.fromName
139 | });
140 |
141 | Object.defineProperty(_enum.prototype, "name", {
142 | value: function () {
143 | return this._name;
144 | }
145 | });
146 |
147 | Object.defineProperty(_enum.prototype, "ordinal", {
148 | value: function () {
149 | return this._ordinal;
150 | }
151 | });
152 |
153 | Object.defineProperty(_enum.prototype, "valueOf", {
154 | value: function () {
155 | return this._name;
156 | }
157 | });
158 |
159 | Object.defineProperty(_enum.prototype, "toString", {
160 | value: function () {
161 | return this._name;
162 | }
163 | });
164 |
165 | Object.defineProperty(_enum.prototype, "toJSON", {
166 | value: function () {
167 | return this._name;
168 | }
169 | });
170 |
171 | /**
172 | * If definition was an array, we can the element values directly. Otherwise, we will have to use the keys
173 | * from the definition.constants object. At this time we can also attach any methods (if provided) to the
174 | * prototype so that they are available to every instance.
175 | */
176 | var _constants = definition;
177 | if (isObject) {
178 | _constants = Object.keys(definition.constants);
179 |
180 | Object.keys(definition.methods).forEach(function (method) {
181 | Object.defineProperty(_enum.prototype, method, {
182 | value: definition.methods[method]
183 | });
184 | });
185 | }
186 |
187 | /** Iterate over all definition, create an instance of our enum for each one, and attach it to the enum type **/
188 | _constants.forEach(function (name, ordinal) {
189 | // Create an instance of the enum
190 | var _constant = new _enum(new __(), name, ordinal);
191 |
192 | // If definition was an object, we want to attach the provided constant-attributes to the instance.
193 | if (isObject) {
194 | Object.keys(definition.constants[name]).forEach(function (attr) {
195 | Object.defineProperty(_constant, attr, {
196 | value: definition.constants[name][attr]
197 | });
198 | });
199 | }
200 |
201 | // Freeze the instance so that it cannot be modified.
202 | Object.freeze(_constant);
203 |
204 | // Attach the instance using the provided name to the enum type itself.
205 | Object.defineProperty(_enum, name, {
206 | value: _constant
207 | });
208 |
209 | // Update our private objects
210 | _values.push(_constant);
211 | _dict[name] = _constant;
212 | });
213 |
214 | /** Define a friendly toString method for the enum **/
215 | var string = typeName + " { " + _enum.values().map(function (c) {
216 | return c.name();
217 | }).join(", ") + " }";
218 |
219 | Object.defineProperty(_enum, "toString", {
220 | value: function () {
221 | return string;
222 | }
223 | });
224 |
225 | /** Freeze our private objects **/
226 | Object.freeze(_values);
227 | Object.freeze(_dict);
228 |
229 | /** Freeze the prototype on the enum and the enum itself **/
230 | Object.freeze(_enum.prototype);
231 | Object.freeze(_enum);
232 |
233 | /** Return the enume **/
234 | return _enum;
235 | }
236 |
237 | return {
238 | define: define
239 | }
240 | }));
241 |
--------------------------------------------------------------------------------
/src/lib/qunit/qunit-1.19.0.css:
--------------------------------------------------------------------------------
1 | /*!
2 | * QUnit 1.19.0
3 | * http://qunitjs.com/
4 | *
5 | * Copyright jQuery Foundation and other contributors
6 | * Released under the MIT license
7 | * http://jquery.org/license
8 | *
9 | * Date: 2015-09-01T15:00Z
10 | */
11 |
12 | /** Font Family and Sizes */
13 |
14 | #qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
15 | font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
16 | }
17 |
18 | #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
19 | #qunit-tests { font-size: smaller; }
20 |
21 |
22 | /** Resets */
23 |
24 | #qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter {
25 | margin: 0;
26 | padding: 0;
27 | }
28 |
29 |
30 | /** Header */
31 |
32 | #qunit-header {
33 | padding: 0.5em 0 0.5em 1em;
34 |
35 | color: #8699A4;
36 | background-color: #0D3349;
37 |
38 | font-size: 1.5em;
39 | line-height: 1em;
40 | font-weight: 400;
41 |
42 | border-radius: 5px 5px 0 0;
43 | }
44 |
45 | #qunit-header a {
46 | text-decoration: none;
47 | color: #C2CCD1;
48 | }
49 |
50 | #qunit-header a:hover,
51 | #qunit-header a:focus {
52 | color: #FFF;
53 | }
54 |
55 | #qunit-testrunner-toolbar label {
56 | display: inline-block;
57 | padding: 0 0.5em 0 0.1em;
58 | }
59 |
60 | #qunit-banner {
61 | height: 5px;
62 | }
63 |
64 | #qunit-testrunner-toolbar {
65 | padding: 0.5em 1em 0.5em 1em;
66 | color: #5E740B;
67 | background-color: #EEE;
68 | overflow: hidden;
69 | }
70 |
71 | #qunit-userAgent {
72 | padding: 0.5em 1em 0.5em 1em;
73 | background-color: #2B81AF;
74 | color: #FFF;
75 | text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
76 | }
77 |
78 | #qunit-modulefilter-container {
79 | float: right;
80 | padding: 0.2em;
81 | }
82 |
83 | .qunit-url-config {
84 | display: inline-block;
85 | padding: 0.1em;
86 | }
87 |
88 | .qunit-filter {
89 | display: block;
90 | float: right;
91 | margin-left: 1em;
92 | }
93 |
94 | /** Tests: Pass/Fail */
95 |
96 | #qunit-tests {
97 | list-style-position: inside;
98 | }
99 |
100 | #qunit-tests li {
101 | padding: 0.4em 1em 0.4em 1em;
102 | border-bottom: 1px solid #FFF;
103 | list-style-position: inside;
104 | }
105 |
106 | #qunit-tests > li {
107 | display: none;
108 | }
109 |
110 | #qunit-tests li.running,
111 | #qunit-tests li.pass,
112 | #qunit-tests li.fail,
113 | #qunit-tests li.skipped {
114 | display: list-item;
115 | }
116 |
117 | #qunit-tests.hidepass li.running,
118 | #qunit-tests.hidepass li.pass {
119 | visibility: hidden;
120 | position: absolute;
121 | width: 0;
122 | height: 0;
123 | padding: 0;
124 | border: 0;
125 | margin: 0;
126 | }
127 |
128 | #qunit-tests li strong {
129 | cursor: pointer;
130 | }
131 |
132 | #qunit-tests li.skipped strong {
133 | cursor: default;
134 | }
135 |
136 | #qunit-tests li a {
137 | padding: 0.5em;
138 | color: #C2CCD1;
139 | text-decoration: none;
140 | }
141 |
142 | #qunit-tests li p a {
143 | padding: 0.25em;
144 | color: #6B6464;
145 | }
146 | #qunit-tests li a:hover,
147 | #qunit-tests li a:focus {
148 | color: #000;
149 | }
150 |
151 | #qunit-tests li .runtime {
152 | float: right;
153 | font-size: smaller;
154 | }
155 |
156 | .qunit-assert-list {
157 | margin-top: 0.5em;
158 | padding: 0.5em;
159 |
160 | background-color: #FFF;
161 |
162 | border-radius: 5px;
163 | }
164 |
165 | .qunit-source {
166 | margin: 0.6em 0 0.3em;
167 | }
168 |
169 | .qunit-collapsed {
170 | display: none;
171 | }
172 |
173 | #qunit-tests table {
174 | border-collapse: collapse;
175 | margin-top: 0.2em;
176 | }
177 |
178 | #qunit-tests th {
179 | text-align: right;
180 | vertical-align: top;
181 | padding: 0 0.5em 0 0;
182 | }
183 |
184 | #qunit-tests td {
185 | vertical-align: top;
186 | }
187 |
188 | #qunit-tests pre {
189 | margin: 0;
190 | white-space: pre-wrap;
191 | word-wrap: break-word;
192 | }
193 |
194 | #qunit-tests del {
195 | background-color: #E0F2BE;
196 | color: #374E0C;
197 | text-decoration: none;
198 | }
199 |
200 | #qunit-tests ins {
201 | background-color: #FFCACA;
202 | color: #500;
203 | text-decoration: none;
204 | }
205 |
206 | /*** Test Counts */
207 |
208 | #qunit-tests b.counts { color: #000; }
209 | #qunit-tests b.passed { color: #5E740B; }
210 | #qunit-tests b.failed { color: #710909; }
211 |
212 | #qunit-tests li li {
213 | padding: 5px;
214 | background-color: #FFF;
215 | border-bottom: none;
216 | list-style-position: inside;
217 | }
218 |
219 | /*** Passing Styles */
220 |
221 | #qunit-tests li li.pass {
222 | color: #3C510C;
223 | background-color: #FFF;
224 | border-left: 10px solid #C6E746;
225 | }
226 |
227 | #qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
228 | #qunit-tests .pass .test-name { color: #366097; }
229 |
230 | #qunit-tests .pass .test-actual,
231 | #qunit-tests .pass .test-expected { color: #999; }
232 |
233 | #qunit-banner.qunit-pass { background-color: #C6E746; }
234 |
235 | /*** Failing Styles */
236 |
237 | #qunit-tests li li.fail {
238 | color: #710909;
239 | background-color: #FFF;
240 | border-left: 10px solid #EE5757;
241 | white-space: pre;
242 | }
243 |
244 | #qunit-tests > li:last-child {
245 | border-radius: 0 0 5px 5px;
246 | }
247 |
248 | #qunit-tests .fail { color: #000; background-color: #EE5757; }
249 | #qunit-tests .fail .test-name,
250 | #qunit-tests .fail .module-name { color: #000; }
251 |
252 | #qunit-tests .fail .test-actual { color: #EE5757; }
253 | #qunit-tests .fail .test-expected { color: #008000; }
254 |
255 | #qunit-banner.qunit-fail { background-color: #EE5757; }
256 |
257 | /*** Skipped tests */
258 |
259 | #qunit-tests .skipped {
260 | background-color: #EBECE9;
261 | }
262 |
263 | #qunit-tests .qunit-skipped-label {
264 | background-color: #F4FF77;
265 | display: inline-block;
266 | font-style: normal;
267 | color: #366097;
268 | line-height: 1.8em;
269 | padding: 0 0.5em;
270 | margin: -0.4em 0.4em -0.4em 0;
271 | }
272 |
273 | /** Result */
274 |
275 | #qunit-testresult {
276 | padding: 0.5em 1em 0.5em 1em;
277 |
278 | color: #2B81AF;
279 | background-color: #D2E0E6;
280 |
281 | border-bottom: 1px solid #FFF;
282 | }
283 | #qunit-testresult .module-name {
284 | font-weight: 700;
285 | }
286 |
287 | /** Fixture */
288 |
289 | #qunit-fixture {
290 | position: absolute;
291 | top: -10000px;
292 | left: -10000px;
293 | width: 1000px;
294 | height: 1000px;
295 | }
296 |
--------------------------------------------------------------------------------
/src/lib/qunit/qunit-1.19.0.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * QUnit 1.19.0
3 | * http://qunitjs.com/
4 | *
5 | * Copyright jQuery Foundation and other contributors
6 | * Released under the MIT license
7 | * http://jquery.org/license
8 | *
9 | * Date: 2015-09-01T15:00Z
10 | */
11 |
12 | (function( global ) {
13 |
14 | var QUnit = {};
15 |
16 | var Date = global.Date;
17 | var now = Date.now || function() {
18 | return new Date().getTime();
19 | };
20 |
21 | var setTimeout = global.setTimeout;
22 | var clearTimeout = global.clearTimeout;
23 |
24 | // Store a local window from the global to allow direct references.
25 | var window = global.window;
26 |
27 | var defined = {
28 | document: window && window.document !== undefined,
29 | setTimeout: setTimeout !== undefined,
30 | sessionStorage: (function() {
31 | var x = "qunit-test-string";
32 | try {
33 | sessionStorage.setItem( x, x );
34 | sessionStorage.removeItem( x );
35 | return true;
36 | } catch ( e ) {
37 | return false;
38 | }
39 | }() )
40 | };
41 |
42 | var fileName = ( sourceFromStacktrace( 0 ) || "" ).replace( /(:\d+)+\)?/, "" ).replace( /.+\//, "" );
43 | var globalStartCalled = false;
44 | var runStarted = false;
45 |
46 | var toString = Object.prototype.toString,
47 | hasOwn = Object.prototype.hasOwnProperty;
48 |
49 | // returns a new Array with the elements that are in a but not in b
50 | function diff( a, b ) {
51 | var i, j,
52 | result = a.slice();
53 |
54 | for ( i = 0; i < result.length; i++ ) {
55 | for ( j = 0; j < b.length; j++ ) {
56 | if ( result[ i ] === b[ j ] ) {
57 | result.splice( i, 1 );
58 | i--;
59 | break;
60 | }
61 | }
62 | }
63 | return result;
64 | }
65 |
66 | // from jquery.js
67 | function inArray( elem, array ) {
68 | if ( array.indexOf ) {
69 | return array.indexOf( elem );
70 | }
71 |
72 | for ( var i = 0, length = array.length; i < length; i++ ) {
73 | if ( array[ i ] === elem ) {
74 | return i;
75 | }
76 | }
77 |
78 | return -1;
79 | }
80 |
81 | /**
82 | * Makes a clone of an object using only Array or Object as base,
83 | * and copies over the own enumerable properties.
84 | *
85 | * @param {Object} obj
86 | * @return {Object} New object with only the own properties (recursively).
87 | */
88 | function objectValues ( obj ) {
89 | var key, val,
90 | vals = QUnit.is( "array", obj ) ? [] : {};
91 | for ( key in obj ) {
92 | if ( hasOwn.call( obj, key ) ) {
93 | val = obj[ key ];
94 | vals[ key ] = val === Object( val ) ? objectValues( val ) : val;
95 | }
96 | }
97 | return vals;
98 | }
99 |
100 | function extend( a, b, undefOnly ) {
101 | for ( var prop in b ) {
102 | if ( hasOwn.call( b, prop ) ) {
103 |
104 | // Avoid "Member not found" error in IE8 caused by messing with window.constructor
105 | // This block runs on every environment, so `global` is being used instead of `window`
106 | // to avoid errors on node.
107 | if ( prop !== "constructor" || a !== global ) {
108 | if ( b[ prop ] === undefined ) {
109 | delete a[ prop ];
110 | } else if ( !( undefOnly && typeof a[ prop ] !== "undefined" ) ) {
111 | a[ prop ] = b[ prop ];
112 | }
113 | }
114 | }
115 | }
116 |
117 | return a;
118 | }
119 |
120 | function objectType( obj ) {
121 | if ( typeof obj === "undefined" ) {
122 | return "undefined";
123 | }
124 |
125 | // Consider: typeof null === object
126 | if ( obj === null ) {
127 | return "null";
128 | }
129 |
130 | var match = toString.call( obj ).match( /^\[object\s(.*)\]$/ ),
131 | type = match && match[ 1 ] || "";
132 |
133 | switch ( type ) {
134 | case "Number":
135 | if ( isNaN( obj ) ) {
136 | return "nan";
137 | }
138 | return "number";
139 | case "String":
140 | case "Boolean":
141 | case "Array":
142 | case "Set":
143 | case "Map":
144 | case "Date":
145 | case "RegExp":
146 | case "Function":
147 | return type.toLowerCase();
148 | }
149 | if ( typeof obj === "object" ) {
150 | return "object";
151 | }
152 | return undefined;
153 | }
154 |
155 | // Safe object type checking
156 | function is( type, obj ) {
157 | return QUnit.objectType( obj ) === type;
158 | }
159 |
160 | var getUrlParams = function() {
161 | var i, current;
162 | var urlParams = {};
163 | var location = window.location;
164 | var params = location.search.slice( 1 ).split( "&" );
165 | var length = params.length;
166 |
167 | if ( params[ 0 ] ) {
168 | for ( i = 0; i < length; i++ ) {
169 | current = params[ i ].split( "=" );
170 | current[ 0 ] = decodeURIComponent( current[ 0 ] );
171 |
172 | // allow just a key to turn on a flag, e.g., test.html?noglobals
173 | current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
174 | if ( urlParams[ current[ 0 ] ] ) {
175 | urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] );
176 | } else {
177 | urlParams[ current[ 0 ] ] = current[ 1 ];
178 | }
179 | }
180 | }
181 |
182 | return urlParams;
183 | };
184 |
185 | // Doesn't support IE6 to IE9, it will return undefined on these browsers
186 | // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
187 | function extractStacktrace( e, offset ) {
188 | offset = offset === undefined ? 4 : offset;
189 |
190 | var stack, include, i;
191 |
192 | if ( e.stack ) {
193 | stack = e.stack.split( "\n" );
194 | if ( /^error$/i.test( stack[ 0 ] ) ) {
195 | stack.shift();
196 | }
197 | if ( fileName ) {
198 | include = [];
199 | for ( i = offset; i < stack.length; i++ ) {
200 | if ( stack[ i ].indexOf( fileName ) !== -1 ) {
201 | break;
202 | }
203 | include.push( stack[ i ] );
204 | }
205 | if ( include.length ) {
206 | return include.join( "\n" );
207 | }
208 | }
209 | return stack[ offset ];
210 |
211 | // Support: Safari <=6 only
212 | } else if ( e.sourceURL ) {
213 |
214 | // exclude useless self-reference for generated Error objects
215 | if ( /qunit.js$/.test( e.sourceURL ) ) {
216 | return;
217 | }
218 |
219 | // for actual exceptions, this is useful
220 | return e.sourceURL + ":" + e.line;
221 | }
222 | }
223 |
224 | function sourceFromStacktrace( offset ) {
225 | var error = new Error();
226 |
227 | // Support: Safari <=7 only, IE <=10 - 11 only
228 | // Not all browsers generate the `stack` property for `new Error()`, see also #636
229 | if ( !error.stack ) {
230 | try {
231 | throw error;
232 | } catch ( err ) {
233 | error = err;
234 | }
235 | }
236 |
237 | return extractStacktrace( error, offset );
238 | }
239 |
240 | /**
241 | * Config object: Maintain internal state
242 | * Later exposed as QUnit.config
243 | * `config` initialized at top of scope
244 | */
245 | var config = {
246 | // The queue of tests to run
247 | queue: [],
248 |
249 | // block until document ready
250 | blocking: true,
251 |
252 | // by default, run previously failed tests first
253 | // very useful in combination with "Hide passed tests" checked
254 | reorder: true,
255 |
256 | // by default, modify document.title when suite is done
257 | altertitle: true,
258 |
259 | // by default, scroll to top of the page when suite is done
260 | scrolltop: true,
261 |
262 | // depth up-to which object will be dumped
263 | maxDepth: 5,
264 |
265 | // when enabled, all tests must call expect()
266 | requireExpects: false,
267 |
268 | // add checkboxes that are persisted in the query-string
269 | // when enabled, the id is set to `true` as a `QUnit.config` property
270 | urlConfig: [
271 | {
272 | id: "hidepassed",
273 | label: "Hide passed tests",
274 | tooltip: "Only show tests and assertions that fail. Stored as query-strings."
275 | },
276 | {
277 | id: "noglobals",
278 | label: "Check for Globals",
279 | tooltip: "Enabling this will test if any test introduces new properties on the " +
280 | "global object (`window` in Browsers). Stored as query-strings."
281 | },
282 | {
283 | id: "notrycatch",
284 | label: "No try-catch",
285 | tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " +
286 | "exceptions in IE reasonable. Stored as query-strings."
287 | }
288 | ],
289 |
290 | // Set of all modules.
291 | modules: [],
292 |
293 | // The first unnamed module
294 | currentModule: {
295 | name: "",
296 | tests: []
297 | },
298 |
299 | callbacks: {}
300 | };
301 |
302 | var urlParams = defined.document ? getUrlParams() : {};
303 |
304 | // Push a loose unnamed module to the modules collection
305 | config.modules.push( config.currentModule );
306 |
307 | if ( urlParams.filter === true ) {
308 | delete urlParams.filter;
309 | }
310 |
311 | // String search anywhere in moduleName+testName
312 | config.filter = urlParams.filter;
313 |
314 | config.testId = [];
315 | if ( urlParams.testId ) {
316 | // Ensure that urlParams.testId is an array
317 | urlParams.testId = decodeURIComponent( urlParams.testId ).split( "," );
318 | for (var i = 0; i < urlParams.testId.length; i++ ) {
319 | config.testId.push( urlParams.testId[ i ] );
320 | }
321 | }
322 |
323 | var loggingCallbacks = {};
324 |
325 | // Register logging callbacks
326 | function registerLoggingCallbacks( obj ) {
327 | var i, l, key,
328 | callbackNames = [ "begin", "done", "log", "testStart", "testDone",
329 | "moduleStart", "moduleDone" ];
330 |
331 | function registerLoggingCallback( key ) {
332 | var loggingCallback = function( callback ) {
333 | if ( objectType( callback ) !== "function" ) {
334 | throw new Error(
335 | "QUnit logging methods require a callback function as their first parameters."
336 | );
337 | }
338 |
339 | config.callbacks[ key ].push( callback );
340 | };
341 |
342 | // DEPRECATED: This will be removed on QUnit 2.0.0+
343 | // Stores the registered functions allowing restoring
344 | // at verifyLoggingCallbacks() if modified
345 | loggingCallbacks[ key ] = loggingCallback;
346 |
347 | return loggingCallback;
348 | }
349 |
350 | for ( i = 0, l = callbackNames.length; i < l; i++ ) {
351 | key = callbackNames[ i ];
352 |
353 | // Initialize key collection of logging callback
354 | if ( objectType( config.callbacks[ key ] ) === "undefined" ) {
355 | config.callbacks[ key ] = [];
356 | }
357 |
358 | obj[ key ] = registerLoggingCallback( key );
359 | }
360 | }
361 |
362 | function runLoggingCallbacks( key, args ) {
363 | var i, l, callbacks;
364 |
365 | callbacks = config.callbacks[ key ];
366 | for ( i = 0, l = callbacks.length; i < l; i++ ) {
367 | callbacks[ i ]( args );
368 | }
369 | }
370 |
371 | // DEPRECATED: This will be removed on 2.0.0+
372 | // This function verifies if the loggingCallbacks were modified by the user
373 | // If so, it will restore it, assign the given callback and print a console warning
374 | function verifyLoggingCallbacks() {
375 | var loggingCallback, userCallback;
376 |
377 | for ( loggingCallback in loggingCallbacks ) {
378 | if ( QUnit[ loggingCallback ] !== loggingCallbacks[ loggingCallback ] ) {
379 |
380 | userCallback = QUnit[ loggingCallback ];
381 |
382 | // Restore the callback function
383 | QUnit[ loggingCallback ] = loggingCallbacks[ loggingCallback ];
384 |
385 | // Assign the deprecated given callback
386 | QUnit[ loggingCallback ]( userCallback );
387 |
388 | if ( global.console && global.console.warn ) {
389 | global.console.warn(
390 | "QUnit." + loggingCallback + " was replaced with a new value.\n" +
391 | "Please, check out the documentation on how to apply logging callbacks.\n" +
392 | "Reference: http://api.qunitjs.com/category/callbacks/"
393 | );
394 | }
395 | }
396 | }
397 | }
398 |
399 | ( function() {
400 | if ( !defined.document ) {
401 | return;
402 | }
403 |
404 | // `onErrorFnPrev` initialized at top of scope
405 | // Preserve other handlers
406 | var onErrorFnPrev = window.onerror;
407 |
408 | // Cover uncaught exceptions
409 | // Returning true will suppress the default browser handler,
410 | // returning false will let it run.
411 | window.onerror = function( error, filePath, linerNr ) {
412 | var ret = false;
413 | if ( onErrorFnPrev ) {
414 | ret = onErrorFnPrev( error, filePath, linerNr );
415 | }
416 |
417 | // Treat return value as window.onerror itself does,
418 | // Only do our handling if not suppressed.
419 | if ( ret !== true ) {
420 | if ( QUnit.config.current ) {
421 | if ( QUnit.config.current.ignoreGlobalErrors ) {
422 | return true;
423 | }
424 | QUnit.pushFailure( error, filePath + ":" + linerNr );
425 | } else {
426 | QUnit.test( "global failure", extend(function() {
427 | QUnit.pushFailure( error, filePath + ":" + linerNr );
428 | }, { validTest: true } ) );
429 | }
430 | return false;
431 | }
432 |
433 | return ret;
434 | };
435 | } )();
436 |
437 | QUnit.urlParams = urlParams;
438 |
439 | // Figure out if we're running the tests from a server or not
440 | QUnit.isLocal = !( defined.document && window.location.protocol !== "file:" );
441 |
442 | // Expose the current QUnit version
443 | QUnit.version = "1.19.0";
444 |
445 | extend( QUnit, {
446 |
447 | // call on start of module test to prepend name to all tests
448 | module: function( name, testEnvironment ) {
449 | var currentModule = {
450 | name: name,
451 | testEnvironment: testEnvironment,
452 | tests: []
453 | };
454 |
455 | // DEPRECATED: handles setup/teardown functions,
456 | // beforeEach and afterEach should be used instead
457 | if ( testEnvironment && testEnvironment.setup ) {
458 | testEnvironment.beforeEach = testEnvironment.setup;
459 | delete testEnvironment.setup;
460 | }
461 | if ( testEnvironment && testEnvironment.teardown ) {
462 | testEnvironment.afterEach = testEnvironment.teardown;
463 | delete testEnvironment.teardown;
464 | }
465 |
466 | config.modules.push( currentModule );
467 | config.currentModule = currentModule;
468 | },
469 |
470 | // DEPRECATED: QUnit.asyncTest() will be removed in QUnit 2.0.
471 | asyncTest: asyncTest,
472 |
473 | test: test,
474 |
475 | skip: skip,
476 |
477 | // DEPRECATED: The functionality of QUnit.start() will be altered in QUnit 2.0.
478 | // In QUnit 2.0, invoking it will ONLY affect the `QUnit.config.autostart` blocking behavior.
479 | start: function( count ) {
480 | var globalStartAlreadyCalled = globalStartCalled;
481 |
482 | if ( !config.current ) {
483 | globalStartCalled = true;
484 |
485 | if ( runStarted ) {
486 | throw new Error( "Called start() outside of a test context while already started" );
487 | } else if ( globalStartAlreadyCalled || count > 1 ) {
488 | throw new Error( "Called start() outside of a test context too many times" );
489 | } else if ( config.autostart ) {
490 | throw new Error( "Called start() outside of a test context when " +
491 | "QUnit.config.autostart was true" );
492 | } else if ( !config.pageLoaded ) {
493 |
494 | // The page isn't completely loaded yet, so bail out and let `QUnit.load` handle it
495 | config.autostart = true;
496 | return;
497 | }
498 | } else {
499 |
500 | // If a test is running, adjust its semaphore
501 | config.current.semaphore -= count || 1;
502 |
503 | // Don't start until equal number of stop-calls
504 | if ( config.current.semaphore > 0 ) {
505 | return;
506 | }
507 |
508 | // throw an Error if start is called more often than stop
509 | if ( config.current.semaphore < 0 ) {
510 | config.current.semaphore = 0;
511 |
512 | QUnit.pushFailure(
513 | "Called start() while already started (test's semaphore was 0 already)",
514 | sourceFromStacktrace( 2 )
515 | );
516 | return;
517 | }
518 | }
519 |
520 | resumeProcessing();
521 | },
522 |
523 | // DEPRECATED: QUnit.stop() will be removed in QUnit 2.0.
524 | stop: function( count ) {
525 |
526 | // If there isn't a test running, don't allow QUnit.stop() to be called
527 | if ( !config.current ) {
528 | throw new Error( "Called stop() outside of a test context" );
529 | }
530 |
531 | // If a test is running, adjust its semaphore
532 | config.current.semaphore += count || 1;
533 |
534 | pauseProcessing();
535 | },
536 |
537 | config: config,
538 |
539 | is: is,
540 |
541 | objectType: objectType,
542 |
543 | extend: extend,
544 |
545 | load: function() {
546 | config.pageLoaded = true;
547 |
548 | // Initialize the configuration options
549 | extend( config, {
550 | stats: { all: 0, bad: 0 },
551 | moduleStats: { all: 0, bad: 0 },
552 | started: 0,
553 | updateRate: 1000,
554 | autostart: true,
555 | filter: ""
556 | }, true );
557 |
558 | config.blocking = false;
559 |
560 | if ( config.autostart ) {
561 | resumeProcessing();
562 | }
563 | },
564 |
565 | stack: function( offset ) {
566 | offset = ( offset || 0 ) + 2;
567 | return sourceFromStacktrace( offset );
568 | }
569 | });
570 |
571 | registerLoggingCallbacks( QUnit );
572 |
573 | function begin() {
574 | var i, l,
575 | modulesLog = [];
576 |
577 | // If the test run hasn't officially begun yet
578 | if ( !config.started ) {
579 |
580 | // Record the time of the test run's beginning
581 | config.started = now();
582 |
583 | verifyLoggingCallbacks();
584 |
585 | // Delete the loose unnamed module if unused.
586 | if ( config.modules[ 0 ].name === "" && config.modules[ 0 ].tests.length === 0 ) {
587 | config.modules.shift();
588 | }
589 |
590 | // Avoid unnecessary information by not logging modules' test environments
591 | for ( i = 0, l = config.modules.length; i < l; i++ ) {
592 | modulesLog.push({
593 | name: config.modules[ i ].name,
594 | tests: config.modules[ i ].tests
595 | });
596 | }
597 |
598 | // The test run is officially beginning now
599 | runLoggingCallbacks( "begin", {
600 | totalTests: Test.count,
601 | modules: modulesLog
602 | });
603 | }
604 |
605 | config.blocking = false;
606 | process( true );
607 | }
608 |
609 | function process( last ) {
610 | function next() {
611 | process( last );
612 | }
613 | var start = now();
614 | config.depth = ( config.depth || 0 ) + 1;
615 |
616 | while ( config.queue.length && !config.blocking ) {
617 | if ( !defined.setTimeout || config.updateRate <= 0 ||
618 | ( ( now() - start ) < config.updateRate ) ) {
619 | if ( config.current ) {
620 |
621 | // Reset async tracking for each phase of the Test lifecycle
622 | config.current.usedAsync = false;
623 | }
624 | config.queue.shift()();
625 | } else {
626 | setTimeout( next, 13 );
627 | break;
628 | }
629 | }
630 | config.depth--;
631 | if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
632 | done();
633 | }
634 | }
635 |
636 | function pauseProcessing() {
637 | config.blocking = true;
638 |
639 | if ( config.testTimeout && defined.setTimeout ) {
640 | clearTimeout( config.timeout );
641 | config.timeout = setTimeout(function() {
642 | if ( config.current ) {
643 | config.current.semaphore = 0;
644 | QUnit.pushFailure( "Test timed out", sourceFromStacktrace( 2 ) );
645 | } else {
646 | throw new Error( "Test timed out" );
647 | }
648 | resumeProcessing();
649 | }, config.testTimeout );
650 | }
651 | }
652 |
653 | function resumeProcessing() {
654 | runStarted = true;
655 |
656 | // A slight delay to allow this iteration of the event loop to finish (more assertions, etc.)
657 | if ( defined.setTimeout ) {
658 | setTimeout(function() {
659 | if ( config.current && config.current.semaphore > 0 ) {
660 | return;
661 | }
662 | if ( config.timeout ) {
663 | clearTimeout( config.timeout );
664 | }
665 |
666 | begin();
667 | }, 13 );
668 | } else {
669 | begin();
670 | }
671 | }
672 |
673 | function done() {
674 | var runtime, passed;
675 |
676 | config.autorun = true;
677 |
678 | // Log the last module results
679 | if ( config.previousModule ) {
680 | runLoggingCallbacks( "moduleDone", {
681 | name: config.previousModule.name,
682 | tests: config.previousModule.tests,
683 | failed: config.moduleStats.bad,
684 | passed: config.moduleStats.all - config.moduleStats.bad,
685 | total: config.moduleStats.all,
686 | runtime: now() - config.moduleStats.started
687 | });
688 | }
689 | delete config.previousModule;
690 |
691 | runtime = now() - config.started;
692 | passed = config.stats.all - config.stats.bad;
693 |
694 | runLoggingCallbacks( "done", {
695 | failed: config.stats.bad,
696 | passed: passed,
697 | total: config.stats.all,
698 | runtime: runtime
699 | });
700 | }
701 |
702 | function Test( settings ) {
703 | var i, l;
704 |
705 | ++Test.count;
706 |
707 | extend( this, settings );
708 | this.assertions = [];
709 | this.semaphore = 0;
710 | this.usedAsync = false;
711 | this.module = config.currentModule;
712 | this.stack = sourceFromStacktrace( 3 );
713 |
714 | // Register unique strings
715 | for ( i = 0, l = this.module.tests; i < l.length; i++ ) {
716 | if ( this.module.tests[ i ].name === this.testName ) {
717 | this.testName += " ";
718 | }
719 | }
720 |
721 | this.testId = generateHash( this.module.name, this.testName );
722 |
723 | this.module.tests.push({
724 | name: this.testName,
725 | testId: this.testId
726 | });
727 |
728 | if ( settings.skip ) {
729 |
730 | // Skipped tests will fully ignore any sent callback
731 | this.callback = function() {};
732 | this.async = false;
733 | this.expected = 0;
734 | } else {
735 | this.assert = new Assert( this );
736 | }
737 | }
738 |
739 | Test.count = 0;
740 |
741 | Test.prototype = {
742 | before: function() {
743 | if (
744 |
745 | // Emit moduleStart when we're switching from one module to another
746 | this.module !== config.previousModule ||
747 |
748 | // They could be equal (both undefined) but if the previousModule property doesn't
749 | // yet exist it means this is the first test in a suite that isn't wrapped in a
750 | // module, in which case we'll just emit a moduleStart event for 'undefined'.
751 | // Without this, reporters can get testStart before moduleStart which is a problem.
752 | !hasOwn.call( config, "previousModule" )
753 | ) {
754 | if ( hasOwn.call( config, "previousModule" ) ) {
755 | runLoggingCallbacks( "moduleDone", {
756 | name: config.previousModule.name,
757 | tests: config.previousModule.tests,
758 | failed: config.moduleStats.bad,
759 | passed: config.moduleStats.all - config.moduleStats.bad,
760 | total: config.moduleStats.all,
761 | runtime: now() - config.moduleStats.started
762 | });
763 | }
764 | config.previousModule = this.module;
765 | config.moduleStats = { all: 0, bad: 0, started: now() };
766 | runLoggingCallbacks( "moduleStart", {
767 | name: this.module.name,
768 | tests: this.module.tests
769 | });
770 | }
771 |
772 | config.current = this;
773 |
774 | if ( this.module.testEnvironment ) {
775 | delete this.module.testEnvironment.beforeEach;
776 | delete this.module.testEnvironment.afterEach;
777 | }
778 | this.testEnvironment = extend( {}, this.module.testEnvironment );
779 |
780 | this.started = now();
781 | runLoggingCallbacks( "testStart", {
782 | name: this.testName,
783 | module: this.module.name,
784 | testId: this.testId
785 | });
786 |
787 | if ( !config.pollution ) {
788 | saveGlobal();
789 | }
790 | },
791 |
792 | run: function() {
793 | var promise;
794 |
795 | config.current = this;
796 |
797 | if ( this.async ) {
798 | QUnit.stop();
799 | }
800 |
801 | this.callbackStarted = now();
802 |
803 | if ( config.notrycatch ) {
804 | promise = this.callback.call( this.testEnvironment, this.assert );
805 | this.resolvePromise( promise );
806 | return;
807 | }
808 |
809 | try {
810 | promise = this.callback.call( this.testEnvironment, this.assert );
811 | this.resolvePromise( promise );
812 | } catch ( e ) {
813 | this.pushFailure( "Died on test #" + ( this.assertions.length + 1 ) + " " +
814 | this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) );
815 |
816 | // else next test will carry the responsibility
817 | saveGlobal();
818 |
819 | // Restart the tests if they're blocking
820 | if ( config.blocking ) {
821 | QUnit.start();
822 | }
823 | }
824 | },
825 |
826 | after: function() {
827 | checkPollution();
828 | },
829 |
830 | queueHook: function( hook, hookName ) {
831 | var promise,
832 | test = this;
833 | return function runHook() {
834 | config.current = test;
835 | if ( config.notrycatch ) {
836 | promise = hook.call( test.testEnvironment, test.assert );
837 | test.resolvePromise( promise, hookName );
838 | return;
839 | }
840 | try {
841 | promise = hook.call( test.testEnvironment, test.assert );
842 | test.resolvePromise( promise, hookName );
843 | } catch ( error ) {
844 | test.pushFailure( hookName + " failed on " + test.testName + ": " +
845 | ( error.message || error ), extractStacktrace( error, 0 ) );
846 | }
847 | };
848 | },
849 |
850 | // Currently only used for module level hooks, can be used to add global level ones
851 | hooks: function( handler ) {
852 | var hooks = [];
853 |
854 | // Hooks are ignored on skipped tests
855 | if ( this.skip ) {
856 | return hooks;
857 | }
858 |
859 | if ( this.module.testEnvironment &&
860 | QUnit.objectType( this.module.testEnvironment[ handler ] ) === "function" ) {
861 | hooks.push( this.queueHook( this.module.testEnvironment[ handler ], handler ) );
862 | }
863 |
864 | return hooks;
865 | },
866 |
867 | finish: function() {
868 | config.current = this;
869 | if ( config.requireExpects && this.expected === null ) {
870 | this.pushFailure( "Expected number of assertions to be defined, but expect() was " +
871 | "not called.", this.stack );
872 | } else if ( this.expected !== null && this.expected !== this.assertions.length ) {
873 | this.pushFailure( "Expected " + this.expected + " assertions, but " +
874 | this.assertions.length + " were run", this.stack );
875 | } else if ( this.expected === null && !this.assertions.length ) {
876 | this.pushFailure( "Expected at least one assertion, but none were run - call " +
877 | "expect(0) to accept zero assertions.", this.stack );
878 | }
879 |
880 | var i,
881 | bad = 0;
882 |
883 | this.runtime = now() - this.started;
884 | config.stats.all += this.assertions.length;
885 | config.moduleStats.all += this.assertions.length;
886 |
887 | for ( i = 0; i < this.assertions.length; i++ ) {
888 | if ( !this.assertions[ i ].result ) {
889 | bad++;
890 | config.stats.bad++;
891 | config.moduleStats.bad++;
892 | }
893 | }
894 |
895 | runLoggingCallbacks( "testDone", {
896 | name: this.testName,
897 | module: this.module.name,
898 | skipped: !!this.skip,
899 | failed: bad,
900 | passed: this.assertions.length - bad,
901 | total: this.assertions.length,
902 | runtime: this.runtime,
903 |
904 | // HTML Reporter use
905 | assertions: this.assertions,
906 | testId: this.testId,
907 |
908 | // Source of Test
909 | source: this.stack,
910 |
911 | // DEPRECATED: this property will be removed in 2.0.0, use runtime instead
912 | duration: this.runtime
913 | });
914 |
915 | // QUnit.reset() is deprecated and will be replaced for a new
916 | // fixture reset function on QUnit 2.0/2.1.
917 | // It's still called here for backwards compatibility handling
918 | QUnit.reset();
919 |
920 | config.current = undefined;
921 | },
922 |
923 | queue: function() {
924 | var bad,
925 | test = this;
926 |
927 | if ( !this.valid() ) {
928 | return;
929 | }
930 |
931 | function run() {
932 |
933 | // each of these can by async
934 | synchronize([
935 | function() {
936 | test.before();
937 | },
938 |
939 | test.hooks( "beforeEach" ),
940 |
941 | function() {
942 | test.run();
943 | },
944 |
945 | test.hooks( "afterEach" ).reverse(),
946 |
947 | function() {
948 | test.after();
949 | },
950 | function() {
951 | test.finish();
952 | }
953 | ]);
954 | }
955 |
956 | // `bad` initialized at top of scope
957 | // defer when previous test run passed, if storage is available
958 | bad = QUnit.config.reorder && defined.sessionStorage &&
959 | +sessionStorage.getItem( "qunit-test-" + this.module.name + "-" + this.testName );
960 |
961 | if ( bad ) {
962 | run();
963 | } else {
964 | synchronize( run, true );
965 | }
966 | },
967 |
968 | push: function( result, actual, expected, message, negative ) {
969 | var source,
970 | details = {
971 | module: this.module.name,
972 | name: this.testName,
973 | result: result,
974 | message: message,
975 | actual: actual,
976 | expected: expected,
977 | testId: this.testId,
978 | negative: negative || false,
979 | runtime: now() - this.started
980 | };
981 |
982 | if ( !result ) {
983 | source = sourceFromStacktrace();
984 |
985 | if ( source ) {
986 | details.source = source;
987 | }
988 | }
989 |
990 | runLoggingCallbacks( "log", details );
991 |
992 | this.assertions.push({
993 | result: !!result,
994 | message: message
995 | });
996 | },
997 |
998 | pushFailure: function( message, source, actual ) {
999 | if ( !( this instanceof Test ) ) {
1000 | throw new Error( "pushFailure() assertion outside test context, was " +
1001 | sourceFromStacktrace( 2 ) );
1002 | }
1003 |
1004 | var details = {
1005 | module: this.module.name,
1006 | name: this.testName,
1007 | result: false,
1008 | message: message || "error",
1009 | actual: actual || null,
1010 | testId: this.testId,
1011 | runtime: now() - this.started
1012 | };
1013 |
1014 | if ( source ) {
1015 | details.source = source;
1016 | }
1017 |
1018 | runLoggingCallbacks( "log", details );
1019 |
1020 | this.assertions.push({
1021 | result: false,
1022 | message: message
1023 | });
1024 | },
1025 |
1026 | resolvePromise: function( promise, phase ) {
1027 | var then, message,
1028 | test = this;
1029 | if ( promise != null ) {
1030 | then = promise.then;
1031 | if ( QUnit.objectType( then ) === "function" ) {
1032 | QUnit.stop();
1033 | then.call(
1034 | promise,
1035 | function() { QUnit.start(); },
1036 | function( error ) {
1037 | message = "Promise rejected " +
1038 | ( !phase ? "during" : phase.replace( /Each$/, "" ) ) +
1039 | " " + test.testName + ": " + ( error.message || error );
1040 | test.pushFailure( message, extractStacktrace( error, 0 ) );
1041 |
1042 | // else next test will carry the responsibility
1043 | saveGlobal();
1044 |
1045 | // Unblock
1046 | QUnit.start();
1047 | }
1048 | );
1049 | }
1050 | }
1051 | },
1052 |
1053 | valid: function() {
1054 | var include,
1055 | filter = config.filter && config.filter.toLowerCase(),
1056 | module = QUnit.urlParams.module && QUnit.urlParams.module.toLowerCase(),
1057 | fullName = ( this.module.name + ": " + this.testName ).toLowerCase();
1058 |
1059 | // Internally-generated tests are always valid
1060 | if ( this.callback && this.callback.validTest ) {
1061 | return true;
1062 | }
1063 |
1064 | if ( config.testId.length > 0 && inArray( this.testId, config.testId ) < 0 ) {
1065 | return false;
1066 | }
1067 |
1068 | if ( module && ( !this.module.name || this.module.name.toLowerCase() !== module ) ) {
1069 | return false;
1070 | }
1071 |
1072 | if ( !filter ) {
1073 | return true;
1074 | }
1075 |
1076 | include = filter.charAt( 0 ) !== "!";
1077 | if ( !include ) {
1078 | filter = filter.slice( 1 );
1079 | }
1080 |
1081 | // If the filter matches, we need to honour include
1082 | if ( fullName.indexOf( filter ) !== -1 ) {
1083 | return include;
1084 | }
1085 |
1086 | // Otherwise, do the opposite
1087 | return !include;
1088 | }
1089 |
1090 | };
1091 |
1092 | // Resets the test setup. Useful for tests that modify the DOM.
1093 | /*
1094 | DEPRECATED: Use multiple tests instead of resetting inside a test.
1095 | Use testStart or testDone for custom cleanup.
1096 | This method will throw an error in 2.0, and will be removed in 2.1
1097 | */
1098 | QUnit.reset = function() {
1099 |
1100 | // Return on non-browser environments
1101 | // This is necessary to not break on node tests
1102 | if ( !defined.document ) {
1103 | return;
1104 | }
1105 |
1106 | var fixture = defined.document && document.getElementById &&
1107 | document.getElementById( "qunit-fixture" );
1108 |
1109 | if ( fixture ) {
1110 | fixture.innerHTML = config.fixture;
1111 | }
1112 | };
1113 |
1114 | QUnit.pushFailure = function() {
1115 | if ( !QUnit.config.current ) {
1116 | throw new Error( "pushFailure() assertion outside test context, in " +
1117 | sourceFromStacktrace( 2 ) );
1118 | }
1119 |
1120 | // Gets current test obj
1121 | var currentTest = QUnit.config.current;
1122 |
1123 | return currentTest.pushFailure.apply( currentTest, arguments );
1124 | };
1125 |
1126 | // Based on Java's String.hashCode, a simple but not
1127 | // rigorously collision resistant hashing function
1128 | function generateHash( module, testName ) {
1129 | var hex,
1130 | i = 0,
1131 | hash = 0,
1132 | str = module + "\x1C" + testName,
1133 | len = str.length;
1134 |
1135 | for ( ; i < len; i++ ) {
1136 | hash = ( ( hash << 5 ) - hash ) + str.charCodeAt( i );
1137 | hash |= 0;
1138 | }
1139 |
1140 | // Convert the possibly negative integer hash code into an 8 character hex string, which isn't
1141 | // strictly necessary but increases user understanding that the id is a SHA-like hash
1142 | hex = ( 0x100000000 + hash ).toString( 16 );
1143 | if ( hex.length < 8 ) {
1144 | hex = "0000000" + hex;
1145 | }
1146 |
1147 | return hex.slice( -8 );
1148 | }
1149 |
1150 | function synchronize( callback, last ) {
1151 | if ( QUnit.objectType( callback ) === "array" ) {
1152 | while ( callback.length ) {
1153 | synchronize( callback.shift() );
1154 | }
1155 | return;
1156 | }
1157 | config.queue.push( callback );
1158 |
1159 | if ( config.autorun && !config.blocking ) {
1160 | process( last );
1161 | }
1162 | }
1163 |
1164 | function saveGlobal() {
1165 | config.pollution = [];
1166 |
1167 | if ( config.noglobals ) {
1168 | for ( var key in global ) {
1169 | if ( hasOwn.call( global, key ) ) {
1170 |
1171 | // in Opera sometimes DOM element ids show up here, ignore them
1172 | if ( /^qunit-test-output/.test( key ) ) {
1173 | continue;
1174 | }
1175 | config.pollution.push( key );
1176 | }
1177 | }
1178 | }
1179 | }
1180 |
1181 | function checkPollution() {
1182 | var newGlobals,
1183 | deletedGlobals,
1184 | old = config.pollution;
1185 |
1186 | saveGlobal();
1187 |
1188 | newGlobals = diff( config.pollution, old );
1189 | if ( newGlobals.length > 0 ) {
1190 | QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join( ", " ) );
1191 | }
1192 |
1193 | deletedGlobals = diff( old, config.pollution );
1194 | if ( deletedGlobals.length > 0 ) {
1195 | QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join( ", " ) );
1196 | }
1197 | }
1198 |
1199 | // Will be exposed as QUnit.asyncTest
1200 | function asyncTest( testName, expected, callback ) {
1201 | if ( arguments.length === 2 ) {
1202 | callback = expected;
1203 | expected = null;
1204 | }
1205 |
1206 | QUnit.test( testName, expected, callback, true );
1207 | }
1208 |
1209 | // Will be exposed as QUnit.test
1210 | function test( testName, expected, callback, async ) {
1211 | var newTest;
1212 |
1213 | if ( arguments.length === 2 ) {
1214 | callback = expected;
1215 | expected = null;
1216 | }
1217 |
1218 | newTest = new Test({
1219 | testName: testName,
1220 | expected: expected,
1221 | async: async,
1222 | callback: callback
1223 | });
1224 |
1225 | newTest.queue();
1226 | }
1227 |
1228 | // Will be exposed as QUnit.skip
1229 | function skip( testName ) {
1230 | var test = new Test({
1231 | testName: testName,
1232 | skip: true
1233 | });
1234 |
1235 | test.queue();
1236 | }
1237 |
1238 | function Assert( testContext ) {
1239 | this.test = testContext;
1240 | }
1241 |
1242 | // Assert helpers
1243 | QUnit.assert = Assert.prototype = {
1244 |
1245 | // Specify the number of expected assertions to guarantee that failed test
1246 | // (no assertions are run at all) don't slip through.
1247 | expect: function( asserts ) {
1248 | if ( arguments.length === 1 ) {
1249 | this.test.expected = asserts;
1250 | } else {
1251 | return this.test.expected;
1252 | }
1253 | },
1254 |
1255 | // Increment this Test's semaphore counter, then return a single-use function that
1256 | // decrements that counter a maximum of once.
1257 | async: function() {
1258 | var test = this.test,
1259 | popped = false;
1260 |
1261 | test.semaphore += 1;
1262 | test.usedAsync = true;
1263 | pauseProcessing();
1264 |
1265 | return function done() {
1266 | if ( !popped ) {
1267 | test.semaphore -= 1;
1268 | popped = true;
1269 | resumeProcessing();
1270 | } else {
1271 | test.pushFailure( "Called the callback returned from `assert.async` more than once",
1272 | sourceFromStacktrace( 2 ) );
1273 | }
1274 | };
1275 | },
1276 |
1277 | // Exports test.push() to the user API
1278 | push: function( /* result, actual, expected, message, negative */ ) {
1279 | var assert = this,
1280 | currentTest = ( assert instanceof Assert && assert.test ) || QUnit.config.current;
1281 |
1282 | // Backwards compatibility fix.
1283 | // Allows the direct use of global exported assertions and QUnit.assert.*
1284 | // Although, it's use is not recommended as it can leak assertions
1285 | // to other tests from async tests, because we only get a reference to the current test,
1286 | // not exactly the test where assertion were intended to be called.
1287 | if ( !currentTest ) {
1288 | throw new Error( "assertion outside test context, in " + sourceFromStacktrace( 2 ) );
1289 | }
1290 |
1291 | if ( currentTest.usedAsync === true && currentTest.semaphore === 0 ) {
1292 | currentTest.pushFailure( "Assertion after the final `assert.async` was resolved",
1293 | sourceFromStacktrace( 2 ) );
1294 |
1295 | // Allow this assertion to continue running anyway...
1296 | }
1297 |
1298 | if ( !( assert instanceof Assert ) ) {
1299 | assert = currentTest.assert;
1300 | }
1301 | return assert.test.push.apply( assert.test, arguments );
1302 | },
1303 |
1304 | ok: function( result, message ) {
1305 | message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " +
1306 | QUnit.dump.parse( result ) );
1307 | this.push( !!result, result, true, message );
1308 | },
1309 |
1310 | notOk: function( result, message ) {
1311 | message = message || ( !result ? "okay" : "failed, expected argument to be falsy, was: " +
1312 | QUnit.dump.parse( result ) );
1313 | this.push( !result, result, false, message, true );
1314 | },
1315 |
1316 | equal: function( actual, expected, message ) {
1317 | /*jshint eqeqeq:false */
1318 | this.push( expected == actual, actual, expected, message );
1319 | },
1320 |
1321 | notEqual: function( actual, expected, message ) {
1322 | /*jshint eqeqeq:false */
1323 | this.push( expected != actual, actual, expected, message, true );
1324 | },
1325 |
1326 | propEqual: function( actual, expected, message ) {
1327 | actual = objectValues( actual );
1328 | expected = objectValues( expected );
1329 | this.push( QUnit.equiv( actual, expected ), actual, expected, message );
1330 | },
1331 |
1332 | notPropEqual: function( actual, expected, message ) {
1333 | actual = objectValues( actual );
1334 | expected = objectValues( expected );
1335 | this.push( !QUnit.equiv( actual, expected ), actual, expected, message, true );
1336 | },
1337 |
1338 | deepEqual: function( actual, expected, message ) {
1339 | this.push( QUnit.equiv( actual, expected ), actual, expected, message );
1340 | },
1341 |
1342 | notDeepEqual: function( actual, expected, message ) {
1343 | this.push( !QUnit.equiv( actual, expected ), actual, expected, message, true );
1344 | },
1345 |
1346 | strictEqual: function( actual, expected, message ) {
1347 | this.push( expected === actual, actual, expected, message );
1348 | },
1349 |
1350 | notStrictEqual: function( actual, expected, message ) {
1351 | this.push( expected !== actual, actual, expected, message, true );
1352 | },
1353 |
1354 | "throws": function( block, expected, message ) {
1355 | var actual, expectedType,
1356 | expectedOutput = expected,
1357 | ok = false,
1358 | currentTest = ( this instanceof Assert && this.test ) || QUnit.config.current;
1359 |
1360 | // 'expected' is optional unless doing string comparison
1361 | if ( message == null && typeof expected === "string" ) {
1362 | message = expected;
1363 | expected = null;
1364 | }
1365 |
1366 | currentTest.ignoreGlobalErrors = true;
1367 | try {
1368 | block.call( currentTest.testEnvironment );
1369 | } catch (e) {
1370 | actual = e;
1371 | }
1372 | currentTest.ignoreGlobalErrors = false;
1373 |
1374 | if ( actual ) {
1375 | expectedType = QUnit.objectType( expected );
1376 |
1377 | // we don't want to validate thrown error
1378 | if ( !expected ) {
1379 | ok = true;
1380 | expectedOutput = null;
1381 |
1382 | // expected is a regexp
1383 | } else if ( expectedType === "regexp" ) {
1384 | ok = expected.test( errorString( actual ) );
1385 |
1386 | // expected is a string
1387 | } else if ( expectedType === "string" ) {
1388 | ok = expected === errorString( actual );
1389 |
1390 | // expected is a constructor, maybe an Error constructor
1391 | } else if ( expectedType === "function" && actual instanceof expected ) {
1392 | ok = true;
1393 |
1394 | // expected is an Error object
1395 | } else if ( expectedType === "object" ) {
1396 | ok = actual instanceof expected.constructor &&
1397 | actual.name === expected.name &&
1398 | actual.message === expected.message;
1399 |
1400 | // expected is a validation function which returns true if validation passed
1401 | } else if ( expectedType === "function" && expected.call( {}, actual ) === true ) {
1402 | expectedOutput = null;
1403 | ok = true;
1404 | }
1405 | }
1406 |
1407 | currentTest.assert.push( ok, actual, expectedOutput, message );
1408 | }
1409 | };
1410 |
1411 | // Provide an alternative to assert.throws(), for enviroments that consider throws a reserved word
1412 | // Known to us are: Closure Compiler, Narwhal
1413 | (function() {
1414 | /*jshint sub:true */
1415 | Assert.prototype.raises = Assert.prototype[ "throws" ];
1416 | }());
1417 |
1418 | function errorString( error ) {
1419 | var name, message,
1420 | resultErrorString = error.toString();
1421 | if ( resultErrorString.substring( 0, 7 ) === "[object" ) {
1422 | name = error.name ? error.name.toString() : "Error";
1423 | message = error.message ? error.message.toString() : "";
1424 | if ( name && message ) {
1425 | return name + ": " + message;
1426 | } else if ( name ) {
1427 | return name;
1428 | } else if ( message ) {
1429 | return message;
1430 | } else {
1431 | return "Error";
1432 | }
1433 | } else {
1434 | return resultErrorString;
1435 | }
1436 | }
1437 |
1438 | // Test for equality any JavaScript type.
1439 | // Author: Philippe Rathé
1440 | QUnit.equiv = (function() {
1441 |
1442 | // Call the o related callback with the given arguments.
1443 | function bindCallbacks( o, callbacks, args ) {
1444 | var prop = QUnit.objectType( o );
1445 | if ( prop ) {
1446 | if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) {
1447 | return callbacks[ prop ].apply( callbacks, args );
1448 | } else {
1449 | return callbacks[ prop ]; // or undefined
1450 | }
1451 | }
1452 | }
1453 |
1454 | // the real equiv function
1455 | var innerEquiv,
1456 |
1457 | // stack to decide between skip/abort functions
1458 | callers = [],
1459 |
1460 | // stack to avoiding loops from circular referencing
1461 | parents = [],
1462 | parentsB = [],
1463 |
1464 | getProto = Object.getPrototypeOf || function( obj ) {
1465 | /* jshint camelcase: false, proto: true */
1466 | return obj.__proto__;
1467 | },
1468 | callbacks = (function() {
1469 |
1470 | // for string, boolean, number and null
1471 | function useStrictEquality( b, a ) {
1472 |
1473 | /*jshint eqeqeq:false */
1474 | if ( b instanceof a.constructor || a instanceof b.constructor ) {
1475 |
1476 | // to catch short annotation VS 'new' annotation of a
1477 | // declaration
1478 | // e.g. var i = 1;
1479 | // var j = new Number(1);
1480 | return a == b;
1481 | } else {
1482 | return a === b;
1483 | }
1484 | }
1485 |
1486 | return {
1487 | "string": useStrictEquality,
1488 | "boolean": useStrictEquality,
1489 | "number": useStrictEquality,
1490 | "null": useStrictEquality,
1491 | "undefined": useStrictEquality,
1492 |
1493 | "nan": function( b ) {
1494 | return isNaN( b );
1495 | },
1496 |
1497 | "date": function( b, a ) {
1498 | return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
1499 | },
1500 |
1501 | "regexp": function( b, a ) {
1502 | return QUnit.objectType( b ) === "regexp" &&
1503 |
1504 | // the regex itself
1505 | a.source === b.source &&
1506 |
1507 | // and its modifiers
1508 | a.global === b.global &&
1509 |
1510 | // (gmi) ...
1511 | a.ignoreCase === b.ignoreCase &&
1512 | a.multiline === b.multiline &&
1513 | a.sticky === b.sticky;
1514 | },
1515 |
1516 | // - skip when the property is a method of an instance (OOP)
1517 | // - abort otherwise,
1518 | // initial === would have catch identical references anyway
1519 | "function": function() {
1520 | var caller = callers[ callers.length - 1 ];
1521 | return caller !== Object && typeof caller !== "undefined";
1522 | },
1523 |
1524 | "array": function( b, a ) {
1525 | var i, j, len, loop, aCircular, bCircular;
1526 |
1527 | // b could be an object literal here
1528 | if ( QUnit.objectType( b ) !== "array" ) {
1529 | return false;
1530 | }
1531 |
1532 | len = a.length;
1533 | if ( len !== b.length ) {
1534 | // safe and faster
1535 | return false;
1536 | }
1537 |
1538 | // track reference to avoid circular references
1539 | parents.push( a );
1540 | parentsB.push( b );
1541 | for ( i = 0; i < len; i++ ) {
1542 | loop = false;
1543 | for ( j = 0; j < parents.length; j++ ) {
1544 | aCircular = parents[ j ] === a[ i ];
1545 | bCircular = parentsB[ j ] === b[ i ];
1546 | if ( aCircular || bCircular ) {
1547 | if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
1548 | loop = true;
1549 | } else {
1550 | parents.pop();
1551 | parentsB.pop();
1552 | return false;
1553 | }
1554 | }
1555 | }
1556 | if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
1557 | parents.pop();
1558 | parentsB.pop();
1559 | return false;
1560 | }
1561 | }
1562 | parents.pop();
1563 | parentsB.pop();
1564 | return true;
1565 | },
1566 |
1567 | "set": function( b, a ) {
1568 | var aArray, bArray;
1569 |
1570 | // b could be any object here
1571 | if ( QUnit.objectType( b ) !== "set" ) {
1572 | return false;
1573 | }
1574 |
1575 | aArray = [];
1576 | a.forEach( function( v ) {
1577 | aArray.push( v );
1578 | });
1579 | bArray = [];
1580 | b.forEach( function( v ) {
1581 | bArray.push( v );
1582 | });
1583 |
1584 | return innerEquiv( bArray, aArray );
1585 | },
1586 |
1587 | "map": function( b, a ) {
1588 | var aArray, bArray;
1589 |
1590 | // b could be any object here
1591 | if ( QUnit.objectType( b ) !== "map" ) {
1592 | return false;
1593 | }
1594 |
1595 | aArray = [];
1596 | a.forEach( function( v, k ) {
1597 | aArray.push( [ k, v ] );
1598 | });
1599 | bArray = [];
1600 | b.forEach( function( v, k ) {
1601 | bArray.push( [ k, v ] );
1602 | });
1603 |
1604 | return innerEquiv( bArray, aArray );
1605 | },
1606 |
1607 | "object": function( b, a ) {
1608 |
1609 | /*jshint forin:false */
1610 | var i, j, loop, aCircular, bCircular,
1611 | // Default to true
1612 | eq = true,
1613 | aProperties = [],
1614 | bProperties = [];
1615 |
1616 | // comparing constructors is more strict than using
1617 | // instanceof
1618 | if ( a.constructor !== b.constructor ) {
1619 |
1620 | // Allow objects with no prototype to be equivalent to
1621 | // objects with Object as their constructor.
1622 | if ( !( ( getProto( a ) === null && getProto( b ) === Object.prototype ) ||
1623 | ( getProto( b ) === null && getProto( a ) === Object.prototype ) ) ) {
1624 | return false;
1625 | }
1626 | }
1627 |
1628 | // stack constructor before traversing properties
1629 | callers.push( a.constructor );
1630 |
1631 | // track reference to avoid circular references
1632 | parents.push( a );
1633 | parentsB.push( b );
1634 |
1635 | // be strict: don't ensure hasOwnProperty and go deep
1636 | for ( i in a ) {
1637 | loop = false;
1638 | for ( j = 0; j < parents.length; j++ ) {
1639 | aCircular = parents[ j ] === a[ i ];
1640 | bCircular = parentsB[ j ] === b[ i ];
1641 | if ( aCircular || bCircular ) {
1642 | if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
1643 | loop = true;
1644 | } else {
1645 | eq = false;
1646 | break;
1647 | }
1648 | }
1649 | }
1650 | aProperties.push( i );
1651 | if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
1652 | eq = false;
1653 | break;
1654 | }
1655 | }
1656 |
1657 | parents.pop();
1658 | parentsB.pop();
1659 | callers.pop(); // unstack, we are done
1660 |
1661 | for ( i in b ) {
1662 | bProperties.push( i ); // collect b's properties
1663 | }
1664 |
1665 | // Ensures identical properties name
1666 | return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
1667 | }
1668 | };
1669 | }());
1670 |
1671 | innerEquiv = function() { // can take multiple arguments
1672 | var args = [].slice.apply( arguments );
1673 | if ( args.length < 2 ) {
1674 | return true; // end transition
1675 | }
1676 |
1677 | return ( (function( a, b ) {
1678 | if ( a === b ) {
1679 | return true; // catch the most you can
1680 | } else if ( a === null || b === null || typeof a === "undefined" ||
1681 | typeof b === "undefined" ||
1682 | QUnit.objectType( a ) !== QUnit.objectType( b ) ) {
1683 |
1684 | // don't lose time with error prone cases
1685 | return false;
1686 | } else {
1687 | return bindCallbacks( a, callbacks, [ b, a ] );
1688 | }
1689 |
1690 | // apply transition with (1..n) arguments
1691 | }( args[ 0 ], args[ 1 ] ) ) &&
1692 | innerEquiv.apply( this, args.splice( 1, args.length - 1 ) ) );
1693 | };
1694 |
1695 | return innerEquiv;
1696 | }());
1697 |
1698 | // Based on jsDump by Ariel Flesler
1699 | // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
1700 | QUnit.dump = (function() {
1701 | function quote( str ) {
1702 | return "\"" + str.toString().replace( /\\/g, "\\\\" ).replace( /"/g, "\\\"" ) + "\"";
1703 | }
1704 | function literal( o ) {
1705 | return o + "";
1706 | }
1707 | function join( pre, arr, post ) {
1708 | var s = dump.separator(),
1709 | base = dump.indent(),
1710 | inner = dump.indent( 1 );
1711 | if ( arr.join ) {
1712 | arr = arr.join( "," + s + inner );
1713 | }
1714 | if ( !arr ) {
1715 | return pre + post;
1716 | }
1717 | return [ pre, inner + arr, base + post ].join( s );
1718 | }
1719 | function array( arr, stack ) {
1720 | var i = arr.length,
1721 | ret = new Array( i );
1722 |
1723 | if ( dump.maxDepth && dump.depth > dump.maxDepth ) {
1724 | return "[object Array]";
1725 | }
1726 |
1727 | this.up();
1728 | while ( i-- ) {
1729 | ret[ i ] = this.parse( arr[ i ], undefined, stack );
1730 | }
1731 | this.down();
1732 | return join( "[", ret, "]" );
1733 | }
1734 |
1735 | var reName = /^function (\w+)/,
1736 | dump = {
1737 |
1738 | // objType is used mostly internally, you can fix a (custom) type in advance
1739 | parse: function( obj, objType, stack ) {
1740 | stack = stack || [];
1741 | var res, parser, parserType,
1742 | inStack = inArray( obj, stack );
1743 |
1744 | if ( inStack !== -1 ) {
1745 | return "recursion(" + ( inStack - stack.length ) + ")";
1746 | }
1747 |
1748 | objType = objType || this.typeOf( obj );
1749 | parser = this.parsers[ objType ];
1750 | parserType = typeof parser;
1751 |
1752 | if ( parserType === "function" ) {
1753 | stack.push( obj );
1754 | res = parser.call( this, obj, stack );
1755 | stack.pop();
1756 | return res;
1757 | }
1758 | return ( parserType === "string" ) ? parser : this.parsers.error;
1759 | },
1760 | typeOf: function( obj ) {
1761 | var type;
1762 | if ( obj === null ) {
1763 | type = "null";
1764 | } else if ( typeof obj === "undefined" ) {
1765 | type = "undefined";
1766 | } else if ( QUnit.is( "regexp", obj ) ) {
1767 | type = "regexp";
1768 | } else if ( QUnit.is( "date", obj ) ) {
1769 | type = "date";
1770 | } else if ( QUnit.is( "function", obj ) ) {
1771 | type = "function";
1772 | } else if ( obj.setInterval !== undefined &&
1773 | obj.document !== undefined &&
1774 | obj.nodeType === undefined ) {
1775 | type = "window";
1776 | } else if ( obj.nodeType === 9 ) {
1777 | type = "document";
1778 | } else if ( obj.nodeType ) {
1779 | type = "node";
1780 | } else if (
1781 |
1782 | // native arrays
1783 | toString.call( obj ) === "[object Array]" ||
1784 |
1785 | // NodeList objects
1786 | ( typeof obj.length === "number" && obj.item !== undefined &&
1787 | ( obj.length ? obj.item( 0 ) === obj[ 0 ] : ( obj.item( 0 ) === null &&
1788 | obj[ 0 ] === undefined ) ) )
1789 | ) {
1790 | type = "array";
1791 | } else if ( obj.constructor === Error.prototype.constructor ) {
1792 | type = "error";
1793 | } else {
1794 | type = typeof obj;
1795 | }
1796 | return type;
1797 | },
1798 | separator: function() {
1799 | return this.multiline ? this.HTML ? " " : "\n" : this.HTML ? " " : " ";
1800 | },
1801 | // extra can be a number, shortcut for increasing-calling-decreasing
1802 | indent: function( extra ) {
1803 | if ( !this.multiline ) {
1804 | return "";
1805 | }
1806 | var chr = this.indentChar;
1807 | if ( this.HTML ) {
1808 | chr = chr.replace( /\t/g, " " ).replace( / /g, " " );
1809 | }
1810 | return new Array( this.depth + ( extra || 0 ) ).join( chr );
1811 | },
1812 | up: function( a ) {
1813 | this.depth += a || 1;
1814 | },
1815 | down: function( a ) {
1816 | this.depth -= a || 1;
1817 | },
1818 | setParser: function( name, parser ) {
1819 | this.parsers[ name ] = parser;
1820 | },
1821 | // The next 3 are exposed so you can use them
1822 | quote: quote,
1823 | literal: literal,
1824 | join: join,
1825 | //
1826 | depth: 1,
1827 | maxDepth: QUnit.config.maxDepth,
1828 |
1829 | // This is the list of parsers, to modify them, use dump.setParser
1830 | parsers: {
1831 | window: "[Window]",
1832 | document: "[Document]",
1833 | error: function( error ) {
1834 | return "Error(\"" + error.message + "\")";
1835 | },
1836 | unknown: "[Unknown]",
1837 | "null": "null",
1838 | "undefined": "undefined",
1839 | "function": function( fn ) {
1840 | var ret = "function",
1841 |
1842 | // functions never have name in IE
1843 | name = "name" in fn ? fn.name : ( reName.exec( fn ) || [] )[ 1 ];
1844 |
1845 | if ( name ) {
1846 | ret += " " + name;
1847 | }
1848 | ret += "( ";
1849 |
1850 | ret = [ ret, dump.parse( fn, "functionArgs" ), "){" ].join( "" );
1851 | return join( ret, dump.parse( fn, "functionCode" ), "}" );
1852 | },
1853 | array: array,
1854 | nodelist: array,
1855 | "arguments": array,
1856 | object: function( map, stack ) {
1857 | var keys, key, val, i, nonEnumerableProperties,
1858 | ret = [];
1859 |
1860 | if ( dump.maxDepth && dump.depth > dump.maxDepth ) {
1861 | return "[object Object]";
1862 | }
1863 |
1864 | dump.up();
1865 | keys = [];
1866 | for ( key in map ) {
1867 | keys.push( key );
1868 | }
1869 |
1870 | // Some properties are not always enumerable on Error objects.
1871 | nonEnumerableProperties = [ "message", "name" ];
1872 | for ( i in nonEnumerableProperties ) {
1873 | key = nonEnumerableProperties[ i ];
1874 | if ( key in map && inArray( key, keys ) < 0 ) {
1875 | keys.push( key );
1876 | }
1877 | }
1878 | keys.sort();
1879 | for ( i = 0; i < keys.length; i++ ) {
1880 | key = keys[ i ];
1881 | val = map[ key ];
1882 | ret.push( dump.parse( key, "key" ) + ": " +
1883 | dump.parse( val, undefined, stack ) );
1884 | }
1885 | dump.down();
1886 | return join( "{", ret, "}" );
1887 | },
1888 | node: function( node ) {
1889 | var len, i, val,
1890 | open = dump.HTML ? "<" : "<",
1891 | close = dump.HTML ? ">" : ">",
1892 | tag = node.nodeName.toLowerCase(),
1893 | ret = open + tag,
1894 | attrs = node.attributes;
1895 |
1896 | if ( attrs ) {
1897 | for ( i = 0, len = attrs.length; i < len; i++ ) {
1898 | val = attrs[ i ].nodeValue;
1899 |
1900 | // IE6 includes all attributes in .attributes, even ones not explicitly
1901 | // set. Those have values like undefined, null, 0, false, "" or
1902 | // "inherit".
1903 | if ( val && val !== "inherit" ) {
1904 | ret += " " + attrs[ i ].nodeName + "=" +
1905 | dump.parse( val, "attribute" );
1906 | }
1907 | }
1908 | }
1909 | ret += close;
1910 |
1911 | // Show content of TextNode or CDATASection
1912 | if ( node.nodeType === 3 || node.nodeType === 4 ) {
1913 | ret += node.nodeValue;
1914 | }
1915 |
1916 | return ret + open + "/" + tag + close;
1917 | },
1918 |
1919 | // function calls it internally, it's the arguments part of the function
1920 | functionArgs: function( fn ) {
1921 | var args,
1922 | l = fn.length;
1923 |
1924 | if ( !l ) {
1925 | return "";
1926 | }
1927 |
1928 | args = new Array( l );
1929 | while ( l-- ) {
1930 |
1931 | // 97 is 'a'
1932 | args[ l ] = String.fromCharCode( 97 + l );
1933 | }
1934 | return " " + args.join( ", " ) + " ";
1935 | },
1936 | // object calls it internally, the key part of an item in a map
1937 | key: quote,
1938 | // function calls it internally, it's the content of the function
1939 | functionCode: "[code]",
1940 | // node calls it internally, it's an html attribute value
1941 | attribute: quote,
1942 | string: quote,
1943 | date: quote,
1944 | regexp: literal,
1945 | number: literal,
1946 | "boolean": literal
1947 | },
1948 | // if true, entities are escaped ( <, >, \t, space and \n )
1949 | HTML: false,
1950 | // indentation unit
1951 | indentChar: " ",
1952 | // if true, items in a collection, are separated by a \n, else just a space.
1953 | multiline: true
1954 | };
1955 |
1956 | return dump;
1957 | }());
1958 |
1959 | // back compat
1960 | QUnit.jsDump = QUnit.dump;
1961 |
1962 | // For browser, export only select globals
1963 | if ( defined.document ) {
1964 |
1965 | // Deprecated
1966 | // Extend assert methods to QUnit and Global scope through Backwards compatibility
1967 | (function() {
1968 | var i,
1969 | assertions = Assert.prototype;
1970 |
1971 | function applyCurrent( current ) {
1972 | return function() {
1973 | var assert = new Assert( QUnit.config.current );
1974 | current.apply( assert, arguments );
1975 | };
1976 | }
1977 |
1978 | for ( i in assertions ) {
1979 | QUnit[ i ] = applyCurrent( assertions[ i ] );
1980 | }
1981 | })();
1982 |
1983 | (function() {
1984 | var i, l,
1985 | keys = [
1986 | "test",
1987 | "module",
1988 | "expect",
1989 | "asyncTest",
1990 | "start",
1991 | "stop",
1992 | "ok",
1993 | "notOk",
1994 | "equal",
1995 | "notEqual",
1996 | "propEqual",
1997 | "notPropEqual",
1998 | "deepEqual",
1999 | "notDeepEqual",
2000 | "strictEqual",
2001 | "notStrictEqual",
2002 | "throws"
2003 | ];
2004 |
2005 | for ( i = 0, l = keys.length; i < l; i++ ) {
2006 | window[ keys[ i ] ] = QUnit[ keys[ i ] ];
2007 | }
2008 | })();
2009 |
2010 | window.QUnit = QUnit;
2011 | }
2012 |
2013 | // For nodejs
2014 | if ( typeof module !== "undefined" && module && module.exports ) {
2015 | module.exports = QUnit;
2016 |
2017 | // For consistency with CommonJS environments' exports
2018 | module.exports.QUnit = QUnit;
2019 | }
2020 |
2021 | // For CommonJS with exports, but without module.exports, like Rhino
2022 | if ( typeof exports !== "undefined" && exports ) {
2023 | exports.QUnit = QUnit;
2024 | }
2025 |
2026 | if ( typeof define === "function" && define.amd ) {
2027 | define( function() {
2028 | return QUnit;
2029 | } );
2030 | QUnit.config.autostart = false;
2031 | }
2032 |
2033 | /*
2034 | * This file is a modified version of google-diff-match-patch's JavaScript implementation
2035 | * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
2036 | * modifications are licensed as more fully set forth in LICENSE.txt.
2037 | *
2038 | * The original source of google-diff-match-patch is attributable and licensed as follows:
2039 | *
2040 | * Copyright 2006 Google Inc.
2041 | * http://code.google.com/p/google-diff-match-patch/
2042 | *
2043 | * Licensed under the Apache License, Version 2.0 (the "License");
2044 | * you may not use this file except in compliance with the License.
2045 | * You may obtain a copy of the License at
2046 | *
2047 | * http://www.apache.org/licenses/LICENSE-2.0
2048 | *
2049 | * Unless required by applicable law or agreed to in writing, software
2050 | * distributed under the License is distributed on an "AS IS" BASIS,
2051 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2052 | * See the License for the specific language governing permissions and
2053 | * limitations under the License.
2054 | *
2055 | * More Info:
2056 | * https://code.google.com/p/google-diff-match-patch/
2057 | *
2058 | * Usage: QUnit.diff(expected, actual)
2059 | *
2060 | */
2061 | QUnit.diff = ( function() {
2062 | function DiffMatchPatch() {
2063 | }
2064 |
2065 | // DIFF FUNCTIONS
2066 |
2067 | /**
2068 | * The data structure representing a diff is an array of tuples:
2069 | * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
2070 | * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
2071 | */
2072 | var DIFF_DELETE = -1,
2073 | DIFF_INSERT = 1,
2074 | DIFF_EQUAL = 0;
2075 |
2076 | /**
2077 | * Find the differences between two texts. Simplifies the problem by stripping
2078 | * any common prefix or suffix off the texts before diffing.
2079 | * @param {string} text1 Old string to be diffed.
2080 | * @param {string} text2 New string to be diffed.
2081 | * @param {boolean=} optChecklines Optional speedup flag. If present and false,
2082 | * then don't run a line-level diff first to identify the changed areas.
2083 | * Defaults to true, which does a faster, slightly less optimal diff.
2084 | * @return {!Array.} Array of diff tuples.
2085 | */
2086 | DiffMatchPatch.prototype.DiffMain = function( text1, text2, optChecklines ) {
2087 | var deadline, checklines, commonlength,
2088 | commonprefix, commonsuffix, diffs;
2089 |
2090 | // The diff must be complete in up to 1 second.
2091 | deadline = ( new Date() ).getTime() + 1000;
2092 |
2093 | // Check for null inputs.
2094 | if ( text1 === null || text2 === null ) {
2095 | throw new Error( "Null input. (DiffMain)" );
2096 | }
2097 |
2098 | // Check for equality (speedup).
2099 | if ( text1 === text2 ) {
2100 | if ( text1 ) {
2101 | return [
2102 | [ DIFF_EQUAL, text1 ]
2103 | ];
2104 | }
2105 | return [];
2106 | }
2107 |
2108 | if ( typeof optChecklines === "undefined" ) {
2109 | optChecklines = true;
2110 | }
2111 |
2112 | checklines = optChecklines;
2113 |
2114 | // Trim off common prefix (speedup).
2115 | commonlength = this.diffCommonPrefix( text1, text2 );
2116 | commonprefix = text1.substring( 0, commonlength );
2117 | text1 = text1.substring( commonlength );
2118 | text2 = text2.substring( commonlength );
2119 |
2120 | // Trim off common suffix (speedup).
2121 | commonlength = this.diffCommonSuffix( text1, text2 );
2122 | commonsuffix = text1.substring( text1.length - commonlength );
2123 | text1 = text1.substring( 0, text1.length - commonlength );
2124 | text2 = text2.substring( 0, text2.length - commonlength );
2125 |
2126 | // Compute the diff on the middle block.
2127 | diffs = this.diffCompute( text1, text2, checklines, deadline );
2128 |
2129 | // Restore the prefix and suffix.
2130 | if ( commonprefix ) {
2131 | diffs.unshift( [ DIFF_EQUAL, commonprefix ] );
2132 | }
2133 | if ( commonsuffix ) {
2134 | diffs.push( [ DIFF_EQUAL, commonsuffix ] );
2135 | }
2136 | this.diffCleanupMerge( diffs );
2137 | return diffs;
2138 | };
2139 |
2140 | /**
2141 | * Reduce the number of edits by eliminating operationally trivial equalities.
2142 | * @param {!Array.} diffs Array of diff tuples.
2143 | */
2144 | DiffMatchPatch.prototype.diffCleanupEfficiency = function( diffs ) {
2145 | var changes, equalities, equalitiesLength, lastequality,
2146 | pointer, preIns, preDel, postIns, postDel;
2147 | changes = false;
2148 | equalities = []; // Stack of indices where equalities are found.
2149 | equalitiesLength = 0; // Keeping our own length var is faster in JS.
2150 | /** @type {?string} */
2151 | lastequality = null;
2152 | // Always equal to diffs[equalities[equalitiesLength - 1]][1]
2153 | pointer = 0; // Index of current position.
2154 | // Is there an insertion operation before the last equality.
2155 | preIns = false;
2156 | // Is there a deletion operation before the last equality.
2157 | preDel = false;
2158 | // Is there an insertion operation after the last equality.
2159 | postIns = false;
2160 | // Is there a deletion operation after the last equality.
2161 | postDel = false;
2162 | while ( pointer < diffs.length ) {
2163 |
2164 | // Equality found.
2165 | if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) {
2166 | if ( diffs[ pointer ][ 1 ].length < 4 && ( postIns || postDel ) ) {
2167 |
2168 | // Candidate found.
2169 | equalities[ equalitiesLength++ ] = pointer;
2170 | preIns = postIns;
2171 | preDel = postDel;
2172 | lastequality = diffs[ pointer ][ 1 ];
2173 | } else {
2174 |
2175 | // Not a candidate, and can never become one.
2176 | equalitiesLength = 0;
2177 | lastequality = null;
2178 | }
2179 | postIns = postDel = false;
2180 |
2181 | // An insertion or deletion.
2182 | } else {
2183 |
2184 | if ( diffs[ pointer ][ 0 ] === DIFF_DELETE ) {
2185 | postDel = true;
2186 | } else {
2187 | postIns = true;
2188 | }
2189 |
2190 | /*
2191 | * Five types to be split:
2192 | * A BXYC D
2193 | * A XC D
2194 | * A BXC
2195 | * AXC D
2196 | * A BXC
2197 | */
2198 | if ( lastequality && ( ( preIns && preDel && postIns && postDel ) ||
2199 | ( ( lastequality.length < 2 ) &&
2200 | ( preIns + preDel + postIns + postDel ) === 3 ) ) ) {
2201 |
2202 | // Duplicate record.
2203 | diffs.splice(
2204 | equalities[ equalitiesLength - 1 ],
2205 | 0,
2206 | [ DIFF_DELETE, lastequality ]
2207 | );
2208 |
2209 | // Change second copy to insert.
2210 | diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT;
2211 | equalitiesLength--; // Throw away the equality we just deleted;
2212 | lastequality = null;
2213 | if ( preIns && preDel ) {
2214 | // No changes made which could affect previous entry, keep going.
2215 | postIns = postDel = true;
2216 | equalitiesLength = 0;
2217 | } else {
2218 | equalitiesLength--; // Throw away the previous equality.
2219 | pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1;
2220 | postIns = postDel = false;
2221 | }
2222 | changes = true;
2223 | }
2224 | }
2225 | pointer++;
2226 | }
2227 |
2228 | if ( changes ) {
2229 | this.diffCleanupMerge( diffs );
2230 | }
2231 | };
2232 |
2233 | /**
2234 | * Convert a diff array into a pretty HTML report.
2235 | * @param {!Array.} diffs Array of diff tuples.
2236 | * @param {integer} string to be beautified.
2237 | * @return {string} HTML representation.
2238 | */
2239 | DiffMatchPatch.prototype.diffPrettyHtml = function( diffs ) {
2240 | var op, data, x,
2241 | html = [];
2242 | for ( x = 0; x < diffs.length; x++ ) {
2243 | op = diffs[ x ][ 0 ]; // Operation (insert, delete, equal)
2244 | data = diffs[ x ][ 1 ]; // Text of change.
2245 | switch ( op ) {
2246 | case DIFF_INSERT:
2247 | html[ x ] = "" + data + " ";
2248 | break;
2249 | case DIFF_DELETE:
2250 | html[ x ] = "" + data + "";
2251 | break;
2252 | case DIFF_EQUAL:
2253 | html[ x ] = "" + data + " ";
2254 | break;
2255 | }
2256 | }
2257 | return html.join( "" );
2258 | };
2259 |
2260 | /**
2261 | * Determine the common prefix of two strings.
2262 | * @param {string} text1 First string.
2263 | * @param {string} text2 Second string.
2264 | * @return {number} The number of characters common to the start of each
2265 | * string.
2266 | */
2267 | DiffMatchPatch.prototype.diffCommonPrefix = function( text1, text2 ) {
2268 | var pointermid, pointermax, pointermin, pointerstart;
2269 | // Quick check for common null cases.
2270 | if ( !text1 || !text2 || text1.charAt( 0 ) !== text2.charAt( 0 ) ) {
2271 | return 0;
2272 | }
2273 | // Binary search.
2274 | // Performance analysis: http://neil.fraser.name/news/2007/10/09/
2275 | pointermin = 0;
2276 | pointermax = Math.min( text1.length, text2.length );
2277 | pointermid = pointermax;
2278 | pointerstart = 0;
2279 | while ( pointermin < pointermid ) {
2280 | if ( text1.substring( pointerstart, pointermid ) ===
2281 | text2.substring( pointerstart, pointermid ) ) {
2282 | pointermin = pointermid;
2283 | pointerstart = pointermin;
2284 | } else {
2285 | pointermax = pointermid;
2286 | }
2287 | pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
2288 | }
2289 | return pointermid;
2290 | };
2291 |
2292 | /**
2293 | * Determine the common suffix of two strings.
2294 | * @param {string} text1 First string.
2295 | * @param {string} text2 Second string.
2296 | * @return {number} The number of characters common to the end of each string.
2297 | */
2298 | DiffMatchPatch.prototype.diffCommonSuffix = function( text1, text2 ) {
2299 | var pointermid, pointermax, pointermin, pointerend;
2300 | // Quick check for common null cases.
2301 | if ( !text1 ||
2302 | !text2 ||
2303 | text1.charAt( text1.length - 1 ) !== text2.charAt( text2.length - 1 ) ) {
2304 | return 0;
2305 | }
2306 | // Binary search.
2307 | // Performance analysis: http://neil.fraser.name/news/2007/10/09/
2308 | pointermin = 0;
2309 | pointermax = Math.min( text1.length, text2.length );
2310 | pointermid = pointermax;
2311 | pointerend = 0;
2312 | while ( pointermin < pointermid ) {
2313 | if ( text1.substring( text1.length - pointermid, text1.length - pointerend ) ===
2314 | text2.substring( text2.length - pointermid, text2.length - pointerend ) ) {
2315 | pointermin = pointermid;
2316 | pointerend = pointermin;
2317 | } else {
2318 | pointermax = pointermid;
2319 | }
2320 | pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
2321 | }
2322 | return pointermid;
2323 | };
2324 |
2325 | /**
2326 | * Find the differences between two texts. Assumes that the texts do not
2327 | * have any common prefix or suffix.
2328 | * @param {string} text1 Old string to be diffed.
2329 | * @param {string} text2 New string to be diffed.
2330 | * @param {boolean} checklines Speedup flag. If false, then don't run a
2331 | * line-level diff first to identify the changed areas.
2332 | * If true, then run a faster, slightly less optimal diff.
2333 | * @param {number} deadline Time when the diff should be complete by.
2334 | * @return {!Array.} Array of diff tuples.
2335 | * @private
2336 | */
2337 | DiffMatchPatch.prototype.diffCompute = function( text1, text2, checklines, deadline ) {
2338 | var diffs, longtext, shorttext, i, hm,
2339 | text1A, text2A, text1B, text2B,
2340 | midCommon, diffsA, diffsB;
2341 |
2342 | if ( !text1 ) {
2343 | // Just add some text (speedup).
2344 | return [
2345 | [ DIFF_INSERT, text2 ]
2346 | ];
2347 | }
2348 |
2349 | if ( !text2 ) {
2350 | // Just delete some text (speedup).
2351 | return [
2352 | [ DIFF_DELETE, text1 ]
2353 | ];
2354 | }
2355 |
2356 | longtext = text1.length > text2.length ? text1 : text2;
2357 | shorttext = text1.length > text2.length ? text2 : text1;
2358 | i = longtext.indexOf( shorttext );
2359 | if ( i !== -1 ) {
2360 | // Shorter text is inside the longer text (speedup).
2361 | diffs = [
2362 | [ DIFF_INSERT, longtext.substring( 0, i ) ],
2363 | [ DIFF_EQUAL, shorttext ],
2364 | [ DIFF_INSERT, longtext.substring( i + shorttext.length ) ]
2365 | ];
2366 | // Swap insertions for deletions if diff is reversed.
2367 | if ( text1.length > text2.length ) {
2368 | diffs[ 0 ][ 0 ] = diffs[ 2 ][ 0 ] = DIFF_DELETE;
2369 | }
2370 | return diffs;
2371 | }
2372 |
2373 | if ( shorttext.length === 1 ) {
2374 | // Single character string.
2375 | // After the previous speedup, the character can't be an equality.
2376 | return [
2377 | [ DIFF_DELETE, text1 ],
2378 | [ DIFF_INSERT, text2 ]
2379 | ];
2380 | }
2381 |
2382 | // Check to see if the problem can be split in two.
2383 | hm = this.diffHalfMatch( text1, text2 );
2384 | if ( hm ) {
2385 | // A half-match was found, sort out the return data.
2386 | text1A = hm[ 0 ];
2387 | text1B = hm[ 1 ];
2388 | text2A = hm[ 2 ];
2389 | text2B = hm[ 3 ];
2390 | midCommon = hm[ 4 ];
2391 | // Send both pairs off for separate processing.
2392 | diffsA = this.DiffMain( text1A, text2A, checklines, deadline );
2393 | diffsB = this.DiffMain( text1B, text2B, checklines, deadline );
2394 | // Merge the results.
2395 | return diffsA.concat( [
2396 | [ DIFF_EQUAL, midCommon ]
2397 | ], diffsB );
2398 | }
2399 |
2400 | if ( checklines && text1.length > 100 && text2.length > 100 ) {
2401 | return this.diffLineMode( text1, text2, deadline );
2402 | }
2403 |
2404 | return this.diffBisect( text1, text2, deadline );
2405 | };
2406 |
2407 | /**
2408 | * Do the two texts share a substring which is at least half the length of the
2409 | * longer text?
2410 | * This speedup can produce non-minimal diffs.
2411 | * @param {string} text1 First string.
2412 | * @param {string} text2 Second string.
2413 | * @return {Array.} Five element Array, containing the prefix of
2414 | * text1, the suffix of text1, the prefix of text2, the suffix of
2415 | * text2 and the common middle. Or null if there was no match.
2416 | * @private
2417 | */
2418 | DiffMatchPatch.prototype.diffHalfMatch = function( text1, text2 ) {
2419 | var longtext, shorttext, dmp,
2420 | text1A, text2B, text2A, text1B, midCommon,
2421 | hm1, hm2, hm;
2422 |
2423 | longtext = text1.length > text2.length ? text1 : text2;
2424 | shorttext = text1.length > text2.length ? text2 : text1;
2425 | if ( longtext.length < 4 || shorttext.length * 2 < longtext.length ) {
2426 | return null; // Pointless.
2427 | }
2428 | dmp = this; // 'this' becomes 'window' in a closure.
2429 |
2430 | /**
2431 | * Does a substring of shorttext exist within longtext such that the substring
2432 | * is at least half the length of longtext?
2433 | * Closure, but does not reference any external variables.
2434 | * @param {string} longtext Longer string.
2435 | * @param {string} shorttext Shorter string.
2436 | * @param {number} i Start index of quarter length substring within longtext.
2437 | * @return {Array.} Five element Array, containing the prefix of
2438 | * longtext, the suffix of longtext, the prefix of shorttext, the suffix
2439 | * of shorttext and the common middle. Or null if there was no match.
2440 | * @private
2441 | */
2442 | function diffHalfMatchI( longtext, shorttext, i ) {
2443 | var seed, j, bestCommon, prefixLength, suffixLength,
2444 | bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
2445 | // Start with a 1/4 length substring at position i as a seed.
2446 | seed = longtext.substring( i, i + Math.floor( longtext.length / 4 ) );
2447 | j = -1;
2448 | bestCommon = "";
2449 | while ( ( j = shorttext.indexOf( seed, j + 1 ) ) !== -1 ) {
2450 | prefixLength = dmp.diffCommonPrefix( longtext.substring( i ),
2451 | shorttext.substring( j ) );
2452 | suffixLength = dmp.diffCommonSuffix( longtext.substring( 0, i ),
2453 | shorttext.substring( 0, j ) );
2454 | if ( bestCommon.length < suffixLength + prefixLength ) {
2455 | bestCommon = shorttext.substring( j - suffixLength, j ) +
2456 | shorttext.substring( j, j + prefixLength );
2457 | bestLongtextA = longtext.substring( 0, i - suffixLength );
2458 | bestLongtextB = longtext.substring( i + prefixLength );
2459 | bestShorttextA = shorttext.substring( 0, j - suffixLength );
2460 | bestShorttextB = shorttext.substring( j + prefixLength );
2461 | }
2462 | }
2463 | if ( bestCommon.length * 2 >= longtext.length ) {
2464 | return [ bestLongtextA, bestLongtextB,
2465 | bestShorttextA, bestShorttextB, bestCommon
2466 | ];
2467 | } else {
2468 | return null;
2469 | }
2470 | }
2471 |
2472 | // First check if the second quarter is the seed for a half-match.
2473 | hm1 = diffHalfMatchI( longtext, shorttext,
2474 | Math.ceil( longtext.length / 4 ) );
2475 | // Check again based on the third quarter.
2476 | hm2 = diffHalfMatchI( longtext, shorttext,
2477 | Math.ceil( longtext.length / 2 ) );
2478 | if ( !hm1 && !hm2 ) {
2479 | return null;
2480 | } else if ( !hm2 ) {
2481 | hm = hm1;
2482 | } else if ( !hm1 ) {
2483 | hm = hm2;
2484 | } else {
2485 | // Both matched. Select the longest.
2486 | hm = hm1[ 4 ].length > hm2[ 4 ].length ? hm1 : hm2;
2487 | }
2488 |
2489 | // A half-match was found, sort out the return data.
2490 | text1A, text1B, text2A, text2B;
2491 | if ( text1.length > text2.length ) {
2492 | text1A = hm[ 0 ];
2493 | text1B = hm[ 1 ];
2494 | text2A = hm[ 2 ];
2495 | text2B = hm[ 3 ];
2496 | } else {
2497 | text2A = hm[ 0 ];
2498 | text2B = hm[ 1 ];
2499 | text1A = hm[ 2 ];
2500 | text1B = hm[ 3 ];
2501 | }
2502 | midCommon = hm[ 4 ];
2503 | return [ text1A, text1B, text2A, text2B, midCommon ];
2504 | };
2505 |
2506 | /**
2507 | * Do a quick line-level diff on both strings, then rediff the parts for
2508 | * greater accuracy.
2509 | * This speedup can produce non-minimal diffs.
2510 | * @param {string} text1 Old string to be diffed.
2511 | * @param {string} text2 New string to be diffed.
2512 | * @param {number} deadline Time when the diff should be complete by.
2513 | * @return {!Array.} Array of diff tuples.
2514 | * @private
2515 | */
2516 | DiffMatchPatch.prototype.diffLineMode = function( text1, text2, deadline ) {
2517 | var a, diffs, linearray, pointer, countInsert,
2518 | countDelete, textInsert, textDelete, j;
2519 | // Scan the text on a line-by-line basis first.
2520 | a = this.diffLinesToChars( text1, text2 );
2521 | text1 = a.chars1;
2522 | text2 = a.chars2;
2523 | linearray = a.lineArray;
2524 |
2525 | diffs = this.DiffMain( text1, text2, false, deadline );
2526 |
2527 | // Convert the diff back to original text.
2528 | this.diffCharsToLines( diffs, linearray );
2529 | // Eliminate freak matches (e.g. blank lines)
2530 | this.diffCleanupSemantic( diffs );
2531 |
2532 | // Rediff any replacement blocks, this time character-by-character.
2533 | // Add a dummy entry at the end.
2534 | diffs.push( [ DIFF_EQUAL, "" ] );
2535 | pointer = 0;
2536 | countDelete = 0;
2537 | countInsert = 0;
2538 | textDelete = "";
2539 | textInsert = "";
2540 | while ( pointer < diffs.length ) {
2541 | switch ( diffs[ pointer ][ 0 ] ) {
2542 | case DIFF_INSERT:
2543 | countInsert++;
2544 | textInsert += diffs[ pointer ][ 1 ];
2545 | break;
2546 | case DIFF_DELETE:
2547 | countDelete++;
2548 | textDelete += diffs[ pointer ][ 1 ];
2549 | break;
2550 | case DIFF_EQUAL:
2551 | // Upon reaching an equality, check for prior redundancies.
2552 | if ( countDelete >= 1 && countInsert >= 1 ) {
2553 | // Delete the offending records and add the merged ones.
2554 | diffs.splice( pointer - countDelete - countInsert,
2555 | countDelete + countInsert );
2556 | pointer = pointer - countDelete - countInsert;
2557 | a = this.DiffMain( textDelete, textInsert, false, deadline );
2558 | for ( j = a.length - 1; j >= 0; j-- ) {
2559 | diffs.splice( pointer, 0, a[ j ] );
2560 | }
2561 | pointer = pointer + a.length;
2562 | }
2563 | countInsert = 0;
2564 | countDelete = 0;
2565 | textDelete = "";
2566 | textInsert = "";
2567 | break;
2568 | }
2569 | pointer++;
2570 | }
2571 | diffs.pop(); // Remove the dummy entry at the end.
2572 |
2573 | return diffs;
2574 | };
2575 |
2576 | /**
2577 | * Find the 'middle snake' of a diff, split the problem in two
2578 | * and return the recursively constructed diff.
2579 | * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
2580 | * @param {string} text1 Old string to be diffed.
2581 | * @param {string} text2 New string to be diffed.
2582 | * @param {number} deadline Time at which to bail if not yet complete.
2583 | * @return {!Array.} Array of diff tuples.
2584 | * @private
2585 | */
2586 | DiffMatchPatch.prototype.diffBisect = function( text1, text2, deadline ) {
2587 | var text1Length, text2Length, maxD, vOffset, vLength,
2588 | v1, v2, x, delta, front, k1start, k1end, k2start,
2589 | k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
2590 | // Cache the text lengths to prevent multiple calls.
2591 | text1Length = text1.length;
2592 | text2Length = text2.length;
2593 | maxD = Math.ceil( ( text1Length + text2Length ) / 2 );
2594 | vOffset = maxD;
2595 | vLength = 2 * maxD;
2596 | v1 = new Array( vLength );
2597 | v2 = new Array( vLength );
2598 | // Setting all elements to -1 is faster in Chrome & Firefox than mixing
2599 | // integers and undefined.
2600 | for ( x = 0; x < vLength; x++ ) {
2601 | v1[ x ] = -1;
2602 | v2[ x ] = -1;
2603 | }
2604 | v1[ vOffset + 1 ] = 0;
2605 | v2[ vOffset + 1 ] = 0;
2606 | delta = text1Length - text2Length;
2607 | // If the total number of characters is odd, then the front path will collide
2608 | // with the reverse path.
2609 | front = ( delta % 2 !== 0 );
2610 | // Offsets for start and end of k loop.
2611 | // Prevents mapping of space beyond the grid.
2612 | k1start = 0;
2613 | k1end = 0;
2614 | k2start = 0;
2615 | k2end = 0;
2616 | for ( d = 0; d < maxD; d++ ) {
2617 | // Bail out if deadline is reached.
2618 | if ( ( new Date() ).getTime() > deadline ) {
2619 | break;
2620 | }
2621 |
2622 | // Walk the front path one step.
2623 | for ( k1 = -d + k1start; k1 <= d - k1end; k1 += 2 ) {
2624 | k1Offset = vOffset + k1;
2625 | if ( k1 === -d || ( k1 !== d && v1[ k1Offset - 1 ] < v1[ k1Offset + 1 ] ) ) {
2626 | x1 = v1[ k1Offset + 1 ];
2627 | } else {
2628 | x1 = v1[ k1Offset - 1 ] + 1;
2629 | }
2630 | y1 = x1 - k1;
2631 | while ( x1 < text1Length && y1 < text2Length &&
2632 | text1.charAt( x1 ) === text2.charAt( y1 ) ) {
2633 | x1++;
2634 | y1++;
2635 | }
2636 | v1[ k1Offset ] = x1;
2637 | if ( x1 > text1Length ) {
2638 | // Ran off the right of the graph.
2639 | k1end += 2;
2640 | } else if ( y1 > text2Length ) {
2641 | // Ran off the bottom of the graph.
2642 | k1start += 2;
2643 | } else if ( front ) {
2644 | k2Offset = vOffset + delta - k1;
2645 | if ( k2Offset >= 0 && k2Offset < vLength && v2[ k2Offset ] !== -1 ) {
2646 | // Mirror x2 onto top-left coordinate system.
2647 | x2 = text1Length - v2[ k2Offset ];
2648 | if ( x1 >= x2 ) {
2649 | // Overlap detected.
2650 | return this.diffBisectSplit( text1, text2, x1, y1, deadline );
2651 | }
2652 | }
2653 | }
2654 | }
2655 |
2656 | // Walk the reverse path one step.
2657 | for ( k2 = -d + k2start; k2 <= d - k2end; k2 += 2 ) {
2658 | k2Offset = vOffset + k2;
2659 | if ( k2 === -d || ( k2 !== d && v2[ k2Offset - 1 ] < v2[ k2Offset + 1 ] ) ) {
2660 | x2 = v2[ k2Offset + 1 ];
2661 | } else {
2662 | x2 = v2[ k2Offset - 1 ] + 1;
2663 | }
2664 | y2 = x2 - k2;
2665 | while ( x2 < text1Length && y2 < text2Length &&
2666 | text1.charAt( text1Length - x2 - 1 ) ===
2667 | text2.charAt( text2Length - y2 - 1 ) ) {
2668 | x2++;
2669 | y2++;
2670 | }
2671 | v2[ k2Offset ] = x2;
2672 | if ( x2 > text1Length ) {
2673 | // Ran off the left of the graph.
2674 | k2end += 2;
2675 | } else if ( y2 > text2Length ) {
2676 | // Ran off the top of the graph.
2677 | k2start += 2;
2678 | } else if ( !front ) {
2679 | k1Offset = vOffset + delta - k2;
2680 | if ( k1Offset >= 0 && k1Offset < vLength && v1[ k1Offset ] !== -1 ) {
2681 | x1 = v1[ k1Offset ];
2682 | y1 = vOffset + x1 - k1Offset;
2683 | // Mirror x2 onto top-left coordinate system.
2684 | x2 = text1Length - x2;
2685 | if ( x1 >= x2 ) {
2686 | // Overlap detected.
2687 | return this.diffBisectSplit( text1, text2, x1, y1, deadline );
2688 | }
2689 | }
2690 | }
2691 | }
2692 | }
2693 | // Diff took too long and hit the deadline or
2694 | // number of diffs equals number of characters, no commonality at all.
2695 | return [
2696 | [ DIFF_DELETE, text1 ],
2697 | [ DIFF_INSERT, text2 ]
2698 | ];
2699 | };
2700 |
2701 | /**
2702 | * Given the location of the 'middle snake', split the diff in two parts
2703 | * and recurse.
2704 | * @param {string} text1 Old string to be diffed.
2705 | * @param {string} text2 New string to be diffed.
2706 | * @param {number} x Index of split point in text1.
2707 | * @param {number} y Index of split point in text2.
2708 | * @param {number} deadline Time at which to bail if not yet complete.
2709 | * @return {!Array.} Array of diff tuples.
2710 | * @private
2711 | */
2712 | DiffMatchPatch.prototype.diffBisectSplit = function( text1, text2, x, y, deadline ) {
2713 | var text1a, text1b, text2a, text2b, diffs, diffsb;
2714 | text1a = text1.substring( 0, x );
2715 | text2a = text2.substring( 0, y );
2716 | text1b = text1.substring( x );
2717 | text2b = text2.substring( y );
2718 |
2719 | // Compute both diffs serially.
2720 | diffs = this.DiffMain( text1a, text2a, false, deadline );
2721 | diffsb = this.DiffMain( text1b, text2b, false, deadline );
2722 |
2723 | return diffs.concat( diffsb );
2724 | };
2725 |
2726 | /**
2727 | * Reduce the number of edits by eliminating semantically trivial equalities.
2728 | * @param {!Array.} diffs Array of diff tuples.
2729 | */
2730 | DiffMatchPatch.prototype.diffCleanupSemantic = function( diffs ) {
2731 | var changes, equalities, equalitiesLength, lastequality,
2732 | pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1,
2733 | lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
2734 | changes = false;
2735 | equalities = []; // Stack of indices where equalities are found.
2736 | equalitiesLength = 0; // Keeping our own length var is faster in JS.
2737 | /** @type {?string} */
2738 | lastequality = null;
2739 | // Always equal to diffs[equalities[equalitiesLength - 1]][1]
2740 | pointer = 0; // Index of current position.
2741 | // Number of characters that changed prior to the equality.
2742 | lengthInsertions1 = 0;
2743 | lengthDeletions1 = 0;
2744 | // Number of characters that changed after the equality.
2745 | lengthInsertions2 = 0;
2746 | lengthDeletions2 = 0;
2747 | while ( pointer < diffs.length ) {
2748 | if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) { // Equality found.
2749 | equalities[ equalitiesLength++ ] = pointer;
2750 | lengthInsertions1 = lengthInsertions2;
2751 | lengthDeletions1 = lengthDeletions2;
2752 | lengthInsertions2 = 0;
2753 | lengthDeletions2 = 0;
2754 | lastequality = diffs[ pointer ][ 1 ];
2755 | } else { // An insertion or deletion.
2756 | if ( diffs[ pointer ][ 0 ] === DIFF_INSERT ) {
2757 | lengthInsertions2 += diffs[ pointer ][ 1 ].length;
2758 | } else {
2759 | lengthDeletions2 += diffs[ pointer ][ 1 ].length;
2760 | }
2761 | // Eliminate an equality that is smaller or equal to the edits on both
2762 | // sides of it.
2763 | if ( lastequality && ( lastequality.length <=
2764 | Math.max( lengthInsertions1, lengthDeletions1 ) ) &&
2765 | ( lastequality.length <= Math.max( lengthInsertions2,
2766 | lengthDeletions2 ) ) ) {
2767 |
2768 | // Duplicate record.
2769 | diffs.splice(
2770 | equalities[ equalitiesLength - 1 ],
2771 | 0,
2772 | [ DIFF_DELETE, lastequality ]
2773 | );
2774 |
2775 | // Change second copy to insert.
2776 | diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT;
2777 |
2778 | // Throw away the equality we just deleted.
2779 | equalitiesLength--;
2780 |
2781 | // Throw away the previous equality (it needs to be reevaluated).
2782 | equalitiesLength--;
2783 | pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1;
2784 |
2785 | // Reset the counters.
2786 | lengthInsertions1 = 0;
2787 | lengthDeletions1 = 0;
2788 | lengthInsertions2 = 0;
2789 | lengthDeletions2 = 0;
2790 | lastequality = null;
2791 | changes = true;
2792 | }
2793 | }
2794 | pointer++;
2795 | }
2796 |
2797 | // Normalize the diff.
2798 | if ( changes ) {
2799 | this.diffCleanupMerge( diffs );
2800 | }
2801 |
2802 | // Find any overlaps between deletions and insertions.
2803 | // e.g: abcxxxxxxdef
2804 | // -> abcxxxdef
2805 | // e.g: xxxabcdefxxx
2806 | // -> def xxxabc
2807 | // Only extract an overlap if it is as big as the edit ahead or behind it.
2808 | pointer = 1;
2809 | while ( pointer < diffs.length ) {
2810 | if ( diffs[ pointer - 1 ][ 0 ] === DIFF_DELETE &&
2811 | diffs[ pointer ][ 0 ] === DIFF_INSERT ) {
2812 | deletion = diffs[ pointer - 1 ][ 1 ];
2813 | insertion = diffs[ pointer ][ 1 ];
2814 | overlapLength1 = this.diffCommonOverlap( deletion, insertion );
2815 | overlapLength2 = this.diffCommonOverlap( insertion, deletion );
2816 | if ( overlapLength1 >= overlapLength2 ) {
2817 | if ( overlapLength1 >= deletion.length / 2 ||
2818 | overlapLength1 >= insertion.length / 2 ) {
2819 | // Overlap found. Insert an equality and trim the surrounding edits.
2820 | diffs.splice(
2821 | pointer,
2822 | 0,
2823 | [ DIFF_EQUAL, insertion.substring( 0, overlapLength1 ) ]
2824 | );
2825 | diffs[ pointer - 1 ][ 1 ] =
2826 | deletion.substring( 0, deletion.length - overlapLength1 );
2827 | diffs[ pointer + 1 ][ 1 ] = insertion.substring( overlapLength1 );
2828 | pointer++;
2829 | }
2830 | } else {
2831 | if ( overlapLength2 >= deletion.length / 2 ||
2832 | overlapLength2 >= insertion.length / 2 ) {
2833 |
2834 | // Reverse overlap found.
2835 | // Insert an equality and swap and trim the surrounding edits.
2836 | diffs.splice(
2837 | pointer,
2838 | 0,
2839 | [ DIFF_EQUAL, deletion.substring( 0, overlapLength2 ) ]
2840 | );
2841 |
2842 | diffs[ pointer - 1 ][ 0 ] = DIFF_INSERT;
2843 | diffs[ pointer - 1 ][ 1 ] =
2844 | insertion.substring( 0, insertion.length - overlapLength2 );
2845 | diffs[ pointer + 1 ][ 0 ] = DIFF_DELETE;
2846 | diffs[ pointer + 1 ][ 1 ] =
2847 | deletion.substring( overlapLength2 );
2848 | pointer++;
2849 | }
2850 | }
2851 | pointer++;
2852 | }
2853 | pointer++;
2854 | }
2855 | };
2856 |
2857 | /**
2858 | * Determine if the suffix of one string is the prefix of another.
2859 | * @param {string} text1 First string.
2860 | * @param {string} text2 Second string.
2861 | * @return {number} The number of characters common to the end of the first
2862 | * string and the start of the second string.
2863 | * @private
2864 | */
2865 | DiffMatchPatch.prototype.diffCommonOverlap = function( text1, text2 ) {
2866 | var text1Length, text2Length, textLength,
2867 | best, length, pattern, found;
2868 | // Cache the text lengths to prevent multiple calls.
2869 | text1Length = text1.length;
2870 | text2Length = text2.length;
2871 | // Eliminate the null case.
2872 | if ( text1Length === 0 || text2Length === 0 ) {
2873 | return 0;
2874 | }
2875 | // Truncate the longer string.
2876 | if ( text1Length > text2Length ) {
2877 | text1 = text1.substring( text1Length - text2Length );
2878 | } else if ( text1Length < text2Length ) {
2879 | text2 = text2.substring( 0, text1Length );
2880 | }
2881 | textLength = Math.min( text1Length, text2Length );
2882 | // Quick check for the worst case.
2883 | if ( text1 === text2 ) {
2884 | return textLength;
2885 | }
2886 |
2887 | // Start by looking for a single character match
2888 | // and increase length until no match is found.
2889 | // Performance analysis: http://neil.fraser.name/news/2010/11/04/
2890 | best = 0;
2891 | length = 1;
2892 | while ( true ) {
2893 | pattern = text1.substring( textLength - length );
2894 | found = text2.indexOf( pattern );
2895 | if ( found === -1 ) {
2896 | return best;
2897 | }
2898 | length += found;
2899 | if ( found === 0 || text1.substring( textLength - length ) ===
2900 | text2.substring( 0, length ) ) {
2901 | best = length;
2902 | length++;
2903 | }
2904 | }
2905 | };
2906 |
2907 | /**
2908 | * Split two texts into an array of strings. Reduce the texts to a string of
2909 | * hashes where each Unicode character represents one line.
2910 | * @param {string} text1 First string.
2911 | * @param {string} text2 Second string.
2912 | * @return {{chars1: string, chars2: string, lineArray: !Array.}}
2913 | * An object containing the encoded text1, the encoded text2 and
2914 | * the array of unique strings.
2915 | * The zeroth element of the array of unique strings is intentionally blank.
2916 | * @private
2917 | */
2918 | DiffMatchPatch.prototype.diffLinesToChars = function( text1, text2 ) {
2919 | var lineArray, lineHash, chars1, chars2;
2920 | lineArray = []; // e.g. lineArray[4] === 'Hello\n'
2921 | lineHash = {}; // e.g. lineHash['Hello\n'] === 4
2922 |
2923 | // '\x00' is a valid character, but various debuggers don't like it.
2924 | // So we'll insert a junk entry to avoid generating a null character.
2925 | lineArray[ 0 ] = "";
2926 |
2927 | /**
2928 | * Split a text into an array of strings. Reduce the texts to a string of
2929 | * hashes where each Unicode character represents one line.
2930 | * Modifies linearray and linehash through being a closure.
2931 | * @param {string} text String to encode.
2932 | * @return {string} Encoded string.
2933 | * @private
2934 | */
2935 | function diffLinesToCharsMunge( text ) {
2936 | var chars, lineStart, lineEnd, lineArrayLength, line;
2937 | chars = "";
2938 | // Walk the text, pulling out a substring for each line.
2939 | // text.split('\n') would would temporarily double our memory footprint.
2940 | // Modifying text would create many large strings to garbage collect.
2941 | lineStart = 0;
2942 | lineEnd = -1;
2943 | // Keeping our own length variable is faster than looking it up.
2944 | lineArrayLength = lineArray.length;
2945 | while ( lineEnd < text.length - 1 ) {
2946 | lineEnd = text.indexOf( "\n", lineStart );
2947 | if ( lineEnd === -1 ) {
2948 | lineEnd = text.length - 1;
2949 | }
2950 | line = text.substring( lineStart, lineEnd + 1 );
2951 | lineStart = lineEnd + 1;
2952 |
2953 | if ( lineHash.hasOwnProperty ? lineHash.hasOwnProperty( line ) :
2954 | ( lineHash[ line ] !== undefined ) ) {
2955 | chars += String.fromCharCode( lineHash[ line ] );
2956 | } else {
2957 | chars += String.fromCharCode( lineArrayLength );
2958 | lineHash[ line ] = lineArrayLength;
2959 | lineArray[ lineArrayLength++ ] = line;
2960 | }
2961 | }
2962 | return chars;
2963 | }
2964 |
2965 | chars1 = diffLinesToCharsMunge( text1 );
2966 | chars2 = diffLinesToCharsMunge( text2 );
2967 | return {
2968 | chars1: chars1,
2969 | chars2: chars2,
2970 | lineArray: lineArray
2971 | };
2972 | };
2973 |
2974 | /**
2975 | * Rehydrate the text in a diff from a string of line hashes to real lines of
2976 | * text.
2977 | * @param {!Array.} diffs Array of diff tuples.
2978 | * @param {!Array.} lineArray Array of unique strings.
2979 | * @private
2980 | */
2981 | DiffMatchPatch.prototype.diffCharsToLines = function( diffs, lineArray ) {
2982 | var x, chars, text, y;
2983 | for ( x = 0; x < diffs.length; x++ ) {
2984 | chars = diffs[ x ][ 1 ];
2985 | text = [];
2986 | for ( y = 0; y < chars.length; y++ ) {
2987 | text[ y ] = lineArray[ chars.charCodeAt( y ) ];
2988 | }
2989 | diffs[ x ][ 1 ] = text.join( "" );
2990 | }
2991 | };
2992 |
2993 | /**
2994 | * Reorder and merge like edit sections. Merge equalities.
2995 | * Any edit section can move as long as it doesn't cross an equality.
2996 | * @param {!Array.} diffs Array of diff tuples.
2997 | */
2998 | DiffMatchPatch.prototype.diffCleanupMerge = function( diffs ) {
2999 | var pointer, countDelete, countInsert, textInsert, textDelete,
3000 | commonlength, changes, diffPointer, position;
3001 | diffs.push( [ DIFF_EQUAL, "" ] ); // Add a dummy entry at the end.
3002 | pointer = 0;
3003 | countDelete = 0;
3004 | countInsert = 0;
3005 | textDelete = "";
3006 | textInsert = "";
3007 | commonlength;
3008 | while ( pointer < diffs.length ) {
3009 | switch ( diffs[ pointer ][ 0 ] ) {
3010 | case DIFF_INSERT:
3011 | countInsert++;
3012 | textInsert += diffs[ pointer ][ 1 ];
3013 | pointer++;
3014 | break;
3015 | case DIFF_DELETE:
3016 | countDelete++;
3017 | textDelete += diffs[ pointer ][ 1 ];
3018 | pointer++;
3019 | break;
3020 | case DIFF_EQUAL:
3021 | // Upon reaching an equality, check for prior redundancies.
3022 | if ( countDelete + countInsert > 1 ) {
3023 | if ( countDelete !== 0 && countInsert !== 0 ) {
3024 | // Factor out any common prefixies.
3025 | commonlength = this.diffCommonPrefix( textInsert, textDelete );
3026 | if ( commonlength !== 0 ) {
3027 | if ( ( pointer - countDelete - countInsert ) > 0 &&
3028 | diffs[ pointer - countDelete - countInsert - 1 ][ 0 ] ===
3029 | DIFF_EQUAL ) {
3030 | diffs[ pointer - countDelete - countInsert - 1 ][ 1 ] +=
3031 | textInsert.substring( 0, commonlength );
3032 | } else {
3033 | diffs.splice( 0, 0, [ DIFF_EQUAL,
3034 | textInsert.substring( 0, commonlength )
3035 | ] );
3036 | pointer++;
3037 | }
3038 | textInsert = textInsert.substring( commonlength );
3039 | textDelete = textDelete.substring( commonlength );
3040 | }
3041 | // Factor out any common suffixies.
3042 | commonlength = this.diffCommonSuffix( textInsert, textDelete );
3043 | if ( commonlength !== 0 ) {
3044 | diffs[ pointer ][ 1 ] = textInsert.substring( textInsert.length -
3045 | commonlength ) + diffs[ pointer ][ 1 ];
3046 | textInsert = textInsert.substring( 0, textInsert.length -
3047 | commonlength );
3048 | textDelete = textDelete.substring( 0, textDelete.length -
3049 | commonlength );
3050 | }
3051 | }
3052 | // Delete the offending records and add the merged ones.
3053 | if ( countDelete === 0 ) {
3054 | diffs.splice( pointer - countInsert,
3055 | countDelete + countInsert, [ DIFF_INSERT, textInsert ] );
3056 | } else if ( countInsert === 0 ) {
3057 | diffs.splice( pointer - countDelete,
3058 | countDelete + countInsert, [ DIFF_DELETE, textDelete ] );
3059 | } else {
3060 | diffs.splice(
3061 | pointer - countDelete - countInsert,
3062 | countDelete + countInsert,
3063 | [ DIFF_DELETE, textDelete ], [ DIFF_INSERT, textInsert ]
3064 | );
3065 | }
3066 | pointer = pointer - countDelete - countInsert +
3067 | ( countDelete ? 1 : 0 ) + ( countInsert ? 1 : 0 ) + 1;
3068 | } else if ( pointer !== 0 && diffs[ pointer - 1 ][ 0 ] === DIFF_EQUAL ) {
3069 |
3070 | // Merge this equality with the previous one.
3071 | diffs[ pointer - 1 ][ 1 ] += diffs[ pointer ][ 1 ];
3072 | diffs.splice( pointer, 1 );
3073 | } else {
3074 | pointer++;
3075 | }
3076 | countInsert = 0;
3077 | countDelete = 0;
3078 | textDelete = "";
3079 | textInsert = "";
3080 | break;
3081 | }
3082 | }
3083 | if ( diffs[ diffs.length - 1 ][ 1 ] === "" ) {
3084 | diffs.pop(); // Remove the dummy entry at the end.
3085 | }
3086 |
3087 | // Second pass: look for single edits surrounded on both sides by equalities
3088 | // which can be shifted sideways to eliminate an equality.
3089 | // e.g: ABA C -> AB AC
3090 | changes = false;
3091 | pointer = 1;
3092 |
3093 | // Intentionally ignore the first and last element (don't need checking).
3094 | while ( pointer < diffs.length - 1 ) {
3095 | if ( diffs[ pointer - 1 ][ 0 ] === DIFF_EQUAL &&
3096 | diffs[ pointer + 1 ][ 0 ] === DIFF_EQUAL ) {
3097 |
3098 | diffPointer = diffs[ pointer ][ 1 ];
3099 | position = diffPointer.substring(
3100 | diffPointer.length - diffs[ pointer - 1 ][ 1 ].length
3101 | );
3102 |
3103 | // This is a single edit surrounded by equalities.
3104 | if ( position === diffs[ pointer - 1 ][ 1 ] ) {
3105 |
3106 | // Shift the edit over the previous equality.
3107 | diffs[ pointer ][ 1 ] = diffs[ pointer - 1 ][ 1 ] +
3108 | diffs[ pointer ][ 1 ].substring( 0, diffs[ pointer ][ 1 ].length -
3109 | diffs[ pointer - 1 ][ 1 ].length );
3110 | diffs[ pointer + 1 ][ 1 ] =
3111 | diffs[ pointer - 1 ][ 1 ] + diffs[ pointer + 1 ][ 1 ];
3112 | diffs.splice( pointer - 1, 1 );
3113 | changes = true;
3114 | } else if ( diffPointer.substring( 0, diffs[ pointer + 1 ][ 1 ].length ) ===
3115 | diffs[ pointer + 1 ][ 1 ] ) {
3116 |
3117 | // Shift the edit over the next equality.
3118 | diffs[ pointer - 1 ][ 1 ] += diffs[ pointer + 1 ][ 1 ];
3119 | diffs[ pointer ][ 1 ] =
3120 | diffs[ pointer ][ 1 ].substring( diffs[ pointer + 1 ][ 1 ].length ) +
3121 | diffs[ pointer + 1 ][ 1 ];
3122 | diffs.splice( pointer + 1, 1 );
3123 | changes = true;
3124 | }
3125 | }
3126 | pointer++;
3127 | }
3128 | // If shifts were made, the diff needs reordering and another shift sweep.
3129 | if ( changes ) {
3130 | this.diffCleanupMerge( diffs );
3131 | }
3132 | };
3133 |
3134 | return function( o, n ) {
3135 | var diff, output, text;
3136 | diff = new DiffMatchPatch();
3137 | output = diff.DiffMain( o, n );
3138 | diff.diffCleanupEfficiency( output );
3139 | text = diff.diffPrettyHtml( output );
3140 |
3141 | return text;
3142 | };
3143 | }() );
3144 |
3145 | // Get a reference to the global object, like window in browsers
3146 | }( (function() {
3147 | return this;
3148 | })() ));
3149 |
3150 | (function() {
3151 |
3152 | // Don't load the HTML Reporter on non-Browser environments
3153 | if ( typeof window === "undefined" || !window.document ) {
3154 | return;
3155 | }
3156 |
3157 | // Deprecated QUnit.init - Ref #530
3158 | // Re-initialize the configuration options
3159 | QUnit.init = function() {
3160 | var tests, banner, result, qunit,
3161 | config = QUnit.config;
3162 |
3163 | config.stats = { all: 0, bad: 0 };
3164 | config.moduleStats = { all: 0, bad: 0 };
3165 | config.started = 0;
3166 | config.updateRate = 1000;
3167 | config.blocking = false;
3168 | config.autostart = true;
3169 | config.autorun = false;
3170 | config.filter = "";
3171 | config.queue = [];
3172 |
3173 | // Return on non-browser environments
3174 | // This is necessary to not break on node tests
3175 | if ( typeof window === "undefined" ) {
3176 | return;
3177 | }
3178 |
3179 | qunit = id( "qunit" );
3180 | if ( qunit ) {
3181 | qunit.innerHTML =
3182 | "" +
3183 | " " +
3184 | "
" +
3185 | " " +
3186 | " ";
3187 | }
3188 |
3189 | tests = id( "qunit-tests" );
3190 | banner = id( "qunit-banner" );
3191 | result = id( "qunit-testresult" );
3192 |
3193 | if ( tests ) {
3194 | tests.innerHTML = "";
3195 | }
3196 |
3197 | if ( banner ) {
3198 | banner.className = "";
3199 | }
3200 |
3201 | if ( result ) {
3202 | result.parentNode.removeChild( result );
3203 | }
3204 |
3205 | if ( tests ) {
3206 | result = document.createElement( "p" );
3207 | result.id = "qunit-testresult";
3208 | result.className = "result";
3209 | tests.parentNode.insertBefore( result, tests );
3210 | result.innerHTML = "Running... ";
3211 | }
3212 | };
3213 |
3214 | var config = QUnit.config,
3215 | hasOwn = Object.prototype.hasOwnProperty,
3216 | defined = {
3217 | document: window.document !== undefined,
3218 | sessionStorage: (function() {
3219 | var x = "qunit-test-string";
3220 | try {
3221 | sessionStorage.setItem( x, x );
3222 | sessionStorage.removeItem( x );
3223 | return true;
3224 | } catch ( e ) {
3225 | return false;
3226 | }
3227 | }())
3228 | },
3229 | modulesList = [];
3230 |
3231 | /**
3232 | * Escape text for attribute or text content.
3233 | */
3234 | function escapeText( s ) {
3235 | if ( !s ) {
3236 | return "";
3237 | }
3238 | s = s + "";
3239 |
3240 | // Both single quotes and double quotes (for attributes)
3241 | return s.replace( /['"<>&]/g, function( s ) {
3242 | switch ( s ) {
3243 | case "'":
3244 | return "'";
3245 | case "\"":
3246 | return """;
3247 | case "<":
3248 | return "<";
3249 | case ">":
3250 | return ">";
3251 | case "&":
3252 | return "&";
3253 | }
3254 | });
3255 | }
3256 |
3257 | /**
3258 | * @param {HTMLElement} elem
3259 | * @param {string} type
3260 | * @param {Function} fn
3261 | */
3262 | function addEvent( elem, type, fn ) {
3263 | if ( elem.addEventListener ) {
3264 |
3265 | // Standards-based browsers
3266 | elem.addEventListener( type, fn, false );
3267 | } else if ( elem.attachEvent ) {
3268 |
3269 | // support: IE <9
3270 | elem.attachEvent( "on" + type, function() {
3271 | var event = window.event;
3272 | if ( !event.target ) {
3273 | event.target = event.srcElement || document;
3274 | }
3275 |
3276 | fn.call( elem, event );
3277 | });
3278 | }
3279 | }
3280 |
3281 | /**
3282 | * @param {Array|NodeList} elems
3283 | * @param {string} type
3284 | * @param {Function} fn
3285 | */
3286 | function addEvents( elems, type, fn ) {
3287 | var i = elems.length;
3288 | while ( i-- ) {
3289 | addEvent( elems[ i ], type, fn );
3290 | }
3291 | }
3292 |
3293 | function hasClass( elem, name ) {
3294 | return ( " " + elem.className + " " ).indexOf( " " + name + " " ) >= 0;
3295 | }
3296 |
3297 | function addClass( elem, name ) {
3298 | if ( !hasClass( elem, name ) ) {
3299 | elem.className += ( elem.className ? " " : "" ) + name;
3300 | }
3301 | }
3302 |
3303 | function toggleClass( elem, name ) {
3304 | if ( hasClass( elem, name ) ) {
3305 | removeClass( elem, name );
3306 | } else {
3307 | addClass( elem, name );
3308 | }
3309 | }
3310 |
3311 | function removeClass( elem, name ) {
3312 | var set = " " + elem.className + " ";
3313 |
3314 | // Class name may appear multiple times
3315 | while ( set.indexOf( " " + name + " " ) >= 0 ) {
3316 | set = set.replace( " " + name + " ", " " );
3317 | }
3318 |
3319 | // trim for prettiness
3320 | elem.className = typeof set.trim === "function" ? set.trim() : set.replace( /^\s+|\s+$/g, "" );
3321 | }
3322 |
3323 | function id( name ) {
3324 | return defined.document && document.getElementById && document.getElementById( name );
3325 | }
3326 |
3327 | function getUrlConfigHtml() {
3328 | var i, j, val,
3329 | escaped, escapedTooltip,
3330 | selection = false,
3331 | len = config.urlConfig.length,
3332 | urlConfigHtml = "";
3333 |
3334 | for ( i = 0; i < len; i++ ) {
3335 | val = config.urlConfig[ i ];
3336 | if ( typeof val === "string" ) {
3337 | val = {
3338 | id: val,
3339 | label: val
3340 | };
3341 | }
3342 |
3343 | escaped = escapeText( val.id );
3344 | escapedTooltip = escapeText( val.tooltip );
3345 |
3346 | if ( config[ val.id ] === undefined ) {
3347 | config[ val.id ] = QUnit.urlParams[ val.id ];
3348 | }
3349 |
3350 | if ( !val.value || typeof val.value === "string" ) {
3351 | urlConfigHtml += "" + val.label + " ";
3357 | } else {
3358 | urlConfigHtml += "" + val.label +
3360 | ": ";
3362 |
3363 | if ( QUnit.is( "array", val.value ) ) {
3364 | for ( j = 0; j < val.value.length; j++ ) {
3365 | escaped = escapeText( val.value[ j ] );
3366 | urlConfigHtml += "" + escaped + " ";
3370 | }
3371 | } else {
3372 | for ( j in val.value ) {
3373 | if ( hasOwn.call( val.value, j ) ) {
3374 | urlConfigHtml += "" + escapeText( val.value[ j ] ) + " ";
3378 | }
3379 | }
3380 | }
3381 | if ( config[ val.id ] && !selection ) {
3382 | escaped = escapeText( config[ val.id ] );
3383 | urlConfigHtml += "" + escaped + " ";
3385 | }
3386 | urlConfigHtml += " ";
3387 | }
3388 | }
3389 |
3390 | return urlConfigHtml;
3391 | }
3392 |
3393 | // Handle "click" events on toolbar checkboxes and "change" for select menus.
3394 | // Updates the URL with the new state of `config.urlConfig` values.
3395 | function toolbarChanged() {
3396 | var updatedUrl, value,
3397 | field = this,
3398 | params = {};
3399 |
3400 | // Detect if field is a select menu or a checkbox
3401 | if ( "selectedIndex" in field ) {
3402 | value = field.options[ field.selectedIndex ].value || undefined;
3403 | } else {
3404 | value = field.checked ? ( field.defaultValue || true ) : undefined;
3405 | }
3406 |
3407 | params[ field.name ] = value;
3408 | updatedUrl = setUrl( params );
3409 |
3410 | if ( "hidepassed" === field.name && "replaceState" in window.history ) {
3411 | config[ field.name ] = value || false;
3412 | if ( value ) {
3413 | addClass( id( "qunit-tests" ), "hidepass" );
3414 | } else {
3415 | removeClass( id( "qunit-tests" ), "hidepass" );
3416 | }
3417 |
3418 | // It is not necessary to refresh the whole page
3419 | window.history.replaceState( null, "", updatedUrl );
3420 | } else {
3421 | window.location = updatedUrl;
3422 | }
3423 | }
3424 |
3425 | function setUrl( params ) {
3426 | var key,
3427 | querystring = "?";
3428 |
3429 | params = QUnit.extend( QUnit.extend( {}, QUnit.urlParams ), params );
3430 |
3431 | for ( key in params ) {
3432 | if ( hasOwn.call( params, key ) ) {
3433 | if ( params[ key ] === undefined ) {
3434 | continue;
3435 | }
3436 | querystring += encodeURIComponent( key );
3437 | if ( params[ key ] !== true ) {
3438 | querystring += "=" + encodeURIComponent( params[ key ] );
3439 | }
3440 | querystring += "&";
3441 | }
3442 | }
3443 | return location.protocol + "//" + location.host +
3444 | location.pathname + querystring.slice( 0, -1 );
3445 | }
3446 |
3447 | function applyUrlParams() {
3448 | var selectedModule,
3449 | modulesList = id( "qunit-modulefilter" ),
3450 | filter = id( "qunit-filter-input" ).value;
3451 |
3452 | selectedModule = modulesList ?
3453 | decodeURIComponent( modulesList.options[ modulesList.selectedIndex ].value ) :
3454 | undefined;
3455 |
3456 | window.location = setUrl({
3457 | module: ( selectedModule === "" ) ? undefined : selectedModule,
3458 | filter: ( filter === "" ) ? undefined : filter,
3459 |
3460 | // Remove testId filter
3461 | testId: undefined
3462 | });
3463 | }
3464 |
3465 | function toolbarUrlConfigContainer() {
3466 | var urlConfigContainer = document.createElement( "span" );
3467 |
3468 | urlConfigContainer.innerHTML = getUrlConfigHtml();
3469 | addClass( urlConfigContainer, "qunit-url-config" );
3470 |
3471 | // For oldIE support:
3472 | // * Add handlers to the individual elements instead of the container
3473 | // * Use "click" instead of "change" for checkboxes
3474 | addEvents( urlConfigContainer.getElementsByTagName( "input" ), "click", toolbarChanged );
3475 | addEvents( urlConfigContainer.getElementsByTagName( "select" ), "change", toolbarChanged );
3476 |
3477 | return urlConfigContainer;
3478 | }
3479 |
3480 | function toolbarLooseFilter() {
3481 | var filter = document.createElement( "form" ),
3482 | label = document.createElement( "label" ),
3483 | input = document.createElement( "input" ),
3484 | button = document.createElement( "button" );
3485 |
3486 | addClass( filter, "qunit-filter" );
3487 |
3488 | label.innerHTML = "Filter: ";
3489 |
3490 | input.type = "text";
3491 | input.value = config.filter || "";
3492 | input.name = "filter";
3493 | input.id = "qunit-filter-input";
3494 |
3495 | button.innerHTML = "Go";
3496 |
3497 | label.appendChild( input );
3498 |
3499 | filter.appendChild( label );
3500 | filter.appendChild( button );
3501 | addEvent( filter, "submit", function( ev ) {
3502 | applyUrlParams();
3503 |
3504 | if ( ev && ev.preventDefault ) {
3505 | ev.preventDefault();
3506 | }
3507 |
3508 | return false;
3509 | });
3510 |
3511 | return filter;
3512 | }
3513 |
3514 | function toolbarModuleFilterHtml() {
3515 | var i,
3516 | moduleFilterHtml = "";
3517 |
3518 | if ( !modulesList.length ) {
3519 | return false;
3520 | }
3521 |
3522 | modulesList.sort(function( a, b ) {
3523 | return a.localeCompare( b );
3524 | });
3525 |
3526 | moduleFilterHtml += "Module: " +
3527 | "< All Modules > ";
3530 |
3531 | for ( i = 0; i < modulesList.length; i++ ) {
3532 | moduleFilterHtml += "" + escapeText( modulesList[ i ] ) + " ";
3536 | }
3537 | moduleFilterHtml += " ";
3538 |
3539 | return moduleFilterHtml;
3540 | }
3541 |
3542 | function toolbarModuleFilter() {
3543 | var toolbar = id( "qunit-testrunner-toolbar" ),
3544 | moduleFilter = document.createElement( "span" ),
3545 | moduleFilterHtml = toolbarModuleFilterHtml();
3546 |
3547 | if ( !toolbar || !moduleFilterHtml ) {
3548 | return false;
3549 | }
3550 |
3551 | moduleFilter.setAttribute( "id", "qunit-modulefilter-container" );
3552 | moduleFilter.innerHTML = moduleFilterHtml;
3553 |
3554 | addEvent( moduleFilter.lastChild, "change", applyUrlParams );
3555 |
3556 | toolbar.appendChild( moduleFilter );
3557 | }
3558 |
3559 | function appendToolbar() {
3560 | var toolbar = id( "qunit-testrunner-toolbar" );
3561 |
3562 | if ( toolbar ) {
3563 | toolbar.appendChild( toolbarUrlConfigContainer() );
3564 | toolbar.appendChild( toolbarLooseFilter() );
3565 | }
3566 | }
3567 |
3568 | function appendHeader() {
3569 | var header = id( "qunit-header" );
3570 |
3571 | if ( header ) {
3572 | header.innerHTML = "" + header.innerHTML + " ";
3575 | }
3576 | }
3577 |
3578 | function appendBanner() {
3579 | var banner = id( "qunit-banner" );
3580 |
3581 | if ( banner ) {
3582 | banner.className = "";
3583 | }
3584 | }
3585 |
3586 | function appendTestResults() {
3587 | var tests = id( "qunit-tests" ),
3588 | result = id( "qunit-testresult" );
3589 |
3590 | if ( result ) {
3591 | result.parentNode.removeChild( result );
3592 | }
3593 |
3594 | if ( tests ) {
3595 | tests.innerHTML = "";
3596 | result = document.createElement( "p" );
3597 | result.id = "qunit-testresult";
3598 | result.className = "result";
3599 | tests.parentNode.insertBefore( result, tests );
3600 | result.innerHTML = "Running... ";
3601 | }
3602 | }
3603 |
3604 | function storeFixture() {
3605 | var fixture = id( "qunit-fixture" );
3606 | if ( fixture ) {
3607 | config.fixture = fixture.innerHTML;
3608 | }
3609 | }
3610 |
3611 | function appendUserAgent() {
3612 | var userAgent = id( "qunit-userAgent" );
3613 |
3614 | if ( userAgent ) {
3615 | userAgent.innerHTML = "";
3616 | userAgent.appendChild(
3617 | document.createTextNode(
3618 | "QUnit " + QUnit.version + "; " + navigator.userAgent
3619 | )
3620 | );
3621 | }
3622 | }
3623 |
3624 | function appendTestsList( modules ) {
3625 | var i, l, x, z, test, moduleObj;
3626 |
3627 | for ( i = 0, l = modules.length; i < l; i++ ) {
3628 | moduleObj = modules[ i ];
3629 |
3630 | if ( moduleObj.name ) {
3631 | modulesList.push( moduleObj.name );
3632 | }
3633 |
3634 | for ( x = 0, z = moduleObj.tests.length; x < z; x++ ) {
3635 | test = moduleObj.tests[ x ];
3636 |
3637 | appendTest( test.name, test.testId, moduleObj.name );
3638 | }
3639 | }
3640 | }
3641 |
3642 | function appendTest( name, testId, moduleName ) {
3643 | var title, rerunTrigger, testBlock, assertList,
3644 | tests = id( "qunit-tests" );
3645 |
3646 | if ( !tests ) {
3647 | return;
3648 | }
3649 |
3650 | title = document.createElement( "strong" );
3651 | title.innerHTML = getNameHtml( name, moduleName );
3652 |
3653 | rerunTrigger = document.createElement( "a" );
3654 | rerunTrigger.innerHTML = "Rerun";
3655 | rerunTrigger.href = setUrl({ testId: testId });
3656 |
3657 | testBlock = document.createElement( "li" );
3658 | testBlock.appendChild( title );
3659 | testBlock.appendChild( rerunTrigger );
3660 | testBlock.id = "qunit-test-output-" + testId;
3661 |
3662 | assertList = document.createElement( "ol" );
3663 | assertList.className = "qunit-assert-list";
3664 |
3665 | testBlock.appendChild( assertList );
3666 |
3667 | tests.appendChild( testBlock );
3668 | }
3669 |
3670 | // HTML Reporter initialization and load
3671 | QUnit.begin(function( details ) {
3672 | var qunit = id( "qunit" );
3673 |
3674 | // Fixture is the only one necessary to run without the #qunit element
3675 | storeFixture();
3676 |
3677 | if ( qunit ) {
3678 | qunit.innerHTML =
3679 | "" +
3680 | " " +
3681 | "
" +
3682 | " " +
3683 | " ";
3684 | }
3685 |
3686 | appendHeader();
3687 | appendBanner();
3688 | appendTestResults();
3689 | appendUserAgent();
3690 | appendToolbar();
3691 | appendTestsList( details.modules );
3692 | toolbarModuleFilter();
3693 |
3694 | if ( qunit && config.hidepassed ) {
3695 | addClass( qunit.lastChild, "hidepass" );
3696 | }
3697 | });
3698 |
3699 | QUnit.done(function( details ) {
3700 | var i, key,
3701 | banner = id( "qunit-banner" ),
3702 | tests = id( "qunit-tests" ),
3703 | html = [
3704 | "Tests completed in ",
3705 | details.runtime,
3706 | " milliseconds. ",
3707 | "",
3708 | details.passed,
3709 | " assertions of ",
3710 | details.total,
3711 | " passed, ",
3712 | details.failed,
3713 | " failed."
3714 | ].join( "" );
3715 |
3716 | if ( banner ) {
3717 | banner.className = details.failed ? "qunit-fail" : "qunit-pass";
3718 | }
3719 |
3720 | if ( tests ) {
3721 | id( "qunit-testresult" ).innerHTML = html;
3722 | }
3723 |
3724 | if ( config.altertitle && defined.document && document.title ) {
3725 |
3726 | // show ✖ for good, ✔ for bad suite result in title
3727 | // use escape sequences in case file gets loaded with non-utf-8-charset
3728 | document.title = [
3729 | ( details.failed ? "\u2716" : "\u2714" ),
3730 | document.title.replace( /^[\u2714\u2716] /i, "" )
3731 | ].join( " " );
3732 | }
3733 |
3734 | // clear own sessionStorage items if all tests passed
3735 | if ( config.reorder && defined.sessionStorage && details.failed === 0 ) {
3736 | for ( i = 0; i < sessionStorage.length; i++ ) {
3737 | key = sessionStorage.key( i++ );
3738 | if ( key.indexOf( "qunit-test-" ) === 0 ) {
3739 | sessionStorage.removeItem( key );
3740 | }
3741 | }
3742 | }
3743 |
3744 | // scroll back to top to show results
3745 | if ( config.scrolltop && window.scrollTo ) {
3746 | window.scrollTo( 0, 0 );
3747 | }
3748 | });
3749 |
3750 | function getNameHtml( name, module ) {
3751 | var nameHtml = "";
3752 |
3753 | if ( module ) {
3754 | nameHtml = "" + escapeText( module ) + " : ";
3755 | }
3756 |
3757 | nameHtml += "" + escapeText( name ) + " ";
3758 |
3759 | return nameHtml;
3760 | }
3761 |
3762 | QUnit.testStart(function( details ) {
3763 | var running, testBlock, bad;
3764 |
3765 | testBlock = id( "qunit-test-output-" + details.testId );
3766 | if ( testBlock ) {
3767 | testBlock.className = "running";
3768 | } else {
3769 |
3770 | // Report later registered tests
3771 | appendTest( details.name, details.testId, details.module );
3772 | }
3773 |
3774 | running = id( "qunit-testresult" );
3775 | if ( running ) {
3776 | bad = QUnit.config.reorder && defined.sessionStorage &&
3777 | +sessionStorage.getItem( "qunit-test-" + details.module + "-" + details.name );
3778 |
3779 | running.innerHTML = ( bad ?
3780 | "Rerunning previously failed test: " :
3781 | "Running: " ) +
3782 | getNameHtml( details.name, details.module );
3783 | }
3784 |
3785 | });
3786 |
3787 | function stripHtml( string ) {
3788 | // strip tags, html entity and whitespaces
3789 | return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\"/g, "").replace(/\s+/g, "");
3790 | }
3791 |
3792 | QUnit.log(function( details ) {
3793 | var assertList, assertLi,
3794 | message, expected, actual, diff,
3795 | showDiff = false,
3796 | testItem = id( "qunit-test-output-" + details.testId );
3797 |
3798 | if ( !testItem ) {
3799 | return;
3800 | }
3801 |
3802 | message = escapeText( details.message ) || ( details.result ? "okay" : "failed" );
3803 | message = "" + message + " ";
3804 | message += "@ " + details.runtime + " ms ";
3805 |
3806 | // pushFailure doesn't provide details.expected
3807 | // when it calls, it's implicit to also not show expected and diff stuff
3808 | // Also, we need to check details.expected existence, as it can exist and be undefined
3809 | if ( !details.result && hasOwn.call( details, "expected" ) ) {
3810 | if ( details.negative ) {
3811 | expected = escapeText( "NOT " + QUnit.dump.parse( details.expected ) );
3812 | } else {
3813 | expected = escapeText( QUnit.dump.parse( details.expected ) );
3814 | }
3815 |
3816 | actual = escapeText( QUnit.dump.parse( details.actual ) );
3817 | message += "Expected: " +
3818 | expected +
3819 | " ";
3820 |
3821 | if ( actual !== expected ) {
3822 |
3823 | message += "Result: " +
3824 | actual + " ";
3825 |
3826 | // Don't show diff if actual or expected are booleans
3827 | if ( !( /^(true|false)$/.test( actual ) ) &&
3828 | !( /^(true|false)$/.test( expected ) ) ) {
3829 | diff = QUnit.diff( expected, actual );
3830 | showDiff = stripHtml( diff ).length !==
3831 | stripHtml( expected ).length +
3832 | stripHtml( actual ).length;
3833 | }
3834 |
3835 | // Don't show diff if expected and actual are totally different
3836 | if ( showDiff ) {
3837 | message += "Diff: " +
3838 | diff + " ";
3839 | }
3840 | } else if ( expected.indexOf( "[object Array]" ) !== -1 ||
3841 | expected.indexOf( "[object Object]" ) !== -1 ) {
3842 | message += "Message: " +
3843 | "Diff suppressed as the depth of object is more than current max depth (" +
3844 | QUnit.config.maxDepth + ").Hint: Use QUnit.dump.maxDepth
to " +
3845 | " run with a higher max depth or " +
3846 | "Rerun without max depth.
";
3847 | }
3848 |
3849 | if ( details.source ) {
3850 | message += "Source: " +
3851 | escapeText( details.source ) + " ";
3852 | }
3853 |
3854 | message += "
";
3855 |
3856 | // this occours when pushFailure is set and we have an extracted stack trace
3857 | } else if ( !details.result && details.source ) {
3858 | message += "" +
3859 | "Source: " +
3860 | escapeText( details.source ) + " " +
3861 | "
";
3862 | }
3863 |
3864 | assertList = testItem.getElementsByTagName( "ol" )[ 0 ];
3865 |
3866 | assertLi = document.createElement( "li" );
3867 | assertLi.className = details.result ? "pass" : "fail";
3868 | assertLi.innerHTML = message;
3869 | assertList.appendChild( assertLi );
3870 | });
3871 |
3872 | QUnit.testDone(function( details ) {
3873 | var testTitle, time, testItem, assertList,
3874 | good, bad, testCounts, skipped, sourceName,
3875 | tests = id( "qunit-tests" );
3876 |
3877 | if ( !tests ) {
3878 | return;
3879 | }
3880 |
3881 | testItem = id( "qunit-test-output-" + details.testId );
3882 |
3883 | assertList = testItem.getElementsByTagName( "ol" )[ 0 ];
3884 |
3885 | good = details.passed;
3886 | bad = details.failed;
3887 |
3888 | // store result when possible
3889 | if ( config.reorder && defined.sessionStorage ) {
3890 | if ( bad ) {
3891 | sessionStorage.setItem( "qunit-test-" + details.module + "-" + details.name, bad );
3892 | } else {
3893 | sessionStorage.removeItem( "qunit-test-" + details.module + "-" + details.name );
3894 | }
3895 | }
3896 |
3897 | if ( bad === 0 ) {
3898 | addClass( assertList, "qunit-collapsed" );
3899 | }
3900 |
3901 | // testItem.firstChild is the test name
3902 | testTitle = testItem.firstChild;
3903 |
3904 | testCounts = bad ?
3905 | "" + bad + " , " + "" + good + " , " :
3906 | "";
3907 |
3908 | testTitle.innerHTML += " (" + testCounts +
3909 | details.assertions.length + ") ";
3910 |
3911 | if ( details.skipped ) {
3912 | testItem.className = "skipped";
3913 | skipped = document.createElement( "em" );
3914 | skipped.className = "qunit-skipped-label";
3915 | skipped.innerHTML = "skipped";
3916 | testItem.insertBefore( skipped, testTitle );
3917 | } else {
3918 | addEvent( testTitle, "click", function() {
3919 | toggleClass( assertList, "qunit-collapsed" );
3920 | });
3921 |
3922 | testItem.className = bad ? "fail" : "pass";
3923 |
3924 | time = document.createElement( "span" );
3925 | time.className = "runtime";
3926 | time.innerHTML = details.runtime + " ms";
3927 | testItem.insertBefore( time, assertList );
3928 | }
3929 |
3930 | // Show the source of the test when showing assertions
3931 | if ( details.source ) {
3932 | sourceName = document.createElement( "p" );
3933 | sourceName.innerHTML = "Source: " + details.source;
3934 | addClass( sourceName, "qunit-source" );
3935 | if ( bad === 0 ) {
3936 | addClass( sourceName, "qunit-collapsed" );
3937 | }
3938 | addEvent( testTitle, "click", function() {
3939 | toggleClass( sourceName, "qunit-collapsed" );
3940 | });
3941 | testItem.appendChild( sourceName );
3942 | }
3943 | });
3944 |
3945 | if ( defined.document ) {
3946 |
3947 | // Avoid readyState issue with phantomjs
3948 | // Ref: #818
3949 | var notPhantom = ( function( p ) {
3950 | return !( p && p.version && p.version.major > 0 );
3951 | } )( window.phantom );
3952 |
3953 | if ( notPhantom && document.readyState === "complete" ) {
3954 | QUnit.load();
3955 | } else {
3956 | addEvent( window, "load", QUnit.load );
3957 | }
3958 | } else {
3959 | config.pageLoaded = true;
3960 | config.autorun = true;
3961 | }
3962 |
3963 | })();
3964 |
--------------------------------------------------------------------------------
/src/test/test-enumjs.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | enumjs Test Suite
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/test/test-enumjs.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Tests for enum.js
3 | * Created on 9/20/15
4 | */
5 |
6 | test('Test define throws an error if name is not provided or is invalid.', function () {
7 | throws(function () {
8 | Enum.define();
9 | }, TypeError, "define must thrown an error if name is not provided.");
10 |
11 | throws(function () {
12 | Enum.define("");
13 | }, TypeError, "define must throw an error if name is empty.");
14 |
15 | throws(function () {
16 | Enum.define(" ");
17 | }, TypeError, "define must throw an error if name is blank.");
18 |
19 | throws(function () {
20 | Enum.define("9abc^");
21 | }, TypeError, "define must throw an error if name is invalid.");
22 | });
23 |
24 | test('Test define throws an error if constants is not provided or is invalid.', function () {
25 | throws(function () {
26 | Enum.define("Test");
27 | }, TypeError, "define must throw an error if constants is not provided.");
28 |
29 | throws(function () {
30 | Enum.define("Test", "");
31 | }, TypeError, "define must throw an error if constants is not an array or object.");
32 |
33 | throws(function () {
34 | Enum.define("Test", []);
35 | }, TypeError, "define must throw an error if constants is an empty array.");
36 |
37 | throws(function () {
38 | Enum.define("Test", ["ONE", 4]);
39 | }, TypeError, "define must throw an error if not all constants are strings.");
40 |
41 | throws(function () {
42 | Enum.define("Test", {});
43 | }, TypeError, "define must throw an error if constants is an empty object.");
44 |
45 | throws(function () {
46 | Enum.define("Test", {
47 | something: 10
48 | });
49 | }, TypeError, "define must throw an error constants attribute is not provided.");
50 |
51 | throws(function () {
52 | Enum.define("Test", {
53 | constants: {}
54 | });
55 | }, TypeError, "define must throw an error if constants attribute is empty.");
56 |
57 | throws(function () {
58 | Enum.define("Test", {
59 | constants: {
60 | ZERO: {
61 | attr: 10
62 | },
63 | ONE: 10
64 | }
65 | });
66 | }, TypeError, "define must throw an error if one or more constants have non-object values.");
67 |
68 | throws(function () {
69 | Enum.define("Test", {
70 | constants: {
71 | ZERO: {}
72 | },
73 | methods: {
74 | one: function () { },
75 | two: "notfunction"
76 | }
77 | });
78 | }, TypeError, "define must throw an error if one or more values in methods attribute is not a function.");
79 | });
80 |
81 | test('Test define defines enums and constants properly, and all behavior is consistent (using array of constants).', function () {
82 | var Numbers = Enum.define("Numbers", ["ONE", "TWO", "THREE"]);
83 |
84 | ok(Numbers.ONE instanceof Numbers, "ONE must be an instance of Numbers.");
85 | ok(Numbers.TWO instanceof Numbers, "TWO must be an instance of Numbers.");
86 | ok(Numbers.THREE instanceof Numbers, "THREE must be an instance of Numbers.");
87 |
88 | ok(Numbers.ONE.name() === "ONE", "name() of ONE must be \"ONE\".");
89 | ok(Numbers.TWO.name() === "TWO", "name() of TWO must be \"TWO\".");
90 | ok(Numbers.THREE.name() === "THREE", "name() of THREE must be \"THREE\".");
91 |
92 | ok(Numbers.ONE.ordinal() === 0, "ordinal() of ONE must be 0.");
93 | ok(Numbers.TWO.ordinal() === 1, "ordinal() of TWO must be 1.");
94 | ok(Numbers.THREE.ordinal() === 2, "ordinal() of THREE must be 2.");
95 |
96 | ok(Numbers.ONE.toString() === "ONE", "toString() of ONE must be \"ONE\".");
97 | ok(Numbers.TWO.toString() === "TWO", "toString() of TWO must be \"TWO\".");
98 | ok(Numbers.THREE.toString() === "THREE", "toString() of THREE must be \"THREE\".");
99 |
100 | ok(Numbers.ONE.valueOf() === "ONE", "valueOf() of ONE must be \"ONE\".");
101 | ok(Numbers.TWO.valueOf() === "TWO", "valueOf() of TWO must be \"TWO\".");
102 | ok(Numbers.THREE.valueOf() === "THREE", "valueOf() of THREE must be \"THREE\".");
103 |
104 | ok(Numbers.fromName("ONE") === Numbers.ONE, "Enum from name \"ONE\" must be the same as Numbers.ONE.");
105 | ok(Numbers.fromName("TWO") === Numbers.TWO, "Enum from name \"TWO\" must be the same as Numbers.TWO.");
106 | ok(Numbers.fromName("THREE") === Numbers.THREE, "Enum from name \"THREE\" must be the same as Numbers.THREE.");
107 |
108 | throws(function() {
109 | Numbers.fromName("FOUR");
110 | }, TypeError, "Numbers.fromName(\"FOUR\") must throw an error.");
111 |
112 | ok(typeof Numbers.values === "function", "Numbers must have a values function.");
113 | ok(Numbers.values().length === 3, "Numbers must return an array of three constants.");
114 | ok(Numbers.values().reduce(function (isInstance, constant) {
115 | return isInstance && constant instanceof Numbers;
116 | }, true), "Every constant in array returned by values() must be an instance of Numbers.");
117 |
118 | ok(Numbers.values().reduce(function (hasValues, constant) {
119 | return hasValues && (typeof constant.values === "function");
120 | }, true), "Every constant must have the values() method.");
121 | ok(Numbers.values().reduce(function (hasValues, constant) {
122 | return hasValues && constant.values === Numbers.values;
123 | }, true), "Every constant must have a values() that delegates to Numbers.values()");
124 | ok(Numbers.values().reduce(function (hasFromName, constant) {
125 | return hasFromName && (typeof constant.fromName === "function");
126 | }, true), "Every constant must have the fromName() method.");
127 | ok(Numbers.values().reduce(function (hasFromName, constant) {
128 | return hasFromName && constant.fromName === Numbers.fromName;
129 | }, true), "Every constant must have a fromName() that delegates to Numbers.fromName()");
130 |
131 | ok(Numbers.toString() === "Numbers { ONE, TWO, THREE }", "Numbers.toString() must match.");
132 | });
133 |
134 | test('Test define defines enums and constants properly, and all behavior is consistent (using object definition).', function() {
135 | var Numbers = Enum.define("Numbers", {
136 | constants: {
137 | ONE: {
138 | value: 1,
139 | toBinary: function() {
140 | return "0001";
141 | }
142 | },
143 | TWO: {
144 | value: 2,
145 | toBinary: function() {
146 | return "0010";
147 | }
148 | },
149 | THREE: {
150 | value: 3,
151 | toBinary: function() {
152 | return "0011";
153 | }
154 | }
155 | },
156 | methods: {
157 | add: function (number) {
158 | if(number instanceof Numbers) {
159 | return this.value + number.value;
160 | }
161 |
162 | return Number.NaN;
163 | },
164 | sub: function (number) {
165 | if(number instanceof Numbers) {
166 | return this.value - number.value;
167 | }
168 |
169 | return Number.NaN;
170 | },
171 | mul: function (number) {
172 | if(number instanceof Numbers) {
173 | return this.value * number.value;
174 | }
175 |
176 | return Number.NaN;
177 | },
178 | div: function (number) {
179 | if(number instanceof Numbers) {
180 | return this.value / number.value;
181 | }
182 |
183 | return Number.NaN;
184 | }
185 | }
186 | });
187 |
188 | ok(Numbers.ONE instanceof Numbers, "ONE must be an instance of Numbers.");
189 | ok(Numbers.TWO instanceof Numbers, "TWO must be an instance of Numbers.");
190 | ok(Numbers.THREE instanceof Numbers, "THREE must be an instance of Numbers.");
191 |
192 | ok(Numbers.ONE.name() === "ONE", "name() of ONE must be \"ONE\".");
193 | ok(Numbers.TWO.name() === "TWO", "name() of TWO must be \"TWO\".");
194 | ok(Numbers.THREE.name() === "THREE", "name() of THREE must be \"THREE\".");
195 |
196 | ok(Numbers.ONE.ordinal() === 0, "ordinal() of ONE must be 0.");
197 | ok(Numbers.TWO.ordinal() === 1, "ordinal() of TWO must be 1.");
198 | ok(Numbers.THREE.ordinal() === 2, "ordinal() of THREE must be 2.");
199 |
200 | ok(Numbers.ONE.toString() === "ONE", "toString() of ONE must be \"ONE\".");
201 | ok(Numbers.TWO.toString() === "TWO", "toString() of TWO must be \"TWO\".");
202 | ok(Numbers.THREE.toString() === "THREE", "toString() of THREE must be \"THREE\".");
203 |
204 | ok(Numbers.ONE.valueOf() === "ONE", "valueOf() of ONE must be \"ONE\".");
205 | ok(Numbers.TWO.valueOf() === "TWO", "valueOf() of TWO must be \"TWO\".");
206 | ok(Numbers.THREE.valueOf() === "THREE", "valueOf() of THREE must be \"THREE\".");
207 |
208 | ok(Numbers.fromName("ONE") === Numbers.ONE, "Enum from name \"ONE\" must be the same as Numbers.ONE.");
209 | ok(Numbers.fromName("TWO") === Numbers.TWO, "Enum from name \"TWO\" must be the same as Numbers.TWO.");
210 | ok(Numbers.fromName("THREE") === Numbers.THREE, "Enum from name \"THREE\" must be the same as Numbers.THREE.");
211 |
212 | throws(function() {
213 | Numbers.fromName("FOUR");
214 | }, TypeError, "Numbers.fromName(\"FOUR\") must throw an error.");
215 |
216 | ok(Numbers.ONE.value === 1, "value of ONE must be 1.");
217 | ok(Numbers.TWO.value === 2, "value of TWO must be 2.");
218 | ok(Numbers.THREE.value === 3, "value of THREE must be 3.");
219 |
220 | ok(typeof Numbers.values === "function", "Numbers must have a values function.");
221 | ok(Numbers.values().length === 3, "Numbers must return an array of three constants.");
222 | ok(Numbers.values().reduce(function (isInstance, constant) {
223 | return isInstance && constant instanceof Numbers;
224 | }, true), "Every constant in array returned by values() must be an instance of Numbers.");
225 |
226 | ok(Numbers.values().reduce(function (hasValues, constant) {
227 | return hasValues && (typeof constant.values === "function");
228 | }, true), "Every constant must have the values() method.");
229 | ok(Numbers.values().reduce(function (hasValues, constant) {
230 | return hasValues && constant.values === Numbers.values;
231 | }, true), "Every constant must have a values() that delegates to Numbers.values().");
232 | ok(Numbers.values().reduce(function (hasFromName, constant) {
233 | return hasFromName && (typeof constant.fromName === "function");
234 | }, true), "Every constant must have the fromName() method.");
235 | ok(Numbers.values().reduce(function (hasFromName, constant) {
236 | return hasFromName && constant.fromName === Numbers.fromName;
237 | }, true), "Every constant must have a fromName() that delegates to Numbers.fromName().");
238 |
239 | ok(Numbers.values().reduce(function (hasMethods, constant) {
240 | return hasMethods &&
241 | typeof constant.add === "function" &&
242 | typeof constant.sub === "function" &&
243 | typeof constant.mul === "function" &&
244 | typeof constant.div === "function" &&
245 | typeof constant.toBinary === "function";
246 | }, true), "Every constant must have all methods provided in the definition.");
247 |
248 | ok(Numbers.TWO.add(Numbers.TWO) === 4, "TWO.add(TWO) must be 4.");
249 | ok(Numbers.THREE.sub(Numbers.ONE) === 2, "THREE.sub(ONE) must be 2.");
250 | ok(Numbers.TWO.mul(Numbers.THREE) === 6, "TWO.mul(THREE) must be 6.");
251 | ok(Numbers.THREE.div(Numbers.ONE) === 3, "THREE.div(ONE) must be 3.");
252 | ok(isNaN(Numbers.ONE.add(5)), "ONE.add(5) must be NaN.");
253 |
254 | ok(Numbers.ONE.toBinary() === "0001", "ONE.toBinary() must be 0001.");
255 | ok(Numbers.TWO.toBinary() === "0010", "TWO.toBinary() must be 0010.");
256 | ok(Numbers.THREE.toBinary() === "0011", "THREE.toBinary() must be 0011.");
257 | });
258 |
259 | test('Test JSON.stringify on an enum constant returns a string representation of the constant.', function () {
260 | var Test = Enum.define("Test", ["One"]);
261 | ok(JSON.stringify(Test.One) === "\"One\"", "JSON.stringify(Test.One) should return \"One\".");
262 | });
263 |
--------------------------------------------------------------------------------