Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

initial revision

  • Loading branch information...
commit 171033e958c2fe9c7a1874b877db3ae8b06ef6dc 0 parents
@btford btford authored
Showing with 22,605 additions and 0 deletions.
  1. +55 −0 README.md
  2. +5 −0 background.html
  3. +4,978 −0 css/bootstrap.css
  4. +18 −0 css/panel.css
  5. +3 −0  css/scope.css
  6. +5 −0 devtools.html
  7. BIN  img/angular.png
  8. BIN  img/angular.pxm
  9. BIN  img/console.png
  10. BIN  img/inspect.png
  11. BIN  img/model-tree.png
  12. BIN  img/options.png
  13. BIN  img/performance.png
  14. +62 −0 js/background.js
  15. +90 −0 js/controllers/OptionsCtrl.js
  16. +134 −0 js/controllers/PerfCtrl.js
  17. +5 −0 js/controllers/TabCtrl.js
  18. +75 −0 js/controllers/TreeCtrl.js
  19. +53 −0 js/devtools.js
  20. +34 −0 js/directives/mtree.js
  21. +36 −0 js/directives/wtree.js
  22. +6 −0 js/filters/first.js
  23. +182 −0 js/inject/debug.js
  24. +1,719 −0 js/lib/angular-mocks.js
  25. +14,326 −0 js/lib/angular.js
  26. +4 −0 js/lib/jquery-1.7.2.min.js
  27. +1 −0  js/panelApp.js
  28. +306 −0 js/services/appContext.js
  29. +26 −0 js/services/chromeExtension.js
  30. +22 −0 manifest.json
  31. +158 −0 panel.html
  32. +70 −0 test/AppContextSpec.js
  33. +55 −0 test/OptionsCtrlSpec.js
  34. +52 −0 test/TreeCtrlSpec.js
  35. +47 −0 test/mock/AppContextMock.js
  36. +54 −0 test/mock/ChromeMock.js
  37. +24 −0 testacular.conf
55 README.md
@@ -0,0 +1,55 @@
+# AngularJS Batarang
+
+## Getting it
+Checkout my fork of AngularJS from Github:
+
+ git clone git://github.com/btford/angular.js.git
+ cd angular.js
+ git fetch origin extension
+ git checkout origin/extension
+
+
+## Installation
+You'll need [Google Chrome Canary](https://tools.google.com/dlpage/chromesxs) to use the extension.
+
+1. Navigate to `chrome://flags/` in Canary, and enable "Experimental Extension APIs"
+2. Navigate to `chrome://chrome/extensions/` and enable Developer Mode.
+3. On the same page, click "Load unpacked extension" and choose the "extension" directory inside the repository that you just checked out.
+
+## Using the Batarang
+First, navigate Chrome Canary to the AngularJS application that you want to debug. [Open the Developer Tools](https://developers.google.com/chrome-developer-tools/docs/overview#access). There should be an AngularJS icon. Click on it to open he AngularJS Batarang.
+
+
+The Batarang has four tabs: Model, Performance, Options, and Help.
+
+### Model
+![Batarang screenshot](img/model-tree.png)
+
+Starting at the top of this tab, there is the root selection. If the application has only one `ng-app` declaration (as most applications do) then you will not see the option to change roots.
+
+Below that is a tree showing how scopes are nested, and which models are attached to them. Clicking on a scope name will take you to the Elements tab, and show you the DOM element associated with that scope. Models and methods attached to each scope are listed with bullet points on the tree. Just the name of methods attached to a scope are shown. Models with a simple value and complex objects are shown as JSON. You can edit either, and the changes will be reflected in the application being debugged.
+
+
+### Performance
+![Batarang performance tab screenshot](img/performance.png)
+
+The performance tab must be enabled separately because it causes code to be injected into AngularJS to track and report performance metrics. There is also an option to output performance metrics to the console.
+
+Below that is a tree of watched expressions, showing which expressions are attached to which scopes. Much like the model tree, you can collapse sections by clicking on "toggle" and you can inspect the element that a scope is attached to by clicking on the scope name.
+
+Underneath that is a graph showing the relative performance of all of the application's expressions. This graph will update as you interact with the application.
+
+### Options
+![Batarang options tab screenshot](img/options.png)
+
+Last, there is the options tab. The options tab has two checkboxes: one for "show scopes" and one for "show bindings." Each of these options, when enabled, highlights the respective feature of the application being debugged; scopes will have a red outline, and bindings will have a blue outline.
+
+### Elements
+![Batarang console screenshot](img/inspect.png)
+
+The Batarang also hooks into some of the existing features of the Chrome developer tools. For AngularJS applications, there is now a properties pane on in the Elements tab. Much like the model tree in the AngularJS tab, you can use this to inspect the models attached to a given element's scope.
+
+### Console
+![Batarang console screenshot](img/console.png)
+
+The Batarang exposes some convenient features to the Chrome developer tools console. To access the scope of an element selected in the Elements tab of the developer tools, in console, you can type `$scope`. If you change value of some model on `$scope` and want to have this change reflected in the running application, you need to call `$scope.$apply()` after making the change.
5 background.html
@@ -0,0 +1,5 @@
+<html>
+<body>
+<script src="js/background.js"></script>
+</body>
+</html>
4,978 css/bootstrap.css
4,978 additions, 0 deletions not shown
18 css/panel.css
@@ -0,0 +1,18 @@
+.hidden {
+ display: none;
+}
+.col {
+ float: left;
+ width: 200px;
+}
+.col-2 {
+ float: left;
+ width: 400px;
+}
+.scope-branch {
+ margin-left: 30px;
+ background-color:rgba(0,0,0,0.06);
+}
+body {
+ margin: 10px;
+}
3  css/scope.css
@@ -0,0 +1,3 @@
+.ng-scope {
+ border: 1px solid red;
+}
5 devtools.html
@@ -0,0 +1,5 @@
+<html>
+<body>
+<script src="js/devtools.js"></script>
+</body>
+</html>
BIN  img/angular.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
BIN  img/angular.pxm
Binary file not shown
BIN  img/console.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
BIN  img/inspect.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
BIN  img/model-tree.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
BIN  img/options.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
BIN  img/performance.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
62 js/background.js
@@ -0,0 +1,62 @@
+var injectPrereqs = {};
+
+var cbs = {};
+
+chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
+ if (request.script === 'register') {
+ chrome.tabs.onUpdated.addListener(cbs[request.tab]);
+
+ } else if (request.script === 'debug-true') {
+ cbs[request.tab] = (function (req) {
+ return function (tabId, changeInfo, tab) {
+ if (tabId !== req.tab) {
+ return;
+ }
+ chrome.tabs.executeScript(tabId, {
+ file: 'js/inject/debug.js'
+ });
+ };
+ }(request));
+ chrome.tabs.onUpdated.addListener(cbs[request.tab]);
+
+ } else if (request.script === 'debug-false' && cbs[request.tab]) {
+ chrome.tabs.onUpdated.removeListener(cbs[request.tab]);
+ delete cbs[request.tab];
+
+ } else {
+ chrome.tabs.executeScript(request.tab, {
+ file: 'js/inject/css-inject.js'
+ }, function () {
+ injectPrereqs[request.tab] = true;
+ chrome.tabs.executeScript(request.tab, {
+ file: 'inject/' + request.script + '.js'
+ });
+ });
+ }
+ if (sendResponse) {
+ sendResponse();
+ }
+});
+
+// notify of page refreshes
+chrome.extension.onConnect.addListener(function(port) {
+ port.onMessage.addListener(function (msg) {
+ if (msg.action === 'register') {
+ var respond = function (tabId, changeInfo, tab) {
+ if (tabId !== msg.inspectedTabId) {
+ return;
+ }
+ port.postMessage('refresh');
+ };
+
+ chrome.tabs.onUpdated.addListener(respond);
+ port.onDisconnect.addListener(function () {
+ chrome.tabs.onUpdated.removeListener(respond);
+ });
+ }
+ });
+ port.onDisconnect.addListener(function () {
+ console.log('disconnected');
+ });
+});
+
90 js/controllers/OptionsCtrl.js
@@ -0,0 +1,90 @@
+panelApp.controller('OptionsCtrl', function OptionsCtrl($scope, appContext, chromeExtension) {
+
+ $scope.debugger = {
+ scopes: false,
+ bindings: false,
+ app: false
+ };
+
+ $scope.$watch('debugger.scopes', function (newVal, oldVal) {
+ if (newVal) {
+ chromeExtension.eval(function () {
+ var addCssRule = function (selector, rule) {
+ var styleSheet = document.styleSheets[document.styleSheets.length - 1];
+ styleSheet.insertRule(selector + '{' + rule + '}', styleSheet.cssRules.length);
+ };
+ addCssRule('.ng-scope', 'border: 1px solid red');
+ });
+ } else {
+ chromeExtension.eval(function () {
+ removeCssRule = function (selector, rule) {
+ var styleSheet = document.styleSheets[document.styleSheets.length - 1];
+
+ var i;
+ for (i = styleSheet.cssRules.length - 1; i >= 0; i -= 1) {
+ if (styleSheet.cssRules[i].cssText === selector + ' { ' + rule + '; }') {
+ styleSheet.deleteRule(i);
+ }
+ }
+ };
+ removeCssRule('.ng-scope', 'border: 1px solid red');
+ });
+ }
+ });
+
+ $scope.$watch('debugger.bindings', function (newVal, oldVal) {
+ if (newVal) {
+ chromeExtension.eval(function () {
+ var addCssRule = function (selector, rule) {
+ var styleSheet = document.styleSheets[document.styleSheets.length - 1];
+ styleSheet.insertRule(selector + '{' + rule + '}', styleSheet.cssRules.length);
+ };
+ addCssRule('.ng-binding', 'border: 1px solid blue');
+ });
+ } else {
+ chromeExtension.eval(function () {
+ removeCssRule = function (selector, rule) {
+ var styleSheet = document.styleSheets[document.styleSheets.length - 1];
+
+ var i;
+ for (i = styleSheet.cssRules.length - 1; i >= 0; i -= 1) {
+ if (styleSheet.cssRules[i].cssText === selector + ' { ' + rule + '; }') {
+ styleSheet.deleteRule(i);
+ }
+ }
+ };
+ removeCssRule('.ng-binding', 'border: 1px solid blue');
+ });
+ }
+ });
+
+ $scope.$watch('debugger.app', function (newVal, oldVal) {
+ if (newVal) {
+ chromeExtension.eval(function () {
+ var addCssRule = function (selector, rule) {
+ var styleSheet = document.styleSheets[document.styleSheets.length - 1];
+ styleSheet.insertRule(selector + '{' + rule + '}', styleSheet.cssRules.length);
+ };
+ addCssRule('[ng-app]', 'border: 1px solid green');
+ //addCssRule('ng-app:', 'border: 1px solid green');
+ addCssRule('[app-run]', 'border: 1px solid green');
+ });
+ } else {
+ chromeExtension.eval(function () {
+ removeCssRule = function (selector, rule) {
+ var styleSheet = document.styleSheets[document.styleSheets.length - 1];
+
+ var i;
+ for (i = styleSheet.cssRules.length - 1; i >= 0; i -= 1) {
+ if (styleSheet.cssRules[i].cssText === selector + ' { ' + rule + '; }') {
+ styleSheet.deleteRule(i);
+ }
+ }
+ };
+ removeCssRule('[ng-app]', 'border: 1px solid green');
+ //removeCssRule('ng-app:', 'border: 1px solid green');
+ removeCssRule('[app-run]', 'border: 1px solid green');
+ });
+ }
+ });
+});
134 js/controllers/PerfCtrl.js
@@ -0,0 +1,134 @@
+panelApp.filter('sortByTime', function () {
+ return function (input) {
+ return input.slice(0).sort(function (a, b) {
+ return b.time - a.time;
+ });
+ };
+});
+
+panelApp.controller('PerfCtrl', function PerfCtrl($scope, appContext) {
+
+ $scope.enable = false;
+
+ $scope.histogram = [];
+ $scope.timeline = [];
+
+ $scope.clearHistogram = function () {
+ appContext.clearHistogram();
+ };
+
+ var first = true;
+ $scope.$watch('enable', function (newVal, oldVal) {
+
+ // prevent refresh on initial pageload
+ if (first) {
+ first = false;
+ } else {
+ appContext.setDebug(newVal);
+ }
+ if (newVal) {
+ //updateTimeline();
+ updateHistogram();
+ }
+ });
+
+ $scope.log = false;
+
+ $scope.$watch('log', function (newVal, oldVal) {
+ appContext.setLog(newVal);
+
+ appContext.watchRefresh(function () {
+ appContext.setLog(newVal);
+ });
+ });
+
+ $scope.inspect = function () {
+ appContext.inspect(this.val.id);
+ };
+
+ var updateTimeline = function () {
+ var timeline = appContext.getTimeline();
+ if (timeline && timeline.length > $scope.timeline.length) {
+ $scope = $scope.concat(timeline.splice($scope.length - 1));
+ }
+ };
+
+ var updateHistogram = function () {
+ var info = appContext.getHistogram();
+ if (!info) {
+ return;
+ }
+ var total = 0;
+ info.forEach(function (elt) {
+ total += elt.time;
+ });
+ var i, elt, his;
+ for (i = 0; (i < $scope.histogram.length && i < info.length); i++) {
+ elt = info[i];
+ his = $scope.histogram[i];
+ his.time = elt.time.toPrecision(3);
+ his.percent = (100 * elt.time / total).toPrecision(3);
+ }
+ for ( ; i < info.length; i++) {
+ elt = info[i];
+ elt.time = elt.time.toPrecision(3);
+ elt.percent = (100 * elt.time / total).toPrecision(3);
+ $scope.histogram.push(elt);
+ }
+ $scope.histogram.length = info.length;
+ };
+
+ var updateTree = function () {
+ var rts = appContext.getListOfRoots();
+ if (!rts) {
+ return;
+ }
+ var roots = [];
+ rts.forEach(function (item) {
+ roots.push({
+ label: item,
+ value: item
+ });
+ });
+
+ $scope.roots = roots;
+ var trees = appContext.getModelTrees();
+ if (!$scope.trees || $scope.trees.length !== trees.length) {
+ $scope.trees = trees;
+ } else {
+
+ var syncBranch = function (oldTree, newTree) {
+ if (!oldTree || !newTree) {
+ return;
+ }
+ oldTree.locals = newTree.locals;
+ if (oldTree.children.length !== newTree.children.length) {
+ oldTree.children = newTree.children;
+ } else {
+ oldTree.children.forEach(function (oldBranch, i) {
+ var newBranch = newTree.children[i];
+ syncBranch(newBranch, oldBranch);
+ });
+ }
+ };
+
+ var treeId, oldTree, newTree;
+ for (treeId in $scope.trees) {
+ if ($scope.trees.hasOwnProperty(treeId)) {
+ oldTree = $scope.trees[treeId];
+ newTree = trees[treeId];
+ syncBranch(oldTree, newTree);
+ }
+ }
+ }
+
+ if (roots.length === 0) {
+ $scope.selectedRoot = null;
+ } else if (!$scope.selectedRoot) {
+ $scope.selectedRoot = roots[0].value;
+ }
+ $scope.$apply();
+ };
+ appContext.watchPoll(updateTree);
+ appContext.watchPoll(updateHistogram);
+});
5 js/controllers/TabCtrl.js
@@ -0,0 +1,5 @@
+// TODO: call this AppCtrl?
+// this acts as the top level ctrl
+panelApp.controller('TabCtrl', function TabCtrl($scope) {
+ $scope.selectedTab = 'Model';
+});
75 js/controllers/TreeCtrl.js
@@ -0,0 +1,75 @@
+
+panelApp.controller('TreeCtrl', function TreeCtrl($scope, chromeExtension, appContext) {
+
+ $scope.inspect = function () {
+ appContext.inspect(this.val.id);
+ };
+
+ $scope.edit = function () {
+ appContext.executeOnScope(this.val.id, function (scope, elt, args) {
+ scope[args.name] = args.value;
+ scope.$apply();
+ }, {
+ name: this.key,
+ value: JSON.parse(this.item)
+ });
+ };
+
+ $scope.roots = [];
+
+ var updateTree = function () {
+ if ($('input:focus').length > 0) {
+ return;
+ }
+ var roots = appContext.getListOfRoots();
+ if (!roots) {
+ return;
+ }
+
+ var trees = appContext.getModelTrees();
+ if (!$scope.trees || $scope.trees.length !== trees.length) {
+ $scope.trees = trees;
+ } else {
+
+ var syncBranch = function (oldTree, newTree) {
+ if (!oldTree || !newTree) {
+ return;
+ }
+ oldTree.locals = newTree.locals;
+ if (oldTree.children.length !== newTree.children.length) {
+ oldTree.children = newTree.children;
+ } else {
+ oldTree.children.forEach(function (oldBranch, i) {
+ var newBranch = newTree.children[i];
+ syncBranch(oldBranch, newBranch);
+ });
+ }
+ };
+
+ var treeId, oldTree, newTree;
+ for (treeId in $scope.trees) {
+ if ($scope.trees.hasOwnProperty(treeId)) {
+ oldTree = $scope.trees[treeId];
+ newTree = trees[treeId];
+ syncBranch(oldTree, newTree);
+ }
+ }
+ }
+
+ $scope.roots.length = roots.length;
+ roots.forEach(function (item, i) {
+ $scope.roots[i] = {
+ label: item,
+ value: item
+ };
+ });
+ if (roots.length === 0) {
+ $scope.selectedRoot = null;
+ } else if (!$scope.selectedRoot) {
+ $scope.selectedRoot = $scope.roots[0].value;
+ }
+ $scope.$apply();
+ };
+
+ appContext.watchPoll(updateTree);
+});
53 js/devtools.js
@@ -0,0 +1,53 @@
+
+// The function below is executed in the context of the inspected page.
+
+var page_getProperties = function () {
+ if (window.angular && $0) {
+ var scope = window.angular.element($0).scope();
+ window.$scope = scope;
+ return (function (scope) {
+ var ret = {
+ __private__: {}
+ };
+
+ for (prop in scope) {
+ if (scope.hasOwnProperty(prop)) {
+ if (prop[0] === '$' && prop[1] === '$') {
+ ret.__private__[prop] = scope[prop];
+ } else {
+ ret[prop] = scope[prop];
+ }
+ }
+ }
+ return ret;
+ }(scope));
+ } else {
+ return {};
+ }
+};
+
+chrome.
+ devtools.
+ panels.
+ elements.
+ createSidebarPane(
+ "AngularJS Properties",
+ function (sidebar) {
+ var selectedElt;
+
+ var updateElementProperties = function () {
+ sidebar.setExpression("(" + page_getProperties.toString() + ")()");
+ }
+
+ updateElementProperties();
+ chrome.devtools.panels.elements.onSelectionChanged.addListener(updateElementProperties);
+ });
+
+// Angular panel
+var angularPanel = chrome.
+ devtools.
+ panels.
+ create(
+ "AngularJS",
+ "img/angular.png",
+ "panel.html");
34 js/directives/mtree.js
@@ -0,0 +1,34 @@
+// model tree
+panelApp.directive('mtree', function($compile) {
+ return {
+ restrict: 'E',
+ terminal: true,
+ scope: {
+ val: '=val',
+ edit: '=edit',
+ inspect: '=inspect'
+ },
+ link: function (scope, element, attrs) {
+ // this is more complicated then it should be
+ // see: https://github.com/angular/angular.js/issues/898
+ element.append(
+ '<div class="scope-branch">' +
+ '<a href ng-click="inspect()">Scope ({{val.id}})</a> | ' +
+ '<a href ng-click="showState = !showState">toggle</a>' +
+ '<div ng-class="{hidden: showState}">' +
+ '<ul>' +
+ '<li ng-repeat="(key, item) in val.locals">' +
+ '{{key}}' +
+ '<input ng-class="{hidden: !item}" ng-model="item" ng-change="edit()()">' +
+ '</li>' +
+ '</ul>' +
+ '<div ng-repeat="child in val.children">' +
+ '<mtree val="child" inspect="inspect" edit="edit"></mtree>' +
+ '</div>' +
+ '</div>' +
+ '</div>');
+
+ $compile(element.contents())(scope.$new());
+ }
+ };
+});
36 js/directives/wtree.js
@@ -0,0 +1,36 @@
+// watchers tree
+panelApp.directive('wtree', function($compile) {
+ return {
+ restrict: 'E',
+ terminal: true,
+ scope: {
+ val: '=val',
+ inspect: '=inspect'
+ },
+ link: function (scope, element, attrs) {
+ // this is more complicated then it should be
+ // see: https://github.com/angular/angular.js/issues/898
+ element.append(
+ '<div class="scope-branch">' +
+ '<a href ng-click="inspect()">Scope ({{val.id}})</a> | ' +
+ '<a href ng-click="showState = !showState">toggle</a>' +
+ '<div ng-class="{hidden: showState}">' +
+ '<ul>' +
+ '<li ng-repeat="item in val.watchers">' +
+ '<a href ng-class="{hidden: item.split(\'\n\').length < 2}" ng-click="showState = !showState">toggle</a> ' +
+ '<span ng-class="{hidden: showState || item.split(\'\n\').length < 2}">{{item | first}} ...</span>' +
+ '<pre ng-class="{hidden: !showState && item.split(\'\n\').length > 1}">' +
+ '{{item}}' +
+ '</pre>' +
+ '</li>' +
+ '</ul>' +
+ '<div ng-repeat="child in val.children">' +
+ '<wtree val="child" inspect="inspect"></wtree>' +
+ '</div>' +
+ '</div>' +
+ '</div>');
+
+ $compile(element.contents())(scope.$new());
+ }
+ };
+});
6 js/filters/first.js
@@ -0,0 +1,6 @@
+// returns the first line of a multi-line string
+panelApp.filter('first', function () {
+ return function (input, output) {
+ return input.split("\n")[0];
+ };
+});
182 js/inject/debug.js
@@ -0,0 +1,182 @@
+var inject = function () {
+ if (document.cookie.indexOf('__ngDebug=true') == -1) {
+ return;
+ }
+ if (document.head) {
+
+ document.head.insertBefore(
+ (function () {
+ var fn = function (window) {
+ //alert('script');
+ var patch = function () {
+ if (window.angular && typeof window.angular.bootstrap === 'function') {
+
+ // do not patch twice
+ if (window.__ngDebug) {
+ return;
+ }
+ //var bootstrap = window.angular.bootstrap;
+ var debug = window.__ngDebug = {
+ watchers: {},
+ timeline: [],
+ watchExp: {},
+ watchList: {}
+ };
+ var ng = angular.module('ng');
+ ng.config(function ($provide) {
+
+ $provide.decorator('$rootScope',
+ function ($delegate) {
+
+ var watchFnToHumanReadableString = function (fn) {
+ if (fn.exp) {
+ return fn.exp.trim();
+ } else if (fn.name) {
+ return fn.name.trim();
+ } else {
+ return fn.toString();
+ }
+ };
+
+ // patch registering watchers
+ // --------------------------
+ var watch = $delegate.__proto__.$watch;
+ $delegate.__proto__.$watch = function() {
+ if (!debug.watchers[this.$id]) {
+ debug.watchers[this.$id] = [];
+ }
+ var str = watchFnToHumanReadableString(arguments[0]);
+
+ debug.watchers[this.$id].push(str);
+
+
+ var w = arguments[0];
+ if (typeof w === 'function') {
+ arguments[0] = function () {
+ var start = window.performance.webkitNow();
+ var ret = w.apply(this, arguments);
+ var end = window.performance.webkitNow();
+ if (!debug.watchExp[str]) {
+ debug.watchExp[str] = {
+ time: 0,
+ calls: 0
+ };
+ }
+ debug.watchExp[str].time += (end - start);
+ debug.watchExp[str].calls += 1;
+ return ret;
+ };
+ } else {
+ var thatScope = this;
+ arguments[0] = function () {
+ var start = window.performance.webkitNow();
+ var ret = thatScope.$eval(w);
+ var end = window.performance.webkitNow();
+ if (!debug.watchExp[str]) {
+ debug.watchExp[str] = {
+ time: 0,
+ calls: 0
+ };
+ }
+ debug.watchExp[str].time += (end - start);
+ debug.watchExp[str].calls += 1;
+ return ret;
+ };
+ }
+
+ var fn = arguments[1];
+ arguments[1] = function () {
+ var start = window.performance.webkitNow();
+ var ret = fn.apply(this, arguments);
+ var end = window.performance.webkitNow();
+ var str = fn.toString();
+ if (typeof debug.watchList[str] !== 'number') {
+ debug.watchList[str] = 0;
+ //debug.watchList[str].total = 0;
+ }
+ debug.watchList[str] += (end - start);
+ //debug.watchList[str].total += (end - start);
+ //debug.dirty = true;
+ return ret;
+ };
+
+ return watch.apply(this, arguments);
+ };
+
+ // patch destroy
+ // -------------
+
+ /*
+ var destroy = $delegate.__proto__.$destroy;
+ $delegate.__proto__.$destroy = function () {
+ if (debug.watchers[this.$id]) {
+ delete debug.watchers[this.$id];
+ }
+ debug.dirty = true;
+ return destroy.apply(this, arguments);
+ };
+ */
+
+ // patch apply
+ // -----------
+ var firstLog = 0;
+ var apply = $delegate.__proto__.$apply;
+ $delegate.__proto__.$apply = function (fn) {
+ var start = window.performance.webkitNow();
+ var ret = apply.apply(this, arguments);
+ var end = window.performance.webkitNow();
+ if (Math.round(end - start) === 0) {
+ if (debug.timeline.length === 0) {
+ firstLog = start;
+ }
+ debug.timeline.push({
+ start: Math.round(start - firstLog),
+ end: Math.round(end - firstLog)
+ });
+ }
+ //debug.dirty = true;
+
+ if (debug.log) {
+ if (fn) {
+ if (fn.name) {
+ fn = fn.name;
+ } else if (fn.toString().split('\n').length > 1) {
+ fn = 'fn () { ' + fn.toString().split('\n')[1].trim() + ' /* ... */ }';
+ } else {
+ fn = fn.toString().trim().substr(0, 30) + '...';
+ }
+ } else {
+ fn = '$apply';
+ }
+ console.log(fn + '\t\t' + (end - start).toPrecision(4) + 'ms');
+ }
+
+ return ret;
+ };
+
+ return $delegate;
+ });
+
+ });
+
+ } else {
+ setTimeout(patch, 1);
+ }
+ };
+
+ patch();
+ };
+
+ var script = window.document.createElement('script');
+ script.innerHTML = '(' + fn.toString() + '(window))';
+
+ return script;
+ }()),
+ document.head.firstChild);
+
+ } else {
+ setTimeout(inject, 1);
+ }
+};
+
+inject();
1,719 js/lib/angular-mocks.js
@@ -0,0 +1,1719 @@
+
+/**
+ * @license AngularJS v"NG_VERSION_FULL"
+ * (c) 2010-2012 Google, Inc. http://angularjs.org
+ * License: MIT
+ *
+ * TODO(vojta): wrap whole file into closure during build
+ */
+
+/**
+ * @ngdoc overview
+ * @name angular.mock
+ * @description
+ *
+ * Namespace from 'angular-mocks.js' which contains testing related code.
+ */
+angular.mock = {};
+
+/**
+ * ! This is a private undocumented service !
+ *
+ * @name ngMock.$browser
+ *
+ * @description
+ * 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 ng.$browser $browser}, except
+ * that there are several helper methods available which can be used in tests.
+ */
+angular.mock.$BrowserProvider = function() {
+ this.$get = function(){
+ return new angular.mock.$Browser();
+ };
+};
+
+angular.mock.$Browser = function() {
+ var self = this;
+
+ 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;
+
+
+ // register url polling fn
+
+ self.onUrlChange = function(listener) {
+ self.pollFns.push(
+ function() {
+ if (self.$$lastUrl != self.$$url) {
+ self.$$lastUrl = self.$$url;
+ listener(self.$$url);
+ }
+ }
+ );
+
+ return listener;
+ };
+
+ 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.now = 0;
+
+
+ self.defer.cancel = function(deferId) {
+ var fnIndex;
+
+ angular.forEach(self.deferredFns, function(fn, index) {
+ if (fn.id === deferId) fnIndex = index;
+ });
+
+ if (fnIndex !== undefined) {
+ self.deferredFns.splice(fnIndex, 1);
+ return true;
+ }
+
+ return false;
+ };
+
+
+ /**
+ * @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 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;
+ },
+
+ 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;
+ }
+ }
+ } 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();
+ }
+};
+
+
+/**
+ * @ngdoc object
+ * @name ngMock.$exceptionHandlerProvider
+ *
+ * @description
+ * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors passed
+ * into the `$exceptionHandler`.
+ */
+
+/**
+ * @ngdoc object
+ * @name ngMock.$exceptionHandler
+ *
+ * @description
+ * 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 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.mode('rethrow');
+};
+
+
+/**
+ * @ngdoc service
+ * @name ngMock.$log
+ *
+ * @description
+ * 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));
+ }
+
+
+ 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 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 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;
+ };
+};
+
+
+(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;
+ }
+ return string;
+ }
+
+ function int(str) {
+ return parseInt(str, 10);
+ }
+
+ 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;
+ }
+
+
+ /**
+ * @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);
+ }
+
+ 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;
+ };
+
+ self.toLocaleDateString = function() {
+ return self.date.toLocaleDateString();
+ };
+
+ self.getFullYear = function() {
+ return self.date.getFullYear();
+ };
+
+ self.getMonth = function() {
+ return self.date.getMonth();
+ };
+
+ self.getDate = function() {
+ return self.date.getDate();
+ };
+
+ self.getHours = function() {
+ return self.date.getHours();
+ };
+
+ self.getMinutes = function() {
+ return self.date.getMinutes();
+ };
+
+ self.getSeconds = function() {
+ return self.date.getSeconds();
+ };
+
+ self.getTimezoneOffset = function() {
+ return offset * 60;
+ };
+
+ self.getUTCFullYear = function() {
+ return self.origDate.getUTCFullYear();
+ };
+
+ self.getUTCMonth = function() {
+ return self.origDate.getUTCMonth();
+ };
+
+ self.getUTCDate = function() {
+ return self.origDate.getUTCDate();
+ };
+
+ self.getUTCHours = function() {
+ return self.origDate.getUTCHours();
+ };
+
+ self.getUTCMinutes = function() {
+ return self.origDate.getUTCMinutes();
+ };
+
+ self.getUTCSeconds = function() {
+ return self.origDate.getUTCSeconds();
+ };
+
+ self.getUTCMilliseconds = function() {
+ return self.origDate.getUTCMilliseconds();
+ };
+
+ self.getDay = function() {
+ return self.date.getDay();
+ };
+
+ // 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'
+ }
+ }
+
+ //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;
+})();
+
+
+/**
+ * @ngdoc function
+ * @name angular.mock.debug
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available function.
+ *
+ * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.
+ *
+ * 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 {string} a serialized string of the argument
+ */
+angular.mock.dump = function(object) {
+ return serialize(object);
+
+ function serialize(object) {
+ var out;
+
+ if (angular.isElement(object)) {
+ object = angular.element(object);
+ out = angular.element('<div></div>');
+ angular.forEach(object, function(element) {
+ out.append(angular.element(element).clone());
+ });
+ out = out.html();
+ } else if (angular.isArray(object)) {
+ out = [];
+ angular.forEach(object, function(o) {
+ out.push(serialize(o));
+ });
+ out = '[ ' + out.join(', ') + ' ]';
+ } else if (angular.isObject(object)) {
+ if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
+ out = serializeScope(object);
+ } else if (object instanceof Error) {
+ out = object.stack || ('' + object.name + ': ' + object.message);
+ } else {
+ out = angular.toJson(object, true);
+ }
+ } else {
+ out = String(object);
+ }
+
+ return out;
+ }
+
+ function serializeScope(scope, offset) {
+ offset = offset || ' ';
+ var log = [offset + 'Scope(' + scope.$id + '): {'];
+ for ( var key in scope ) {
+ if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) {
+ log.push(' ' + key + ': ' + angular.toJson(scope[key]));
+ }
+ }
+ var child = scope.$$childHead;
+ while(child) {
+ log.push(serializeScope(child, offset + ' '));
+ child = child.$$nextSibling;
+ }
+ log.push('}');
+ return log.join('\n' + offset);
+ }
+};
+
+/**
+ * @ngdoc object
+ * @name ngMock.$httpBackend
+ * @description
+ * Fake HTTP backend implementation suitable for unit testing application that use the
+ * {@link ng.$http $http service}.
+ *
+ * *Note*: For fake http backend implementation suitable for end-to-end testing or backend-less
+ * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
+ *
+ * During unit testing, we want our unit tests to run quickly and have no external dependencies so
+ * we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or
+ * {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is
+ * to verify whether a certain request has been sent or not, or alternatively just let the
+ * application make requests, respond with pre-trained responses and assert that the end result is
+ * what we expect it to be.
+ *
+ * This mock implementation can be used to respond with static or dynamic responses via the
+ * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
+ *
+ * When an Angular application needs some data from a server, it calls the $http service, which
+ * sends the request to a real server using $httpBackend service. With dependency injection, it is
+ * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
+ * the requests and respond with some testing data without sending a request to real server.
+ *
+ * There are two ways to specify what test data should be returned as http responses by the mock
+ * backend when the code under test makes http requests:
+ *
+ * - `$httpBackend.expect` - specifies a request expectation
+ * - `$httpBackend.when` - specifies a backend definition
+ *
+ *
+ * # Request Expectations vs Backend Definitions
+ *
+ * Request expectations provide a way to make assertions about requests made by the application and
+ * to define responses for those requests. The test will fail if the expected requests are not made
+ * or they are made in the wrong order.
+ *
+ * Backend definitions allow you to define a fake backend for your application which doesn't assert
+ * if a particular request was made or not, it just returns a trained response if a request is made.
+ * The test will pass whether or not the request gets made during testing.
+ *
+ *
+ * <table class="table">
+ * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
+ * <tr>
+ * <th>Syntax</th>
+ * <td>.expect(...).respond(...)</td>
+ * <td>.when(...).respond(...)</td>
+ * </tr>
+ * <tr>
+ * <th>Typical usage</th>
+ * <td>strict unit tests</td>
+ * <td>loose (black-box) unit testing</td>
+ * </tr>
+ * <tr>
+ * <th>Fulfills multiple requests</th>
+ * <td>NO</td>
+ * <td>YES</td>
+ * </tr>
+ * <tr>
+ * <th>Order of requests matters</th>
+ * <td>YES</td>
+ * <td>NO</td>
+ * </tr>
+ * <tr>
+ * <th>Request required</th>
+ * <td>YES</td>
+ * <td>NO</td>
+ * </tr>
+ * <tr>
+ * <th>Response required</th>
+ * <td>optional (see below)</td>
+ * <td>YES</td>
+ * </tr>
+ * </table>
+ *
+ * In cases where both backend definitions and request expectations are specified during unit
+ * testing, the request expectations are evaluated first.
+ *
+ * If a request expectation has no response specified, the algorithm will search your backend
+ * definitions for an appropriate response.
+ *
+ * If a request didn't match any expectation or if the expectation doesn't have the response
+ * defined, the backend definitions are evaluated in sequential order to see if any of them match
+ * the request. The response from the first matched definition is returned.
+ *
+ *
+ * # Flushing HTTP requests
+ *
+ * The $httpBackend used in production, always responds to requests with responses asynchronously.
+ * If we preserved this behavior in unit testing, we'd have to create async unit tests, which are
+ * hard to write, follow and maintain. At the same time the testing mock, can't respond
+ * synchronously because that would change the execution of the code under test. For this reason the
+ * mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending
+ * requests and thus preserving the async api of the backend, while allowing the test to execute
+ * synchronously.
+ *
+ *
+ * # Unit testing with mock $httpBackend
+ *
+ * <pre>
+ // controller
+ function MyController($scope, $http) {
+ $http.get('/auth.py').success(function(data) {
+ $scope.user = data;
+ });
+
+ this.saveMessage = function(message) {
+ $scope.status = 'Saving...';
+ $http.post('/add-msg.py', message).success(function(response) {
+ $scope.status = '';
+ }).error(function() {
+ $scope.status = 'ERROR!';
+ });
+ };
+ }
+
+ // testing controller
+ var $http;
+
+ beforeEach(inject(function($injector) {
+ $httpBackend = $injector.get('$httpBackend');
+
+ // backend definition common for all tests
+ $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
+ }));
+
+
+ afterEach(function() {
+ $httpBackend.verifyNoOutstandingExpectation();
+ $httpBackend.verifyNoOutstandingRequest();
+ });
+
+
+ it('should fetch authentication token', function() {
+ $httpBackend.expectGET('/auth.py');
+ var controller = scope.$new(MyController);
+ $httpBackend.flush();
+ });
+
+
+ it('should send msg to server', function() {
+ // now you don’t care about the authentication, but
+ // the controller will still send the request and
+ // $httpBackend will respond without you having to
+ // specify the expectation and response for this request
+ $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
+
+ var controller = scope.$new(MyController);
+ $httpBackend.flush();
+ controller.saveMessage('message content');
+ expect(controller.status).toBe('Saving...');
+ $httpBackend.flush();
+ expect(controller.status).toBe('');
+ });
+
+
+ it('should send auth header', function() {
+ $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
+ // check if the header was send, if it wasn't the expectation won't
+ // match the request and the test will fail
+ return headers['Authorization'] == 'xxx';
+ }).respond(201, '');
+
+ var controller = scope.$new(MyController);
+ controller.saveMessage('whatever');
+ $httpBackend.flush();
+ });
+ </pre>
+ */
+angular.mock.$HttpBackendProvider = function() {
+ this.$get = [createHttpBackendMock];
+};
+
+/**
+ * General factory function for $httpBackend mock.
+ * Returns instance for unit testing (when no arguments specified):
+ * - passing through is disabled
+ * - auto flushing is disabled
+ *
+ * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
+ * - passing through (delegating request to real backend) is enabled
+ * - auto flushing is enabled
+ *
+ * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
+ * @param {Object=} $browser Auto-flushing enabled if specified
+ * @return {Object} Instance of $httpBackend mock
+ */
+function createHttpBackendMock($delegate, $browser) {
+ var definitions = [],
+ expectations = [],
+ responses = [],
+ responsesPush = angular.bind(responses, responses.push);
+
+ function createResponse(status, data, headers) {
+ if (angular.isFunction(status)) return status;
+
+ return function() {
+ return angular.isNumber(status)
+ ? [status, data, headers]
+ : [200, status, data];
+ };
+ }
+
+ // TODO(vojta): change params to: method, url, data, headers, callback
+ function $httpBackend(method, url, data, callback, headers) {
+ var xhr = new MockXhr(),
+ expectation = expectations[0],
+ wasExpected = false;
+
+ function prettyPrint(data) {
+ return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
+ ? data
+ : angular.toJson(data);
+ }
+
+ if (expectation && expectation.match(method, url)) {
+ if (!expectation.matchData(data))
+ throw Error('Expected ' + expectation + ' with different data\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
+
+ if (!expectation.matchHeaders(headers))
+ throw Error('Expected ' + expectation + ' with different headers\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
+ prettyPrint(headers));
+
+ expectations.shift();
+
+ if (expectation.response) {
+ responses.push(function() {
+ var response = expectation.response(method, url, data, headers);
+ xhr.$$respHeaders = response[2];
+ callback(response[0], response[1], xhr.getAllResponseHeaders());
+ });
+ return;
+ }
+ wasExpected = true;
+ }
+
+ var i = -1, definition;
+ while ((definition = definitions[++i])) {
+ if (definition.match(method, url, data, headers || {})) {
+ if (definition.response) {
+ // if $browser specified, we do auto flush all requests
+ ($browser ? $browser.defer : responsesPush)(function() {
+ var response = definition.response(method, url, data, headers);
+ xhr.$$respHeaders = response[2];
+ callback(response[0], response[1], xhr.getAllResponseHeaders());
+ });
+ } else if (definition.passThrough) {
+ $delegate(method, url, data, callback, headers);
+ } else throw Error('No response defined !');
+ return;
+ }
+ }
+ throw wasExpected ?
+ Error('No response defined !') :
+ Error('Unexpected request: ' + method + ' ' + url + '\n' +
+ (expectation ? 'Expected ' + expectation : 'No more request expected'));
+ }
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#when
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current definition.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ *
+ * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string) and response headers
+ * (Object).
+ */
+ $httpBackend.when = function(method, url, data, headers) {
+ var definition = new MockHttpExpectation(method, url, data, headers),
+ chain = {
+ respond: function(status, data, headers) {
+ definition.response = createResponse(status, data, headers);
+ }
+ };
+
+ if ($browser) {
+ chain.passThrough = function() {
+ definition.passThrough = true;
+ };
+ }
+
+ definitions.push(definition);
+ return chain;
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenGET
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for GET requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenHEAD
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenDELETE
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenPOST
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for POST requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenPUT
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenJSONP
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+ createShortMethods('when');
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expect
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current expectation.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ *
+ * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string) and response headers
+ * (Object).
+ */
+ $httpBackend.expect = function(method, url, data, headers) {
+ var expectation = new MockHttpExpectation(method, url, data, headers);
+ expectations.push(expectation);
+ return {
+ respond: function(status, data, headers) {
+ expectation.response = createResponse(status, data, headers);
+ }
+ };
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectGET
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for GET requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled. See #expect for more info.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectHEAD
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for HEAD requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectDELETE
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for DELETE requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectPOST
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for POST requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectPUT
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for PUT requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectPATCH
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for PATCH requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectJSONP
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for JSONP requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+ createShortMethods('expect');
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#flush
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Flushes all pending requests using the trained responses.
+ *
+ * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
+ * all pending requests will be flushed. If there are no pending requests when the flush method
+ * is called an exception is thrown (as this typically a sign of programming error).
+ */
+ $httpBackend.flush = function(count) {
+ if (!responses.length) throw Error('No pending request to flush !');
+
+ if (angular.isDefined(count)) {
+ while (count--) {
+ if (!responses.length) throw Error('No more pending request to flush !');
+ responses.shift()();
+ }
+ } else {
+ while (responses.length) {
+ responses.shift()();
+ }
+ }
+ $httpBackend.verifyNoOutstandingExpectation();
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#verifyNoOutstandingExpectation
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Verifies that all of the requests defined via the `expect` api were made. If any of the
+ * requests were not made, verifyNoOutstandingExpectation throws an exception.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ * <pre>
+ * afterEach($httpBackend.verifyExpectations);
+ * </pre>
+ */
+ $httpBackend.verifyNoOutstandingExpectation = function() {
+ if (expectations.length) {
+ throw Error('Unsatisfied requests: ' + expectations.join(', '));
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#verifyNoOutstandingRequest
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Verifies that there are no outstanding requests that need to be flushed.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ * <pre>
+ * afterEach($httpBackend.verifyNoOutstandingRequest);
+ * </pre>
+ */
+ $httpBackend.verifyNoOutstandingRequest = function() {
+ if (responses.length) {
+ throw Error('Unflushed requests: ' + responses.length);
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#resetExpectations
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Resets all request expectations, but preserves all backend definitions. Typically, you would
+ * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
+ * $httpBackend mock.
+ */
+ $httpBackend.resetExpectations = function() {
+ expectations.length = 0;
+ responses.length = 0;
+ };
+
+ return $httpBackend;
+
+
+ function createShortMethods(prefix) {
+ angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
+ $httpBackend[prefix + method] = function(url, headers) {
+ return $httpBackend[prefix](method, url, undefined, headers)
+ }
+ });
+
+ angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
+ $httpBackend[prefix + method] = function(url, data, headers) {
+ return $httpBackend[prefix](method, url, data, headers)
+ }
+ });
+ }
+}
+
+function MockHttpExpectation(method, url, data, headers) {
+
+ this.data = data;
+ this.headers = headers;
+
+ this.match = function(m, u, d, h) {
+ if (method != m) return false;
+ if (!this.matchUrl(u)) return false;
+ if (angular.isDefined(d) && !this.matchData(d)) return false;
+ if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
+ return true;
+ };
+
+ this.matchUrl = function(u) {
+ if (!url) return true;
+ if (angular.isFunction(url.test)) return url.test(u);
+ return url == u;
+ };
+
+ this.matchHeaders = function(h) {
+ if (angular.isUndefined(headers)) return true;
+ if (angular.isFunction(headers)) return headers(h);
+ return angular.equals(headers, h);
+ };
+
+ this.matchData = function(d) {
+ if (angular.isUndefined(data)) return true;
+ if (data && angular.isFunction(data.test)) return data.test(d);
+ if (data && !angular.isString(data)) return angular.toJson(data) == d;
+ return data == d;
+ };
+
+ this.toString = function() {
+ return method + ' ' + url;
+ };
+}
+
+function MockXhr() {
+
+ // hack for testing $http, $httpBackend
+ MockXhr.$$lastInstance = this;
+
+ this.open = function(method, url, async) {
+ this.$$method = method;
+ this.$$url = url;
+ this.$$async = async;
+ this.$$reqHeaders = {};
+ this.$$respHeaders = {};
+ };
+
+ this.send = function(data) {
+ this.$$data = data;
+ };
+
+ this.setRequestHeader = function(key, value) {
+ this.$$reqHeaders[key] = value;
+ };
+
+ this.getResponseHeader = function(name) {
+ // the lookup must be case insensitive, that's why we try two quick lookups and full scan at last
+ var header = this.$$respHeaders[name];
+ if (header) return header;
+
+ name = angular.lowercase(name);
+ header = this.$$respHeaders[name];
+ if (header) return header;
+
+ header = undefined;
+ angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
+ if (!header && angular.lowercase(headerName) == name) header = headerVal;
+ });
+ return header;
+ };
+
+ this.getAllResponseHeaders = function() {
+ var lines = [];
+
+ angular.forEach(this.$$respHeaders, function(value, key) {
+ lines.push(key + ': ' + value);
+ });
+ return lines.join('\n');
+ };
+
+ this.abort = angular.noop;
+}
+
+
+/**
+ * @ngdoc function
+ * @name ngMock.$timeout
+ * @description
+ *
+ * This service is just a simple decorator for {@link ng.$timeout $timeout} service
+ * that adds a "flush" method.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMock.$timeout#flush
+ * @methodOf ngMock.$timeout
+ * @description