Permalink
Browse files

Bibliotheken aktualisiert und Upgrade auf Requirejs2.0

  • Loading branch information...
1 parent ad4c571 commit 67b64e9969cf205623e546adfe72c8d84367b394 Tobias Bosch committed Jul 7, 2012
View
4 html5build.xml
@@ -41,8 +41,8 @@
<java classpathref="classpathId" classname="org.mozilla.javascript.tools.shell.Main">
<arg line="${basedir}/misc/requirejs/r.js -o"/>
<arg line="baseUrl=src/main/webapp name=lib/almond"/>
- <arg line="include=main.js out=${outputDir}/main.js"/>
- <arg line="optimize=none"/>
+ <arg line="include=main mainConfigFile=src/main/webapp/main.js"/>
+ <arg line="out=${outputDir}/main.js waitSeconds=60 optimize=none"/>
</java>
</target>
View
2 jstd-server.sh
@@ -1,2 +1,2 @@
#!/bin/sh
-java -jar misc/JsTestDriver-1.3.2.jar --port 9876 --runnerMode INFO
+java -jar misc/JsTestDriver.jar --port 9876 --runnerMode INFO
View
2 jstd-ui.sh
@@ -1,2 +1,2 @@
#!/bin/sh
-java -jar misc/JsTestDriver-1.3.2.jar --config jstd-ui.conf --reset --tests all --testOutput target/jstd-reports
+java -jar misc/JsTestDriver.jar --config jstd-ui.conf --reset --tests all --testOutput target/jstd-reports
View
2 jstd-unit.sh
@@ -1,2 +1,2 @@
#!/bin/sh
-java -jar misc/JsTestDriver-1.3.2.jar --config jstd-unit.conf --reset --tests all --testOutput target/jstd-reports
+java -jar misc/JsTestDriver.jar --config jstd-unit.conf --reset --tests all --testOutput target/jstd-reports
View
BIN misc/JsTestDriver.jar
Binary file not shown.
View
1 misc/JsTestDriver.version.txt
@@ -0,0 +1 @@
+1.3.4.b
View
1 misc/install.sh
@@ -0,0 +1 @@
+mvn install:install-file -Dfile=JsTestDriver.jar -DgroupId=com.google.jstestdriver -DartifactId=jstestdriver -Dversion=1.3.4.b -Dpackaging=jar
View
9,725 misc/requirejs/r.js
7,687 additions, 2,038 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
5 pom.xml
@@ -65,9 +65,6 @@
<property name="classpath" value="${classpath}"/>
<property name="minify" value="${html5.minify}"/>
</ant>
- <zip destfile="${basedir}/target/html5.zip"
- basedir="${basedir}/target/html5"/>
- <attachartifact file="${basedir}/target/html5.zip" classifier="html5" type="zip"/>
</target>
</configuration>
<goals>
@@ -103,7 +100,7 @@
<dependency>
<groupId>com.google.jstestdriver</groupId>
<artifactId>jstestdriver</artifactId>
- <version>1.3.2</version>
+ <version>1.3.4.b</version>
<scope>test</scope>
</dependency>
<dependency>
View
2 src/main/webapp/app/application.js
@@ -1,4 +1,4 @@
-define(function () {
+define(['angular'], function (angular) {
angular.module("rylc", ["rylc-controllers", "rylc-markup", "rylc-services"]);
View
2 src/main/webapp/app/backendService.js
@@ -1,4 +1,4 @@
-define(function () {
+define(['lib/Base64'], function (Base64) {
function backendServiceFactory($http, $q, $waitDialog) {
var defaultErrorCodeMessageMapping = {
401:'Zugriff verweigert.',
View
4 src/main/webapp/app/controllers.js
@@ -1,5 +1,5 @@
-define(['app/AuthenticationController', 'app/RentalHistoryController', 'app/RentalController'],
- function (AuthenticationController, RentalHistoryController, RentalController) {
+define(['angular', 'app/AuthenticationController', 'app/RentalHistoryController', 'app/RentalController'],
+ function (angular, AuthenticationController, RentalHistoryController, RentalController) {
var module = angular.module("rylc-controllers", ["rylc-services"]);
module.controller("rylc.AuthenticationController", AuthenticationController);
View
2 src/main/webapp/app/markup.js
@@ -1,4 +1,4 @@
-define(function () {
+define(['angular'], function (angular) {
function simpleDateFilterFactory(utilsService) {
return utilsService.formatSimpleDate;
View
4 src/main/webapp/app/services.js
@@ -1,5 +1,5 @@
-define(["app/utilsService", "app/backendService", "app/rentalService"],
- function (utilsServiceFactory, backendServiceFactory, rentalServiceFactory) {
+define(["angular", "app/utilsService", "app/backendService", "app/rentalService"],
+ function (angular, utilsServiceFactory, backendServiceFactory, rentalServiceFactory) {
function configureHttp($httpProvider) {
$httpProvider.defaults.headers.post = {'Content-Type':'application/json'};
View
131 src/main/webapp/lib/almond.js
@@ -1,25 +1,22 @@
/**
- * almond 0.0.3 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
+ * almond 0.1.1 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/almond for details
*/
-/*jslint strict: false, plusplus: false */
+//Going sloppy to avoid 'use strict' string cost, but strict practices should
+//be followed.
+/*jslint sloppy: true */
/*global setTimeout: false */
var requirejs, require, define;
(function (undef) {
-
var defined = {},
waiting = {},
+ config = {},
+ defining = {},
aps = [].slice,
main, req;
- if (typeof define === "function") {
- //If a define is already in play via another AMD loader,
- //do not overwrite.
- return;
- }
-
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
@@ -29,6 +26,11 @@ var requirejs, require, define;
* @returns {String} normalized name
*/
function normalize(name, baseName) {
+ var baseParts = baseName && baseName.split("/"),
+ map = config.map,
+ starMap = (map && map['*']) || {},
+ nameParts, nameSegment, mapValue, foundMap, i, j, part;
+
//Adjust any relative paths.
if (name && name.charAt(0) === ".") {
//If have a base name, try to normalize against it,
@@ -40,13 +42,11 @@ var requirejs, require, define;
//module. For instance, baseName of "one/two/three", maps to
//"one/two/three.js", but we want the directory, "one/two" for
//this normalization.
- baseName = baseName.split("/");
- baseName = baseName.slice(0, baseName.length - 1);
+ baseParts = baseParts.slice(0, baseParts.length - 1);
- name = baseName.concat(name.split("/"));
+ name = baseParts.concat(name.split("/"));
//start trimDots
- var i, part;
for (i = 0; (part = name[i]); i++) {
if (part === ".") {
name.splice(i, 1);
@@ -59,7 +59,7 @@ var requirejs, require, define;
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
- break;
+ return true;
} else if (i > 0) {
name.splice(i - 1, 2);
i -= 2;
@@ -71,6 +71,43 @@ var requirejs, require, define;
name = name.join("/");
}
}
+
+ //Apply map config if available.
+ if ((baseParts || starMap) && map) {
+ nameParts = name.split('/');
+
+ for (i = nameParts.length; i > 0; i -= 1) {
+ nameSegment = nameParts.slice(0, i).join("/");
+
+ if (baseParts) {
+ //Find the longest baseName segment match in the config.
+ //So, do joins on the biggest to smallest lengths of baseParts.
+ for (j = baseParts.length; j > 0; j -= 1) {
+ mapValue = map[baseParts.slice(0, j).join('/')];
+
+ //baseName segment has config, find if it has one for
+ //this name.
+ if (mapValue) {
+ mapValue = mapValue[nameSegment];
+ if (mapValue) {
+ //Match, update name to the new value.
+ foundMap = mapValue;
+ break;
+ }
+ }
+ }
+ }
+
+ foundMap = foundMap || starMap[nameSegment];
+
+ if (foundMap) {
+ nameParts.splice(0, i, foundMap);
+ name = nameParts.join('/');
+ break;
+ }
+ }
+ }
+
return name;
}
@@ -99,8 +136,13 @@ var requirejs, require, define;
if (waiting.hasOwnProperty(name)) {
var args = waiting[name];
delete waiting[name];
+ defining[name] = true;
main.apply(undef, args);
}
+
+ if (!defined.hasOwnProperty(name)) {
+ throw new Error('No ' + name);
+ }
return defined[name];
}
@@ -136,27 +178,27 @@ var requirejs, require, define;
};
}
+ function makeConfig(name) {
+ return function () {
+ return (config && config.config && config.config[name]) || {};
+ };
+ }
+
main = function (name, deps, callback, relName) {
var args = [],
usingExports,
- cjsModule, depName, i, ret, map;
+ cjsModule, depName, ret, map, i;
//Use name if no relName
- if (!relName) {
- relName = name;
- }
+ relName = relName || name;
//Call the callback to define the module, if necessary.
if (typeof callback === 'function') {
- //Default to require, exports, module if no deps if
- //the factory arg has any arguments specified.
- if (!deps.length && callback.length) {
- deps = ['require', 'exports', 'module'];
- }
-
//Pull out the defined dependencies and pass the ordered
//values to the callback.
+ //Default to [require, exports, module] if no deps
+ deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
for (i = 0; i < deps.length; i++) {
map = makeMap(deps[i], relName);
depName = map.f;
@@ -173,15 +215,16 @@ var requirejs, require, define;
cjsModule = args[i] = {
id: name,
uri: '',
- exports: defined[name]
+ exports: defined[name],
+ config: makeConfig(name)
};
} else if (defined.hasOwnProperty(depName) || waiting.hasOwnProperty(depName)) {
args[i] = callDep(depName);
} else if (map.p) {
map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
args[i] = defined[depName];
- } else {
- throw name + ' missing ' + depName;
+ } else if (!defining[depName]) {
+ throw new Error(name + ' missing ' + depName);
}
}
@@ -191,9 +234,10 @@ var requirejs, require, define;
//If setting exports via "module" is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
- if (cjsModule && cjsModule.exports !== undef) {
+ if (cjsModule && cjsModule.exports !== undef &&
+ cjsModule.exports !== defined[name]) {
defined[name] = cjsModule.exports;
- } else if (!usingExports) {
+ } else if (ret !== undef || !usingExports) {
//Use the return value from the function.
defined[name] = ret;
}
@@ -205,27 +249,30 @@ var requirejs, require, define;
}
};
- requirejs = req = function (deps, callback, relName, forceSync) {
+ requirejs = require = req = function (deps, callback, relName, forceSync) {
if (typeof deps === "string") {
-
//Just return the module wanted. In this scenario, the
//deps arg is the module name, and second arg (if passed)
//is just the relName.
//Normalize module name, if it contains . or ..
return callDep(makeMap(deps, callback).f);
} else if (!deps.splice) {
//deps is a config object, not an array.
- //Drop the config stuff on the ground.
+ config = deps;
if (callback.splice) {
//callback is an array, which means it is a dependency list.
//Adjust args if there are dependencies
deps = callback;
- callback = arguments[2];
+ callback = relName;
+ relName = null;
} else {
- deps = [];
+ deps = undef;
}
}
+ //Support require(['a'])
+ callback = callback || function () {};
+
//Simulate async callback;
if (forceSync) {
main(undef, deps, callback, relName);
@@ -242,17 +289,11 @@ var requirejs, require, define;
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
- req.config = function () {
+ req.config = function (cfg) {
+ config = cfg;
return req;
};
- /**
- * Export require as a global, but only if it does not already exist.
- */
- if (!require) {
- require = req;
- }
-
define = function (name, deps, callback) {
//This module may not have dependencies
@@ -264,11 +305,7 @@ var requirejs, require, define;
deps = [];
}
- if (define.unordered) {
- waiting[name] = [name, deps, callback];
- } else {
- main(name, deps, callback);
- }
+ waiting[name] = [name, deps, callback];
};
define.amd = {
View
26,568 src/main/webapp/lib/angular.js
13,467 additions, 13,101 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
15 src/main/webapp/lib/jqmExternalAsEmbeddedPages.js
@@ -2,15 +2,20 @@
* Patch for jquery mobile to transparently lookup non existing embedded pages
* as external pages with the suffix .html.
*/
-(function ($) {
+define(["jquery", "jquery.mobile"], function($) {
$.mobile.originalLoadPage = $.mobile.loadPage;
$.mobile.loadPage = function (url, options) {
var match = url.match(/#(\w+)/);
- var pageId = match && match[1];
- if (pageId && !document.getElementById(pageId)) {
- url = pageId+".html";
+ if (match) {
+ var pageId = match[1];
+ var page = document.getElementById(pageId);
+ if (!page || $(page).is(":jqmData(external-page='true')")) {
+ url = pageId + ".html";
+ }
}
return $.mobile.originalLoadPage(url, options);
};
-})(window.jQuery);
+});
+
+
View
3,437 src/main/webapp/lib/jquery-mobile-angular-adapter.js
1,866 additions, 1,571 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
18,085 src/main/webapp/lib/jquery.js
9,045 additions, 9,040 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
2 src/main/webapp/lib/jquery.mobile.js
@@ -3577,7 +3577,7 @@ $.mobile.transitionFallbacks = {};
//if there's a data-rel=back attr, go back in history
if( $link.is( ":jqmData(rel='back')" ) ) {
- window.history.back();
+ window.history.back();
return false;
}
View
189 src/main/webapp/lib/order.js
@@ -1,189 +0,0 @@
-/**
- * @license RequireJS order 1.0.5 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-/*jslint nomen: false, plusplus: false, strict: false */
-/*global require: false, define: false, window: false, document: false,
- setTimeout: false */
-
-//Specify that requirejs optimizer should wrap this code in a closure that
-//maps the namespaced requirejs API to non-namespaced local variables.
-/*requirejs namespace: true */
-
-(function () {
-
- //Sadly necessary browser inference due to differences in the way
- //that browsers load and execute dynamically inserted javascript
- //and whether the script/cache method works when ordered execution is
- //desired. Currently, Gecko and Opera do not load/fire onload for scripts with
- //type="script/cache" but they execute injected scripts in order
- //unless the 'async' flag is present.
- //However, this is all changing in latest browsers implementing HTML5
- //spec. With compliant browsers .async true by default, and
- //if false, then it will execute in order. Favor that test first for forward
- //compatibility.
- var testScript = typeof document !== "undefined" &&
- typeof window !== "undefined" &&
- document.createElement("script"),
-
- supportsInOrderExecution = testScript && (testScript.async ||
- ((window.opera &&
- Object.prototype.toString.call(window.opera) === "[object Opera]") ||
- //If Firefox 2 does not have to be supported, then
- //a better check may be:
- //('mozIsLocallyAvailable' in window.navigator)
- ("MozAppearance" in document.documentElement.style))),
-
- //This test is true for IE browsers, which will load scripts but only
- //execute them once the script is added to the DOM.
- supportsLoadSeparateFromExecute = testScript &&
- testScript.readyState === 'uninitialized',
-
- readyRegExp = /^(complete|loaded)$/,
- cacheWaiting = [],
- cached = {},
- scriptNodes = {},
- scriptWaiting = [];
-
- //Done with the test script.
- testScript = null;
-
- //Callback used by the type="script/cache" callback that indicates a script
- //has finished downloading.
- function scriptCacheCallback(evt) {
- var node = evt.currentTarget || evt.srcElement, i,
- moduleName, resource;
-
- if (evt.type === "load" || readyRegExp.test(node.readyState)) {
- //Pull out the name of the module and the context.
- moduleName = node.getAttribute("data-requiremodule");
-
- //Mark this cache request as loaded
- cached[moduleName] = true;
-
- //Find out how many ordered modules have loaded
- for (i = 0; (resource = cacheWaiting[i]); i++) {
- if (cached[resource.name]) {
- resource.req([resource.name], resource.onLoad);
- } else {
- //Something in the ordered list is not loaded,
- //so wait.
- break;
- }
- }
-
- //If just loaded some items, remove them from cacheWaiting.
- if (i > 0) {
- cacheWaiting.splice(0, i);
- }
-
- //Remove this script tag from the DOM
- //Use a setTimeout for cleanup because some older IE versions vomit
- //if removing a script node while it is being evaluated.
- setTimeout(function () {
- node.parentNode.removeChild(node);
- }, 15);
- }
- }
-
- /**
- * Used for the IE case, where fetching is done by creating script element
- * but not attaching it to the DOM. This function will be called when that
- * happens so it can be determined when the node can be attached to the
- * DOM to trigger its execution.
- */
- function onFetchOnly(node) {
- var i, loadedNode, resourceName;
-
- //Mark this script as loaded.
- node.setAttribute('data-orderloaded', 'loaded');
-
- //Cycle through waiting scripts. If the matching node for them
- //is loaded, and is in the right order, add it to the DOM
- //to execute the script.
- for (i = 0; (resourceName = scriptWaiting[i]); i++) {
- loadedNode = scriptNodes[resourceName];
- if (loadedNode &&
- loadedNode.getAttribute('data-orderloaded') === 'loaded') {
- delete scriptNodes[resourceName];
- require.addScriptToDom(loadedNode);
- } else {
- break;
- }
- }
-
- //If just loaded some items, remove them from waiting.
- if (i > 0) {
- scriptWaiting.splice(0, i);
- }
- }
-
- define({
- version: '1.0.5',
-
- load: function (name, req, onLoad, config) {
- var hasToUrl = !!req.nameToUrl,
- url, node, context;
-
- //If no nameToUrl, then probably a build with a loader that
- //does not support it, and all modules are inlined.
- if (!hasToUrl) {
- req([name], onLoad);
- return;
- }
-
- url = req.nameToUrl(name, null);
-
- //Make sure the async attribute is not set for any pathway involving
- //this script.
- require.s.skipAsync[url] = true;
- if (supportsInOrderExecution || config.isBuild) {
- //Just a normal script tag append, but without async attribute
- //on the script.
- req([name], onLoad);
- } else if (supportsLoadSeparateFromExecute) {
- //Just fetch the URL, but do not execute it yet. The
- //non-standards IE case. Really not so nice because it is
- //assuming and touching requrejs internals. OK though since
- //ordered execution should go away after a long while.
- context = require.s.contexts._;
-
- if (!context.urlFetched[url] && !context.loaded[name]) {
- //Indicate the script is being fetched.
- context.urlFetched[url] = true;
-
- //Stuff from require.load
- require.resourcesReady(false);
- context.scriptCount += 1;
-
- //Fetch the script now, remember it.
- node = require.attach(url, context, name, null, null, onFetchOnly);
- scriptNodes[name] = node;
- scriptWaiting.push(name);
- }
-
- //Do a normal require for it, once it loads, use it as return
- //value.
- req([name], onLoad);
- } else {
- //Credit to LABjs author Kyle Simpson for finding that scripts
- //with type="script/cache" allow scripts to be downloaded into
- //browser cache but not executed. Use that
- //so that subsequent addition of a real type="text/javascript"
- //tag will cause the scripts to be executed immediately in the
- //correct order.
- if (req.specified(name)) {
- req([name], onLoad);
- } else {
- cacheWaiting.push({
- name: name,
- req: req,
- onLoad: onLoad
- });
- require.attach(url, null, name, scriptCacheCallback, "script/cache");
- }
- }
- }
- });
-}());
View
2,782 src/main/webapp/lib/require.js
1,383 additions, 1,399 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
48 src/main/webapp/main.js
@@ -1,16 +1,36 @@
-define([
- // Patches
- "lib/order!lib/JSONParseDate.js",
+require.config({
+ paths:{
+ 'jquery':'lib/jquery',
+ 'angular':'lib/angular',
+ 'jquery.mobile':'lib/jquery.mobile'
+ },
+ shim:{
+ 'lib/Base64':{exports:'Base64'},
+ 'angular':{ deps:['jquery'],exports:'angular' }
+ }
+});
+
+function tryHoldReady() {
+ if (!tryHoldReady.executed && window.jQuery) {
+ window.jQuery.holdReady(true);
+ tryHoldReady.executed = true;
+ }
+}
+tryHoldReady();
+require.onResourceLoad = tryHoldReady;
+
+require([
+ "jquery",
// Libraries
- "lib/order!lib/Base64.js",
- "lib/order!lib/jquery.js",
- "lib/order!lib/jquery.mobile.js",
- "lib/order!lib/jqmExternalAsEmbeddedPages.js",
- "lib/order!lib/angular.js",
- "lib/order!lib/jquery-mobile-angular-adapter.js",
+ "lib/jqmExternalAsEmbeddedPages",
+ "lib/JSONParseDate",
+ "lib/jquery-mobile-angular-adapter",
// Application
- "lib/order!app/services",
- "lib/order!app/controllers",
- "lib/order!app/markup",
- "lib/order!app/application"
-]);
+ "app/services",
+ "app/controllers",
+ "app/markup",
+ "app/application"
+], function (jquery) {
+ jquery.holdReady(false);
+});
+
View
57 src/test/webapp/UnitSpecRunner.html
@@ -10,27 +10,62 @@
</head>
<body>
<script>
- require(["main"], function () {
+ require.config({
+ paths:{
+ 'jquery':'lib/jquery',
+ 'angular':'lib/angular',
+ 'jquery.mobile':'lib/jquery.mobile'
+ },
+ shim:{
+ // Libraries
+ 'lib/Base64':{exports:'Base64'},
+ 'angular':{
+ deps:['jquery'],
+ exports:'angular'
+ },
+ // Test Libraries
+ "lib/jasmine":{exports:"jasmine"},
+ "lib/jasmine-html":["lib/jasmine"],
+ "lib/angular-mocks":["angular", "lib/jasmine"],
+ // Tests
+ "unit/JSONParseDateSpec":["lib/angular-mocks"],
+ "unit/jqmExternalAsEmbeddedPagesSpec":["lib/angular-mocks"],
+ "unit/AuthenticationControllerSpec":["lib/angular-mocks"],
+ "unit/utilsServiceSpec.js":["lib/angular-mocks"],
+ "unit/backendServiceSpec.js":["lib/angular-mocks"],
+ "unit/rentalServiceSpec.js":["lib/angular-mocks"],
+ }
+ });
+
require([
// Test Libraries
- "lib/order!lib/jasmine",
- "lib/order!lib/jasmine-html",
- "lib/order!lib/angular-mocks",
+ "lib/jasmine",
+ "lib/jasmine-html",
+ "lib/angular-mocks",
+ // Libraries
+ "lib/jqmExternalAsEmbeddedPages",
+ "lib/JSONParseDate",
+ "lib/jquery-mobile-angular-adapter",
+ // Application
+ "app/services",
+ "app/controllers",
+ "app/markup",
+ "app/application",
// Tests
- "lib/order!unit/JSONParseDateSpec",
- "lib/order!unit/jqmExternalAsEmbeddedPagesSpec",
- "lib/order!unit/AuthenticationControllerSpec",
- "lib/order!unit/utilsServiceSpec.js",
- "lib/order!unit/backendServiceSpec.js",
- "lib/order!unit/rentalServiceSpec.js"], function () {
+ "unit/JSONParseDateSpec",
+ "unit/jqmExternalAsEmbeddedPagesSpec",
+ "unit/AuthenticationControllerSpec",
+ "unit/utilsServiceSpec.js",
+ "unit/backendServiceSpec.js",
+ "unit/rentalServiceSpec.js"
+ ], function (jasmine) {
var trivialReporter = new jasmine.TrivialReporter();
jasmine.getEnv().addReporter(trivialReporter);
jasmine.getEnv().specFilter = function (spec) {
return trivialReporter.specFilter(spec);
};
jasmine.getEnv().execute();
});
- });
</script>
</body>
</html>
View
387 src/test/webapp/lib/JasmineAdapter.js
@@ -1,189 +1,198 @@
-/**
- * @fileoverview Jasmine JsTestDriver Adapter.
- * @author misko@hevery.com (Misko Hevery)
- * @author olmo.maldonado@gmail.com (Olmo Maldonado)
- */
-(function(){
-
-
-var Env = function(onTestDone, onComplete){
- jasmine.Env.call(this);
-
- this.specFilter = function(spec){
- if (!this.exclusive) return true;
- var blocks = spec.queue.blocks, l = blocks.length;
- for (var i = 0; i < l; i++) if (blocks[i].func.exclusive >= this.exclusive) return true;
- return false;
- };
-
- this.reporter = new Reporter(onTestDone, onComplete);
-};
-jasmine.util.inherit(Env, jasmine.Env);
-
-// Here we store:
-// 0: everyone runs
-// 1: run everything under ddescribe
-// 2: run only iits (ignore ddescribe)
-Env.prototype.exclusive = 0;
-
-
-Env.prototype.execute = function(){
- collectMode = false;
- playback();
- jasmine.Env.prototype.execute.call(this);
-};
-
-
-var Reporter = function(onTestDone, onComplete){
- this.onTestDone = onTestDone;
- this.onComplete = onComplete;
- this.reset();
-};
-jasmine.util.inherit(Reporter, jasmine.Reporter);
-
-
-Reporter.formatStack = function(stack) {
- var line, lines = (stack || '').split(/\r?\n/), l = lines.length, frames = [];
- for (var i = 0; i < l; i++){
- line = lines[i];
- if (line.match(/\/jasmine[\.-]/)) continue;
- frames.push(line.replace(/https?:\/\/\w+(:\d+)?\/test\//, '').replace(/^\s*/, ' '));
- }
- return frames.join('\n');
-};
-
-
-Reporter.prototype.reset = function(){
- this.specLog = jstestdriver.console.log_ = [];
-};
-
-
-Reporter.prototype.log = function(str){
- this.specLog.push(str);
-};
-
-
-Reporter.prototype.reportSpecStarting = function(){
- this.reset();
- this.start = +new Date();
-};
-
-
-Reporter.prototype.reportSpecResults = function(spec){
- var elapsed = +new Date() - this.start, results = spec.results();
-
- if (results.skipped) return;
-
- var item, state = 'passed', items = results.getItems(), l = items.length, messages = [];
- for (var i = 0; i < l; i++){
- item = items[i];
- if (item.passed()) continue;
- state = (item.message.indexOf('AssertionError:') != -1) ? 'error' : 'failed';
- messages.push({
- message: item + '',
- name: item.trace.name,
- stack: Reporter.formatStack(item.trace.stack)
- });
- }
-
- this.onTestDone(new jstestdriver.TestResult(
- spec.suite.getFullName(),
- spec.description,
- state,
- jstestdriver.angular.toJson(messages),
- this.specLog.join('\n'),
- elapsed
- ));
-};
-
-
-Reporter.prototype.reportRunnerResults = function(){
- this.onComplete();
-};
-
-
-var collectMode = true, intercepted = {};
-
-describe = intercept('describe');
-beforeEach = intercept('beforeEach');
-afterEach = intercept('afterEach');
-
-var JASMINE_TYPE = 'jasmine test case';
-TestCase('Jasmine Adapter Tests', null, JASMINE_TYPE);
-
-jstestdriver.pluginRegistrar.register({
-
- name: 'jasmine',
-
- getTestRunsConfigurationFor: function(testCaseInfos, expressions, testRunsConfiguration) {
- for (var i = 0; i < testCaseInfos.length; i++) {
- if (testCaseInfos[i].getType() == JASMINE_TYPE) {
- testRunsConfiguration.push(new jstestdriver.TestRunConfiguration(testCaseInfos[i], []));
- }
- }
- return false; // allow other TestCases to be collected.
- },
-
- runTestConfiguration: function(config, onTestDone, onComplete){
- if (config.getTestCaseInfo().getType() != JASMINE_TYPE) return false;
- (jasmine.currentEnv_ = new Env(onTestDone, onComplete)).execute();
- return true;
- },
-
- onTestsFinish: function(){
- jasmine.currentEnv_ = null;
- collectMode = true;
- }
-
-});
-
-function intercept(method){
- var bucket = intercepted[method] = [], method = window[method];
- return function(desc, fn){
- if (collectMode) bucket.push(function(){ method(desc, fn); });
- else method(desc, fn);
- };
-}
-
-function playback(){
- for (var method in intercepted){
- var bucket = intercepted[method];
- for (var i = 0, l = bucket.length; i < l; i++) bucket[i]();
- }
-}
-
-})();
-
-var ddescribe = function(name, fn){
- var env = jasmine.getEnv();
- if (!env.exclusive) env.exclusive = 1; // run ddescribe only
- describe(name, function(){
- var oldIt = it;
- it = function(name, fn){
- fn.exclusive = 1; // run anything under ddescribe
- env.it(name, fn);
- };
-
- try {
- fn.call(this);
- } finally {
- it = oldIt;
- };
- });
-};
-
-var iit = function(name, fn){
- var env = jasmine.getEnv();
- env.exclusive = fn.exclusive = 2; // run only iits
- env.it(name, fn);
-};
-
-// Patch Jasmine for proper stack traces
-jasmine.Spec.prototype.fail = function (e) {
- var result = new jasmine.ExpectationResult({
- passed: false,
- message: e ? jasmine.util.formatException(e) : 'Exception'
- });
- if(e) result.trace = e;
- this.results_.addResult(result);
-};
+/**
+ * @fileoverview Jasmine JsTestDriver Adapter.
+ * @author misko@hevery.com (Misko Hevery)
+ */
+(function(window) {
+ var rootDescribes = new Describes(window);
+ rootDescribes.collectMode();
+
+ var JASMINE_TYPE = 'jasmine test case';
+ TestCase('Jasmine Adapter Tests', null, JASMINE_TYPE);
+
+ var jasminePlugin = {
+ name:'jasmine',
+
+ getTestRunsConfigurationFor: function(testCaseInfos, expressions, testRunsConfiguration) {
+ for (var i = 0; i < testCaseInfos.length; i++) {
+ if (testCaseInfos[i].getType() == JASMINE_TYPE) {
+ testRunsConfiguration.push(new jstestdriver.TestRunConfiguration(testCaseInfos[i], []));
+ }
+ }
+ return false;
+ },
+
+ runTestConfiguration: function(testRunConfiguration, onTestDone, onTestRunConfigurationComplete) {
+ if (testRunConfiguration.getTestCaseInfo().getType() != JASMINE_TYPE) return false;
+
+ var jasmineEnv = jasmine.currentEnv_ = new jasmine.Env();
+ rootDescribes.playback();
+ var specLog = jstestdriver.console.log_ = [];
+ var start;
+ jasmineEnv.specFilter = function(spec) {
+ return rootDescribes.isExclusive(spec);
+ };
+ jasmineEnv.reporter = {
+ log: function(str) {
+ specLog.push(str);
+ },
+
+ reportRunnerStarting: function(runner) { },
+
+ reportSpecStarting: function(spec) {
+ specLog = jstestdriver.console.log_ = [];
+ start = new Date().getTime();
+ },
+
+ reportSpecResults: function(spec) {
+ var suite = spec.suite;
+ var results = spec.results();
+ if (results.skipped) return;
+ var end = new Date().getTime();
+ var messages = [];
+ var resultItems = results.getItems();
+ var state = 'passed';
+ for ( var i = 0; i < resultItems.length; i++) {
+ if (!resultItems[i].passed()) {
+ state = resultItems[i].message.match(/AssertionError:/) ? 'error' : 'failed';
+ messages.push({
+ message: resultItems[i].toString(),
+ name: resultItems[i].trace.name,
+ stack: formatStack(resultItems[i].trace.stack)
+ });
+ }
+ }
+ onTestDone(
+ new jstestdriver.TestResult(
+ suite.getFullName(),
+ spec.description,
+ state,
+ jstestdriver.angular.toJson(messages),
+ specLog.join('\n'),
+ end - start));
+ },
+
+ reportSuiteResults: function(suite) {},
+
+ reportRunnerResults: function(runner) {
+ onTestRunConfigurationComplete();
+ }
+ };
+ jasmineEnv.execute();
+ return true;
+ },
+
+ onTestsFinish: function() {
+ jasmine.currentEnv_ = null;
+ rootDescribes.collectMode();
+ }
+ };
+ jstestdriver.pluginRegistrar.register(jasminePlugin);
+
+ function formatStack(stack) {
+ var lines = (stack||'').split(/\r?\n/);
+ var frames = [];
+ for (var i = 0; i < lines.length; i++) {
+ if (!lines[i].match(/\/jasmine[\.-]/)) {
+ frames.push(lines[i].replace(/https?:\/\/\w+(:\d+)?\/test\//, '').replace(/^\s*/, ' '));
+ }
+ }
+ return frames.join('\n');
+ }
+
+ function noop() {}
+ function Describes(window) {
+ var describes = {};
+ var beforeEachs = {};
+ var afterEachs = {};
+ // Here we store:
+ // 0: everyone runs
+ // 1: run everything under ddescribe
+ // 2: run only iits (ignore ddescribe)
+ var exclusive = 0;
+ var collectMode = true;
+ intercept('describe', describes);
+ intercept('xdescribe', describes);
+ intercept('beforeEach', beforeEachs);
+ intercept('afterEach', afterEachs);
+
+ function intercept(functionName, collection) {
+ window[functionName] = function(desc, fn) {
+ if (collectMode) {
+ collection[desc] = function() {
+ jasmine.getEnv()[functionName](desc, fn);
+ };
+ } else {
+ jasmine.getEnv()[functionName](desc, fn);
+ }
+ };
+ }
+ window.ddescribe = function(name, fn) {
+ if (exclusive < 1) {
+ exclusive = 1; // run ddescribe only
+ }
+ window.describe(name, function() {
+ var oldIt = window.it;
+ window.it = function(name, fn) {
+ if (fn) fn.exclusive = 1; // run anything under ddescribe
+ jasmine.getEnv().it(name, fn);
+ };
+ try {
+ fn.call(this);
+ } finally {
+ window.it = oldIt;
+ };
+ });
+ };
+ window.iit = function(name, fn) {
+ exclusive = fn.exclusive = 2; // run only iits
+ jasmine.getEnv().it(name, fn);
+ };
+
+
+ this.collectMode = function() {
+ collectMode = true;
+ exclusive = 0; // run everything
+ };
+ this.playback = function() {
+ collectMode = false;
+ playback(beforeEachs);
+ playback(afterEachs);
+ playback(describes);
+
+ function playback(set) {
+ for ( var name in set) {
+ set[name]();
+ }
+ }
+ };
+
+ this.isExclusive = function(spec) {
+ if (exclusive) {
+ var blocks = spec.queue.blocks;
+ for ( var i = 0; i < blocks.length; i++) {
+ if (blocks[i].func.exclusive >= exclusive) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return true;
+ };
+ }
+
+})(window);
+
+// Patch Jasmine for proper stack traces
+jasmine.Spec.prototype.fail = function (e) {
+ var expectationResult = new jasmine.ExpectationResult({
+ passed: false,
+ message: e ? jasmine.util.formatException(e) : 'Exception'
+ });
+ // PATCH
+ if (e) {
+ expectationResult.trace = e;
+ }
+ this.results_.addResult(expectationResult);
+};
+
+
View
2,344 src/test/webapp/lib/angular-mocks.js
@@ -1,6 +1,6 @@
/**
- * @license AngularJS v1.0.0rc10
+ * @license AngularJS v1.0.1
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*
@@ -17,552 +17,546 @@
angular.mock = {};
/**
- * @ngdoc object
- * @name angular.module.ngMock.$browser
+ * ! This is a private undocumented service !
+ *
+ * @name ngMock.$browser
*
* @description
- * This service is a mock implementation of {@link angular.module.ng.$browser}. It provides fake
+ * This service is a mock implementation of {@link ng.$browser}. It provides fake
* implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
* cookies, etc...
*
- * The api of this service is the same as that of the real {@link angular.module.ng.$browser $browser}, except
+ * The api of this service is the same as that of the real {@link ng.$browser $browser}, except
* that there are several helper methods available which can be used in tests.
- *
- * The following apis can be used in tests:
- *
- * - $browser.defer — enables testing of code that uses
- * {@link angular.module.ng.$defer $defer} for executing functions via the `setTimeout` api.
*/
angular.mock.$BrowserProvider = function() {
- this.$get = function(){
- return new angular.mock.$Browser();
- };
+ this.$get = function(){
+ return new angular.mock.$Browser();
+ };
};
angular.mock.$Browser = function() {
- var self = this;
+ var self = this;
- this.isMock = true;
- self.$$url = "http://server";
- self.$$lastUrl = self.$$url; // used by url polling fn
- self.pollFns = [];
+ this.isMock = true;
+ self.$$url = "http://server/";
+ self.$$lastUrl = self.$$url; // used by url polling fn
+ self.pollFns = [];
- // TODO(vojta): remove this temporary api
- self.$$completeOutstandingRequest = angular.noop;
- self.$$incOutstandingRequestCount = angular.noop;
+ // TODO(vojta): remove this temporary api
+ self.$$completeOutstandingRequest = angular.noop;
+ self.$$incOutstandingRequestCount = angular.noop;
- // register url polling fn
+ // register url polling fn
- self.onUrlChange = function(listener) {
- self.pollFns.push(
- function() {
- if (self.$$lastUrl != self.$$url) {
- self.$$lastUrl = self.$$url;
- listener(self.$$url);
- }
- }
- );
+ self.onUrlChange = function(listener) {
+ self.pollFns.push(
+ function() {
+ if (self.$$lastUrl != self.$$url) {
+ self.$$lastUrl = self.$$url;
+ listener(self.$$url);
+ }
+ }
+ );
- return listener;
- };
+ return listener;
+ };
- self.cookieHash = {};
- self.lastCookieHash = {};
- self.deferredFns = [];
- self.deferredNextId = 0;
+ self.cookieHash = {};
+ self.lastCookieHash = {};
+ self.deferredFns = [];
+ self.deferredNextId = 0;
- self.defer = function(fn, delay) {
- delay = delay || 0;
- self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
- self.deferredFns.sort(function(a,b){ return a.time - b.time;});
- return self.deferredNextId++;
- };
+ self.defer = function(fn, delay) {
+ delay = delay || 0;
+ self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
+ self.deferredFns.sort(function(a,b){ return a.time - b.time;});
+ return self.deferredNextId++;
+ };
- self.defer.now = 0;
+ self.defer.now = 0;
- self.defer.cancel = function(deferId) {
- var fnIndex;
+ self.defer.cancel = function(deferId) {
+ var fnIndex;
- angular.forEach(self.deferredFns, function(fn, index) {
- if (fn.id === deferId) fnIndex = index;
- });
+ angular.forEach(self.deferredFns, function(fn, index) {
+ if (fn.id === deferId) fnIndex = index;
+ });
- if (fnIndex !== undefined) {
- self.deferredFns.splice(fnIndex, 1);
- return true;
- }
+ if (fnIndex !== undefined) {
+ self.deferredFns.splice(fnIndex, 1);
+ return true;
+ }
- return false;
- };
-
-
- /**
- * @ngdoc method
- * @name angular.module.ngMock.$browser#defer.flush
- * @methodOf angular.module.ngMock.$browser
- *
- * @description
- * Flushes all pending requests and executes the defer callbacks.
- *
- * @param {number=} number of milliseconds to flush. See {@link #defer.now}
- */
- self.defer.flush = function(delay) {
- if (angular.isDefined(delay)) {
- self.defer.now += delay;
- } else {
- if (self.deferredFns.length) {
- self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
- } else {
- throw Error('No deferred tasks to be flushed');
- }
- }
+ return false;
+ };
- while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
- self.deferredFns.shift().fn();
- }
- };
- /**
- * @ngdoc property
- * @name angular.module.ngMock.$browser#defer.now
- * @propertyOf angular.module.ngMock.$browser
- *
- * @description
- * Current milliseconds mock time.
- */
-
- self.$$baseHref = '';
- self.baseHref = function() {
- return this.$$baseHref;
- };
+
+ /**
+ * @name ngMock.$browser#defer.flush
+ * @methodOf ngMock.$browser
+ *
+ * @description
+ * Flushes all pending requests and executes the defer callbacks.
+ *
+ * @param {number=} number of milliseconds to flush. See {@link #defer.now}
+ */
+ self.defer.flush = function(delay) {
+ if (angular.isDefined(delay)) {
+ self.defer.now += delay;
+ } else {
+ if (self.deferredFns.length) {
+ self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
+ } else {
+ throw Error('No deferred tasks to be flushed');
+ }
+ }
+
+ while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
+ self.deferredFns.shift().fn();
+ }
+ };
+ /**
+ * @name ngMock.$browser#defer.now
+ * @propertyOf ngMock.$browser
+ *
+ * @description
+ * Current milliseconds mock time.
+ */
+
+ self.$$baseHref = '';
+ self.baseHref = function() {
+ return this.$$baseHref;
+ };
};
angular.mock.$Browser.prototype = {
- /**
- * @name angular.module.ngMock.$browser#poll
- * @methodOf angular.module.ngMock.$browser
- *
- * @description
- * run all fns in pollFns
- */
- poll: function poll() {
- angular.forEach(this.pollFns, function(pollFn){
- pollFn();
- });
- },
+ /**
+ * @name ngMock.$browser#poll
+ * @methodOf ngMock.$browser
+ *
+ * @description
+ * run all fns in pollFns
+ */
+ poll: function poll() {
+ angular.forEach(this.pollFns, function(pollFn){
+ pollFn();
+ });
+ },
- addPollFn: function(pollFn) {
- this.pollFns.push(pollFn);
- return pollFn;
- },
+ addPollFn: function(pollFn) {
+ this.pollFns.push(pollFn);
+ return pollFn;
+ },
- url: function(url, replace) {
- if (url) {
- this.$$url = url;
- return this;
- }
+ url: function(url, replace) {
+ if (url) {
+ this.$$url = url;
+ return this;
+ }
- return this.$$url;
- },
-
- cookies: function(name, value) {
- if (name) {
- if (value == undefined) {
- delete this.cookieHash[name];
- } else {
- if (angular.isString(value) && //strings only
- value.length <= 4096) { //strict cookie storage limits
- this.cookieHash[name] = value;
+ return this.$$url;
+ },
+
+ cookies: function(name, value) {
+ if (name) {
+ if (value == undefined) {
+ delete this.cookieHash[name];
+ } else {
+ if (angular.isString(value) && //strings only
+ value.length <= 4096) { //strict cookie storage limits
+ this.cookieHash[name] = value;
+ }
+ }
+ } else {
+ if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
+ this.lastCookieHash = angular.copy(this.cookieHash);
+ this.cookieHash = angular.copy(this.cookieHash);
+ }
+ return this.cookieHash;
}
- }
- } else {
- if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
- this.lastCookieHash = angular.copy(this.cookieHash);
- this.cookieHash = angular.copy(this.cookieHash);
- }
- return this.cookieHash;
- }
- },
+ },
- notifyWhenNoOutstandingRequests: function(fn) {
- fn();
- }
+ notifyWhenNoOutstandingRequests: function(fn) {
+ fn();
+ }
};
/**
* @ngdoc object
- * @name angular.module.ngMock.$exceptionHandlerProvider
+ * @name ngMock.$exceptionHandlerProvider
*
* @description
- * Configures the mock implementation of {@link angular.module.ng.$exceptionHandler} to rethrow or to log errors passed
+ * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors passed
* into the `$exceptionHandler`.
*/
/**
* @ngdoc object
- * @name angular.module.ngMock.$exceptionHandler
+ * @name ngMock.$exceptionHandler
*
* @description
- * Mock implementation of {@link angular.module.ng.$exceptionHandler} that rethrows or logs errors passed
- * into it. See {@link angular.module.ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
+ * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
+ * into it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
* information.
*/
angular.mock.$ExceptionHandlerProvider = function() {
- var handler;
-
- /**
- * @ngdoc method
- * @name angular.module.ngMock.$exceptionHandlerProvider#mode
- * @methodOf angular.module.ngMock.$exceptionHandlerProvider
- *
- * @description
- * Sets the logging mode.
- *
- * @param {string} mode Mode of operation, defaults to `rethrow`.
- *
- * - `rethrow`: If any errors are are passed into the handler in tests, it typically
- * means that there is a bug in the application or test, so this mock will
- * make these tests fail.
- * - `log`: Sometimes it is desirable to test that an error is throw, for this case the `log` mode stores the
- * error and allows later assertion of it.
- * See {@link angular.module.ngMock.$log#assertEmpty assertEmpty()} and
- * {@link angular.module.ngMock.$log#reset reset()}
- */
- this.mode = function(mode) {
- switch(mode) {
- case 'rethrow':
- handler = function(e) {
- throw e;
- };
- break;
- case 'log':
- var errors = [];
-
- handler = function(e) {
- if (arguments.length == 1) {
- errors.push(e);
- } else {
- errors.push([].slice.call(arguments, 0));
- }
- };
+ var handler;
- handler.errors = errors;
- break;
- default:
- throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
- }
- };
+ /**
+ * @ngdoc method
+ * @name ngMock.$exceptionHandlerProvider#mode
+ * @methodOf ngMock.$exceptionHandlerProvider
+ *
+ * @description
+ * Sets the logging mode.
+ *
+ * @param {string} mode Mode of operation, defaults to `rethrow`.
+ *
+ * - `rethrow`: If any errors are are passed into the handler in tests, it typically
+ * means that there is a bug in the application or test, so this mock will
+ * make these tests fail.
+ * - `log`: Sometimes it is desirable to test that an error is throw, for this case the `log` mode stores the
+ * error and allows later assertion of it.
+ * See {@link ngMock.$log#assertEmpty assertEmpty()} and
+ * {@link ngMock.$log#reset reset()}
+ */
+ this.mode = function(mode) {
+ switch(mode) {
+ case 'rethrow':
+ handler = function(e) {
+ throw e;
+ };
+ break;
+ case 'log':
+ var errors = [];
+
+ handler = function(e) {
+ if (arguments.length == 1) {
+ errors.push(e);
+ } else {
+ errors.push([].slice.call(arguments, 0));
+ }
+ };
+
+ handler.errors = errors;
+ break;
+ default:
+ throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
+ }
+ };
- this.$get = function() {
- return handler;
- };
+ this.$get = function() {
+ return handler;
+ };
- this.mode('rethrow');
+ this.mode('rethrow');
};
/**
* @ngdoc service
- * @name angular.module.ngMock.$log
+ * @name ngMock.$log
*
* @description
- * Mock implementation of {@link angular.module.ng.$log} that gathers all logged messages in arrays
+ * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
* (one array per logging level). These arrays are exposed as `logs` property of each of the
* level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
*
*/
angular.mock.$LogProvider = function() {
- function concat(array1, array2, index) {
- return array1.concat(Array.prototype.slice.call(array2, index));
- }
+ function concat(array1, array2, index) {
+ return array1.concat(Array.prototype.slice.call(array2, index));
+ }
- this.$get = function () {
- var $log = {
- log: function() { $log.log.logs.push(concat([], arguments, 0)); },
- warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
- info: function() { $log.info.logs.push(concat([], arguments, 0)); },
- error: function() { $log.error.logs.push(concat([], arguments, 0)); }
- };
+ this.$get = function () {
+ var $log = {
+ log: function() { $log.log.logs.push(concat([], arguments, 0)); },
+ warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
+ info: function() { $log.info.logs.push(concat([], arguments, 0)); },
+ error: function() { $log.error.logs.push(concat([], arguments, 0)); }
+ };
- /**
- * @ngdoc method
- * @name angular.module.ngMock.$log#reset
- * @methodOf angular.module.ngMock.$log
- *
- * @description
- * Reset all of the logging arrays to empty.
- */
- $log.reset = function () {
- /**
- * @ngdoc property
- * @name angular.module.ngMock.$log#log.logs
- * @propertyOf angular.module.ngMock.$log
- *
- * @description
- * Array of logged messages.
- */
- $log.log.logs = [];
- /**
- * @ngdoc property
- * @name angular.module.ngMock.$log#warn.logs
- * @propertyOf angular.module.ngMock.$log
- *
- * @description
- * Array of logged messages.
- */
- $log.warn.logs = [];
- /**
- * @ngdoc property
- * @name angular.module.ngMock.$log#info.logs
- * @propertyOf angular.module.ngMock.$log
- *
- * @description
- * Array of logged messages.
- */
- $log.info.logs = [];
- /**
- * @ngdoc property
- * @name angular.module.ngMock.$log#error.logs
- * @propertyOf angular.module.ngMock.$log
- *
- * @description
- * Array of logged messages.
- */
- $log.error.logs = [];
- };
+ /**
+ * @ngdoc method
+ * @name ngMock.$log#reset
+ * @methodOf ngMock.$log
+ *
+ * @description
+ * Reset all of the logging arrays to empty.
+ */
+ $log.reset = function () {
+ /**
+ * @ngdoc property
+ * @name ngMock.$log#log.logs
+ * @propertyOf ngMock.$log
+ *
+ * @description
+ * Array of logged messages.
+ */
+ $log.log.logs = [];
+ /**
+ * @ngdoc property
+ * @name ngMock.$log#warn.logs
+ * @propertyOf ngMock.$log
+ *
+ * @description
+ * Array of logged messages.
+ */
+ $log.warn.logs = [];
+ /**
+ * @ngdoc property
+ * @name ngMock.$log#info.logs
+ * @propertyOf ngMock.$log
+ *
+ * @description
+ * Array of logged messages.
+ */
+ $log.info.logs = [];
+ /**
+ * @ngdoc property
+ * @name ngMock.$log#error.logs
+ * @propertyOf ngMock.$log
+ *
+ * @description
+ * Array of logged messages.
+ */
+ $log.error.logs = [];
+ };
- /**
- * @ngdoc method
- * @name angular.module.ngMock.$log#assertEmpty
- * @methodOf angular.module.ngMock.$log
- *
- * @description
- * Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
- */
- $log.assertEmpty = function() {
- var errors = [];
- angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
- angular.forEach($log[logLevel].logs, function(log) {
- angular.forEach(log, function (logItem) {
- errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || ''));
- });
- });
- });
- if (errors.length) {
- errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
- "log message was not checked and removed:");
- errors.push('');
- throw new Error(errors.join('\n---------\n'));
- }
- };
+ /**
+ * @ngdoc method
+ * @name ngMock.$log#assertEmpty
+ * @methodOf ngMock.$log
+ *
+ * @description
+ * Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
+ */
+ $log.assertEmpty = function() {
+ var errors = [];
+ angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
+ angular.forEach($log[logLevel].logs, function(log) {
+ angular.forEach(log, function (logItem) {
+ errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || ''));
+ });
+ });
+ });
+ if (errors.length) {
+ errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
+ "log message was not checked and removed:");
+ errors.push('');
+ throw new Error(errors.join('\n---------\n'));
+ }
+ };
- $log.reset();
- return $log;
- };
+ $log.reset();
+ return $log;
+ };
};
(function() {
- var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
-
- function jsonStringToDate(string){
- var match;
- if (match = string.match(R_ISO8061_STR)) {
- var date = new Date(0),
- tzHour = 0,
- tzMin = 0;
- if (match[9]) {
- tzHour = int(match[9] + match[10]);
- tzMin = int(match[9] + match[11]);
- }
- date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
- date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
- return date;
+ var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
+
+ function jsonStringToDate(string){
+ var match;
+ if (match = string.match(R_ISO8061_STR)) {
+ var date = new Date(0),
+ tzHour = 0,
+ tzMin = 0;
+ if (match[9]) {
+ tzHour = int(match[9] + match[10]);
+ tzMin = int(match[9] + match[11]);
+ }
+ date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
+ date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
+ return date;
+ }
+ return string;
}
- return string;
- }
-
- function int(str) {
- return parseInt(str, 10);
- }
-
- function padNumber(num, digits, trim) {
- var neg = '';
- if (num < 0) {
- neg = '-';
- num = -num;
+
+ function int(str) {
+ return parseInt(str, 10);
}
- num = '' + num;
- while(num.length < digits) num = '0' + num;
- if (trim)
- num = num.substr(num.length - digits);
- return neg + num;
- }
-
-
- /**
- * @ngdoc object
- * @name angular.mock.TzDate
- * @description
- *
- * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
- *
- * Mock of the Date type which has its timezone specified via constroctor arg.
- *
- * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
- * offset, so that we can test code that depends on local timezone settings without dependency on
- * the time zone settings of the machine where the code is running.
- *
- * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
- * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
- *
- * @example
- * !!!! WARNING !!!!!
- * This is not a complete Date object so only methods that were implemented can be called safely.
- * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
- *
- * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
- * incomplete we might be missing some non-standard methods. This can result in errors like:
- * "Date.prototype.foo called on incompatible Object".
- *
- * <pre>
- * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
- * newYearInBratislava.getTimezoneOffset() => -60;
- * newYearInBratislava.getFullYear() => 2010;
- * newYearInBratislava.getMonth() => 0;
- * newYearInBratislava.getDate() => 1;
- * newYearInBratislava.getHours() => 0;
- * newYearInBratislava.getMinutes() => 0;
- * </pre>
- *
- */
- angular.mock.TzDate = function (offset, timestamp) {
- var self = new Date(0);
- if (angular.isString(timestamp)) {
- var tsStr = timestamp;
-
- self.origDate = jsonStringToDate(timestamp);
-
- timestamp = self.origDate.getTime();
- if (isNaN(timestamp))
- throw {
- name: "Illegal Argument",
- message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
- };
- } else {
- self.origDate = new Date(timestamp);
+
+ function padNumber(num, digits, trim) {
+ var neg = '';
+ if (num < 0) {
+ neg = '-';
+ num = -num;
+ }
+ num = '' + num;
+ while(num.length < digits) num = '0' + num;
+ if (trim)
+ num = num.substr(num.length - digits);
+ return neg + num;
}
- var localOffset = new Date(timestamp).getTimezoneOffset();
- self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
- self.date = new Date(timestamp + self.offsetDiff);
- self.getTime = function() {
- return self.date.getTime() - self.offsetDiff;
- };
+ /**
+ * @ngdoc object
+ * @name angular.mock.TzDate
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
+ *
+ * Mock of the Date type which has its timezone specified via constroctor arg.
+ *
+ * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
+ * offset, so that we can test code that depends on local timezone settings without dependency on
+ * the time zone settings of the machine where the code is running.
+ *
+ * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
+ * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
+ *
+ * @example
+ * !!!! WARNING !!!!!
+ * This is not a complete Date object so only methods that were implemented can be called safely.
+ * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
+ *
+ * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
+ * incomplete we might be missing some non-standard methods. This can result in errors like:
+ * "Date.prototype.foo called on incompatible Object".
+ *
+ * <pre>
+ * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
+ * newYearInBratislava.getTimezoneOffset() => -60;
+ * newYearInBratislava.getFullYear() => 2010;
+ * newYearInBratislava.getMonth() => 0;
+ * newYearInBratislava.getDate() => 1;
+ * newYearInBratislava.getHours() => 0;
+ * newYearInBratislava.getMinutes() => 0;
+ * </pre>
+ *
+ */
+ angular.mock.TzDate = function (offset, timestamp) {
+ var self = new Date(0);
+ if (angular.isString(timestamp)) {
+ var tsStr = timestamp;
+
+ self.origDate = jsonStringToDate(timestamp);
+
+ timestamp = self.origDate.getTime();
+ if (isNaN(timestamp))
+ throw {
+ name: "Illegal Argument",
+ message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
+ };
+ } else {
+ self.origDate = new Date(timestamp);
+ }
- self.toLocaleDateString = function() {
- return self.date.toLocaleDateString();
- };
+ var localOffset = new Date(timestamp).getTimezoneOffset();
+ self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
+ self.date = new Date(timestamp + self.offsetDiff);
- self.getFullYear = function() {
- return self.date.getFullYear();
- };
+ self.getTime = function() {
+ return self.date.getTime() - self.offsetDiff;
+ };
- self.getMonth = function() {
- return self.date.getMonth();
- };
+ self.toLocaleDateString = function() {
+ return self.date.toLocaleDateString();
+ };
- self.getDate = function() {
- return self.date.getDate();
- };
+ self.getFullYear = function() {
+ return self.date.getFullYear();
+ };
- self.getHours = function() {
- return self.date.getHours();
- };
+ self.getMonth = function() {
+ return self.date.getMonth();
+ };
- self.getMinutes = function() {
- return self.date.getMinutes();
- };
+ self.getDate = function() {
+ return self.date.getDate();
+ };
- self.getSeconds = function() {
- return self.date.getSeconds();
- };
+ self.getHours = function() {
+ return self.date.getHours();
+ };
- self.getTimezoneOffset = function() {
- return offset * 60;
- };
+ self.getMinutes = function() {
+ return self.date.getMinutes();
+ };
- self.getUTCFullYear = function() {
- return self.origDate.getUTCFullYear();
- };
+ self.getSeconds = function() {
+ return self.date.getSeconds();
+ };
- self.getUTCMonth = function() {
- return self.origDate.getUTCMonth();
- };
+ self.getTimezoneOffset = function() {
+ return offset * 60;
+ };
- self.getUTCDate = function() {
- return self.origDate.getUTCDate();
- };
+ self.getUTCFullYear = function() {
+ return self.origDate.getUTCFullYear();
+ };
- self.getUTCHours = function() {
- return self.origDate.getUTCHours();
- };
+ self.getUTCMonth = function() {
+ return self.origDate.getUTCMonth();
+ };
- self.getUTCMinutes = function() {
- return self.origDate.getUTCMinutes();
- };
+ self.getUTCDate = function() {
+ return self.origDate.getUTCDate();
+ };
- self.getUTCSeconds = function() {
- return self.origDate.getUTCSeconds();
- };
+ self.getUTCHours = function() {
+ return self.origDate.getUTCHours();
+ };
- self.getUTCMilliseconds = function() {
- return self.origDate.getUTCMilliseconds();
- };
+ self.getUTCMinutes = function() {
+ return self.origDate.getUTCMinutes();
+ };
- self.getDay = function() {
- return self.date.getDay();
- };
+ self.getUTCSeconds = function() {
+ return self.origDate.getUTCSeconds();
+ };
- // provide this method only on browsers that already have it
- if (self.toISOString) {
- self.toISOString = function() {
- return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
- padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
- padNumber(self.origDate.getUTCDate(), 2) + 'T' +
- padNumber(self.origDate.getUTCHours(), 2) + ':' +
- padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
- padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
- padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'
- }
- }
+ self.getUTCMilliseconds = function() {
+ return self.origDate.getUTCMilliseconds();
+ };
- //hide all methods not implemented in this mock that the Date prototype exposes
- var unimplementedMethods = ['getMilliseconds', 'getUTCDay',
- 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
- 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
- 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
- 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
- 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
-
- angular.forEach(unimplementedMethods, function(methodName) {
- self[methodName] = function() {
- throw Error("Method '" + methodName + "' is not implemented in the TzDate mock");
- };
- });
+ self.getDay = function() {
+ return self.date.getDay();
+ };
- return self;
- };
+ // provide this method only on browsers that already have it
+ if (self.toISOString) {
+ self.toISOString = function() {
+ return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
+ padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
+ padNumber(self.origDate.getUTCDate(), 2) + 'T' +
+ padNumber(self.origDate.getUTCHours(), 2) + ':' +
+ padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
+ padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
+ padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'
+ }
+ }
- //make "tzDateInstance instanceof Date" return true
- angular.mock.TzDate.prototype = Date.prototype;
+ //hide all methods not implemented in this mock that the Date prototype exposes
+ var unimplementedMethods = ['getMilliseconds', 'getUTCDay',
+ 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
+ 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
+ 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
+ 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
+ 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
+
+ angular.forEach(unimplementedMethods, function(methodName) {
+ self[methodName] = function() {
+ throw Error("Method '" + methodName + "' is not implemented in the TzDate mock");
+ };
+ });
+
+ return self;
+ };
+
+ //make "tzDateInstance instanceof Date" return true
+ angular.mock.TzDate.prototype = Date.prototype;
})();
@@ -578,72 +572,72 @@ angular.mock.$LogProvider = function() {
* This method is also available on window, where it can be used to display objects on debug console.
*
* @param {*} object - any object to turn into string.
- * @return a serialized string of the argument
+ * @return {string} a serialized string of the argument
*/
angular.mock.dump = function(object) {
- return serialize(object);
-
- function serialize(object) {
- var out;