diff --git a/.gitignore b/.gitignore index 7a1537ba..aa461ff9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .idea node_modules +bower_components \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 47430c17..79bda212 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,12 +5,13 @@ before_script: - export DISPLAY=:99.0 - sh -e /etc/init.d/xvfb start - - npm install -g grunt-cli@0.1.x karma@0.8.x + - npm install -g gulp karma bower - cd server - npm install --quiet - node server.js & - sleep 3 # give server some time to start - cd ../client - npm install --quiet + - bower install --quiet - script: grunt release + script: gulp diff --git a/README.md b/README.md index 27a8e0cf..d25f1f61 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ ## Purpose -The idea is to **demonstrate how to write a typical, non-trivial CRUD application using AngularJS**. To showcase AngularJS in its most advantageous environment we've set out to write a simplified project management tool supporting teams using the SCRUM methodology. The sample application tries to show best practices when it comes to: folders structure, using modules, testing, communicating with a REST back-end, organizing navigation, addressing security concerns (authentication / authorization). +The idea is to **demonstrate how to write a typical, non-trivial [CRUD](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete) application using AngularJS**. To showcase AngularJS in its most advantageous environment we've set out to write a simplified project management tool supporting teams using the [SCRUM](http://en.wikipedia.org/wiki/Scrum_(software_development)) methodology. The sample application tries to show best practices when it comes to: folders structure, using modules, testing, communicating with a REST back-end, organizing navigation, addressing security concerns (authentication / authorization). This sample application is featured in our [book](http://goo.gl/gKEsIo) where you can find detailed description of the patterns and techniques used to write this code: @@ -19,16 +19,15 @@ We've learned a lot while using and supporting AngularJS on the [mailing list](h * Persistence store: [MongoDB](http://www.mongodb.org/) hosted on [MongoLab](https://mongolab.com/) * Backend: [Node.js](http://nodejs.org/) * Awesome [AngularJS](http://www.angularjs.org/) on the client -* CSS based on [Twitter's bootstrap](http://getbootstrap.com/) +* CSS based on [Bootstrap](http://getbootstrap.com/) ### Build It is a complete project with a build system focused on AngularJS apps and tightly integrated with other tools commonly used in the AngularJS community: -* powered by [Grunt.js](http://gruntjs.com/) +* powered by [gulp.js](http://gulpjs.com/) * test written using [Jasmine](http://jasmine.github.io/) syntax -* test are executed by [Karma Test Runner](http://karma-runner.github.io/0.8/index.html) (integrated with the Grunt.js build) +* test are executed by [Karma Test Runner](http://karma-runner.github.io/) (integrated with the gulp.js build) * build supporting JS, CSS and AngularJS templates minification -* [Twitter's bootstrap](http://getbootstrap.com/) with LESS templates processing integrated into the build * [Travis-CI](https://travis-ci.org/) integration ## Installation @@ -37,14 +36,12 @@ It is a complete project with a build system focused on AngularJS apps and tight You need to install Node.js and then the development tools. Node.js comes with a package manager called [npm](http://npmjs.org) for installing NodeJS applications and libraries. * [Install node.js](http://nodejs.org/download/) (requires node.js version >= 0.8.4) -* Install Grunt-CLI and Karma as global npm modules: +* Install gulp and Karma runner as global npm modules: ``` - npm install -g grunt-cli karma + npm install -g gulp karma ``` -(Note that you may need to uninstall grunt 0.3 globally before installing grunt-cli) - ### Get the Code Either clone this repository or fork it on GitHub and clone your fork: @@ -71,7 +68,7 @@ Our backend application server is a NodeJS application that relies upon some 3rd ### Client App Our client application is a straight HTML/Javascript application but our development process uses a Node.js build tool -[Grunt.js](gruntjs.com). Grunt relies upon some 3rd party libraries that we need to install as local dependencies using npm. +[gulp.js](gulpjs.com). gulp relies upon some 3rd party libraries that we need to install as local dependencies using npm. * Install local dependencies (from the project root folder): @@ -129,12 +126,12 @@ angular.module('app').constant('MONGOLAB_CONFIG', { ``` ### Build the client app -The app made up of a number of javascript, css and html files that need to be merged into a final distribution for running. We use the Grunt build tool to do this. +The app made up of a number of javascript, css and html files that need to be merged into a final distribution for running. We use the gulp build tool to do this. * Build client application: ``` cd client - grunt build + gulp cd .. ``` @@ -163,37 +160,26 @@ testing against browsers that you need to support. ### Folders structure At the top level, the repository is split into a client folder and a server folder. The client folder contains all the client-side AngularJS application. The server folder contains a very basic Express based webserver that delivers and supports the application. Within the client folder you have the following structure: -* `node_modules` contains build tasks for Grunt along with other, user-installed, Node packages +* `node_modules` contains build tasks for gulp along with other, user-installed, Node packages * `dist` contains build results * `src` contains application's sources * `test` contains test sources, configuration and dependencies * `vendor` contains external dependencies for the application ### Default Build -The default grunt task will build (checks the javascript (lint), runs the unit tests (test:unit) and builds distributable files) and run all unit tests: `grunt` (or `grunt.cmd` on Windows). The tests are run by karma and need one or more browsers open to actually run the tests. +The default gulp task will build (checks the javascript (`lint`), runs the unit tests (`test``) and builds distributable files: * `cd client` -* `grunt` -* Open one or more browsers and point them to [http://localhost:8080/__test/]. Once the browsers connect the tests will run and the build will complete. -* If you leave the browsers open at this url then future runs of `grunt` will automatically run the tests against these browsers. +* `gulp` ### Continuous Building -The watch grunt task will monitor the source files and run the default build task every time a file changes: `grunt watch`. +The watch gulp task will monitor the source files and run the default build task every time a file changes: `gulp watch`. ### Build without tests -If for some reason you don't want to run the test but just generate the files - not a good idea(!!) - you can simply run the build task: `grunt build`. - -### Building release code -You can build a release version of the app, with minified files. This task will also run the "end to end" (e2e) tests. -The e2e tests require the server to be started and also one or more browsers open to run the tests. (You can use the same browsers as for the unit tests.) -* `cd client` -* Run `grunt release` -* Open one or more browsers and point them to [http://localhost:8080/__test/]. Once the browsers connect the tests will run and the build will complete. -* If you leave the browsers open at this url then future runs of `grunt` will automatically run the tests against these browsers. +If for some reason you don't want to run the test but just generate the files - not a good idea(!!) - you can simply run the build task: `gulp build`. ### Continuous testing -You can have grunt (karma) continuously watch for file changes and automatically run all the tests on every change, without rebuilding the distribution files. This can make the test run faster when you are doing test driven development and don't need to actually run the application itself. +You can have gulp (karma) continuously watch for file changes and automatically run all the tests on every change, without rebuilding the distribution files. This can make the test run faster when you are doing test driven development and don't need to actually run the application itself. * `cd client` -* Run `grunt test-watch`. -* Open one or more browsers and point them to [http://localhost:8080/__test/]. -* Each time a file changes the tests will be run against each browser. +* Run `gulp tdd`. In the default configuration it will start a new instance of Chrome. +* The task will wait for code changes, re-executing tests on each change. \ No newline at end of file diff --git a/client/bower.json b/client/bower.json new file mode 100644 index 00000000..74608c65 --- /dev/null +++ b/client/bower.json @@ -0,0 +1,26 @@ +{ + "name": "angular-app", + "version": "0.0.0", + "homepage": "https://github.com/angular-app/angular-app", + "authors": [ + "Pawel Kozlowski & Peter Bacon Darwin" + ], + "description": "a simplified project management tool supporting teams using the SCRUM methodology - demonstrating AngularJS", + "license": "MIT", + "private": true, + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ], + "dependencies": { + "angularjs": "~1.3.0", + "angular-route": "~1.3.0", + "angular-mocks": "~1.3.0", + "jquery": "~2.1.1", + "angularjs-mongolab": "*", + "angular-bootstrap": "~0.11.0" + } +} diff --git a/client/gruntFile.js b/client/gruntFile.js deleted file mode 100644 index 3eb736d3..00000000 --- a/client/gruntFile.js +++ /dev/null @@ -1,182 +0,0 @@ -module.exports = function (grunt) { - - grunt.loadNpmTasks('grunt-contrib-concat'); - grunt.loadNpmTasks('grunt-contrib-jshint'); - grunt.loadNpmTasks('grunt-contrib-uglify'); - grunt.loadNpmTasks('grunt-contrib-clean'); - grunt.loadNpmTasks('grunt-contrib-copy'); - grunt.loadNpmTasks('grunt-contrib-watch'); - grunt.loadNpmTasks('grunt-recess'); - grunt.loadNpmTasks('grunt-karma'); - grunt.loadNpmTasks('grunt-html2js'); - - // Default task. - grunt.registerTask('default', ['jshint','build','karma:unit']); - grunt.registerTask('build', ['clean','html2js','concat','recess:build','copy:assets']); - grunt.registerTask('release', ['clean','html2js','uglify','jshint','karma:unit','concat:index', 'recess:min','copy:assets']); - grunt.registerTask('test-watch', ['karma:watch']); - - // Print a timestamp (useful for when watching) - grunt.registerTask('timestamp', function() { - grunt.log.subhead(Date()); - }); - - var karmaConfig = function(configFile, customOptions) { - var options = { configFile: configFile, keepalive: true }; - var travisOptions = process.env.TRAVIS && { browsers: ['Firefox'], reporters: 'dots' }; - return grunt.util._.extend(options, customOptions, travisOptions); - }; - - // Project configuration. - grunt.initConfig({ - distdir: 'dist', - pkg: grunt.file.readJSON('package.json'), - banner: - '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + - '<%= pkg.homepage ? " * " + pkg.homepage + "\\n" : "" %>' + - ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>;\n' + - ' * Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %>\n */\n', - src: { - js: ['src/**/*.js'], - jsTpl: ['<%= distdir %>/templates/**/*.js'], - specs: ['test/**/*.spec.js'], - scenarios: ['test/**/*.scenario.js'], - html: ['src/index.html'], - tpl: { - app: ['src/app/**/*.tpl.html'], - common: ['src/common/**/*.tpl.html'] - }, - less: ['src/less/stylesheet.less'], // recess:build doesn't accept ** in its file patterns - lessWatch: ['src/less/**/*.less'] - }, - clean: ['<%= distdir %>/*'], - copy: { - assets: { - files: [{ dest: '<%= distdir %>', src : '**', expand: true, cwd: 'src/assets/' }] - } - }, - karma: { - unit: { options: karmaConfig('test/config/unit.js') }, - watch: { options: karmaConfig('test/config/unit.js', { singleRun:false, autoWatch: true}) } - }, - html2js: { - app: { - options: { - base: 'src/app' - }, - src: ['<%= src.tpl.app %>'], - dest: '<%= distdir %>/templates/app.js', - module: 'templates.app' - }, - common: { - options: { - base: 'src/common' - }, - src: ['<%= src.tpl.common %>'], - dest: '<%= distdir %>/templates/common.js', - module: 'templates.common' - } - }, - concat:{ - dist:{ - options: { - banner: "<%= banner %>" - }, - src:['<%= src.js %>', '<%= src.jsTpl %>'], - dest:'<%= distdir %>/<%= pkg.name %>.js' - }, - index: { - src: ['src/index.html'], - dest: '<%= distdir %>/index.html', - options: { - process: true - } - }, - angular: { - src:['vendor/angular/angular.js', 'vendor/angular/angular-route.js'], - dest: '<%= distdir %>/angular.js' - }, - mongo: { - src:['vendor/mongolab/*.js'], - dest: '<%= distdir %>/mongolab.js' - }, - bootstrap: { - src:['vendor/angular-ui/bootstrap/*.js'], - dest: '<%= distdir %>/bootstrap.js' - }, - jquery: { - src:['vendor/jquery/*.js'], - dest: '<%= distdir %>/jquery.js' - } - }, - uglify: { - dist:{ - options: { - banner: "<%= banner %>" - }, - src:['<%= src.js %>' ,'<%= src.jsTpl %>'], - dest:'<%= distdir %>/<%= pkg.name %>.js' - }, - angular: { - src:['<%= concat.angular.src %>'], - dest: '<%= distdir %>/angular.js' - }, - mongo: { - src:['vendor/mongolab/*.js'], - dest: '<%= distdir %>/mongolab.js' - }, - bootstrap: { - src:['vendor/angular-ui/bootstrap/*.js'], - dest: '<%= distdir %>/bootstrap.js' - }, - jquery: { - src:['vendor/jquery/*.js'], - dest: '<%= distdir %>/jquery.js' - } - }, - recess: { - build: { - files: { - '<%= distdir %>/<%= pkg.name %>.css': - ['<%= src.less %>'] }, - options: { - compile: true - } - }, - min: { - files: { - '<%= distdir %>/<%= pkg.name %>.css': ['<%= src.less %>'] - }, - options: { - compress: true - } - } - }, - watch:{ - all: { - files:['<%= src.js %>', '<%= src.specs %>', '<%= src.lessWatch %>', '<%= src.tpl.app %>', '<%= src.tpl.common %>', '<%= src.html %>'], - tasks:['default','timestamp'] - }, - build: { - files:['<%= src.js %>', '<%= src.specs %>', '<%= src.lessWatch %>', '<%= src.tpl.app %>', '<%= src.tpl.common %>', '<%= src.html %>'], - tasks:['build','timestamp'] - } - }, - jshint:{ - files:['gruntFile.js', '<%= src.js %>', '<%= src.jsTpl %>', '<%= src.specs %>', '<%= src.scenarios %>'], - options:{ - curly:true, - eqeqeq:true, - immed:true, - latedef:true, - newcap:true, - noarg:true, - sub:true, - boss:true, - eqnull:true, - globals:{} - } - } - }); - -}; diff --git a/client/gulpfile.js b/client/gulpfile.js new file mode 100644 index 00000000..70709d65 --- /dev/null +++ b/client/gulpfile.js @@ -0,0 +1,161 @@ +var gulp = require('gulp'); +var templateCache = require('gulp-angular-templatecache'); +var jshint = require('gulp-jshint'); +var concat = require('gulp-concat'); +var uglify = require('gulp-uglify'); +var template = require('gulp-template'); +var header = require('gulp-header'); +var htmlmin = require('gulp-htmlmin'); + +var merge = require('merge-stream'); +var rimraf = require('rimraf'); +var _ = require('lodash'); + +var karma = require('karma').server; + +var package = require('./package.json'); + +var karmaCommonConf = { + browsers: process.env.TRAVIS ? ['SL_Chrome', 'SL_Firefox', 'SL_Safari', 'SL_IE_11'] : ['Chrome'], + customLaunchers: { + 'SL_Chrome': { + base: 'SauceLabs', + browserName: 'chrome', + platform: 'Linux', + version: '36' + }, + 'SL_Firefox': { + base: 'SauceLabs', + browserName: 'firefox', + platform: 'Linux', + version: '31' + }, + 'SL_Safari': { + base: 'SauceLabs', + browserName: 'safari', + platform: 'OS X 10.9', + version: '7' + }, + 'SL_IE_11': { + base: 'SauceLabs', + browserName: 'internet explorer', + platform: 'Windows 8.1', + version: '11' + } + }, + frameworks: ['jasmine'], + preprocessors: { + 'src/**/*.tpl.html': ['ng-html2js'] + }, + files: [ + 'bower_components/jquery/dist/jquery.js', + 'bower_components/angular/angular.js', + 'bower_components/angular-route/angular-route.js', + 'bower_components/angularjs-mongolab/src/angular-mongolab.js', + 'bower_components/angular-mocks/angular-mocks.js', + 'bower_components/angular-bootstrap/ui-bootstrap-tpls.js', + 'src/**/*.tpl.html', + 'src/**/*.js', + 'test/unit/**/*.spec.js' + ], + reporters: process.env.TRAVIS ? ['dots', 'saucelabs'] : ['progress'], + ngHtml2JsPreprocessor: { + cacheIdFromPath: function(filepath) { + //cut off src/common/ and src/app/ prefixes, if present + //we do this so in directives we can refer to templates in a way + //that those templates can be served by a web server during dev time + //without any need to bundle them + return filepath.replace('src/common/', '').replace('src/app/', ''); + } + }, + sauceLabs: { + username: 'pkozlowski', + accessKey: '173aa66e-43e6-4e34-b873-9cb037b8ae5c', + testName: 'angular-app tests' + } +}; + + +gulp.task('build-index', function () { + return gulp.src('src/index.html') + .pipe(template({ + pkg: package, + year: new Date() + })) + .pipe(gulp.dest('dist')); +}); + +gulp.task('build-js', function () { + + var now = new Date(); + + var htmlMinOpts = { + collapseWhitespace: true, + conservativeCollapse: true + }; + + return merge( + gulp.src('src/**/*.js'), + gulp.src('src/app/**/*.tpl.html').pipe(htmlmin(htmlMinOpts)).pipe(templateCache({standalone: true, module: 'templates.app'})), + gulp.src('src/common/**/*.tpl.html').pipe(htmlmin(htmlMinOpts)).pipe(templateCache({standalone: true, module: 'templates.common'})) + ).pipe(concat(package.name + '.js')) + .pipe(uglify()) + .pipe(header( + '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - <%= buildDate %>\n' + + '<%= pkg.homepage ? " * " + pkg.homepage + "\\n" : "" %>' + + ' * Copyright (c) <%= copyrightYear %> <%= pkg.author %>;\n' + + ' * Licensed <%= pkg.licenses[0].type %>\n */\n', + { + pkg: package, + buildDate: now, + copyrightYear: now.getFullYear() + })) + .pipe(gulp.dest('dist')); +}); + +gulp.task('copy-static', function () { + return merge( + gulp.src('src/assets/**/*.*'), + gulp.src(['bower_components/angular/angular.js', 'bower_components/angular-route/angular-route.js']).pipe(concat('angular.js')), + gulp.src('bower_components/angular-bootstrap/ui-bootstrap-tpls.js'), + gulp.src('bower_components/jquery/dist/jquery.js'), + gulp.src('bower_components/angularjs-mongolab/src/*.js') + ).pipe(gulp.dest('dist')); +}); + +gulp.task('clean', function (done) { + return rimraf('dist', done); +}); + +gulp.task('lint', function () { + return gulp.src(['src/**/*.js', 'test/unit/**/*.js']).pipe(jshint()) + .pipe(jshint.reporter('default')) + .pipe(jshint.reporter('fail')); +}); + +gulp.task('test', function (done) { + karma.start(_.assign({}, karmaCommonConf, {singleRun: true}), done); +}); + +gulp.task('tdd', function (done) { + karma.start(karmaCommonConf, done); +}); + +gulp.task('watch', ['lint', 'build'], function () { + + gulp.watch('src/**/*.js', ['lint', 'build-js']); + gulp.watch('src/**/*.tpl.html', ['build-js']); + gulp.watch('src/index.html', ['build-index']); + gulp.watch('src/assets/**/*.*', ['copy-static']); + +}); + +gulp.task('build', ['copy-static', 'build-index', 'build-js']); +gulp.task('default', ['lint', 'test', 'build']); + +/* +TODO: +- watch shouldn't break on errors +- don't uglify / HTML minifiy during watch +- live-reload + */ \ No newline at end of file diff --git a/client/package.json b/client/package.json index 703954e9..e406d437 100644 --- a/client/package.json +++ b/client/package.json @@ -19,17 +19,23 @@ "engines": { "node": ">= 0.8.4" }, - "dependencies": {}, "devDependencies": { - "grunt": "~0.4.0", - "grunt-recess": "~0.3", - "grunt-contrib-clean": "~0.4.0", - "grunt-contrib-copy": "~0.4.0", - "grunt-contrib-jshint": "~0.2.0", - "grunt-contrib-concat": "~0.1.3", - "grunt-contrib-uglify": "~0.1.1", - "grunt-karma": "~0.4.4", - "grunt-html2js": "~0.1.0", - "grunt-contrib-watch": "~0.3.1" + "lodash": "~2.4.1", + "merge-stream": "~0.1.5", + "rimraf": "~2.2.8", + "karma": "~0.12.17", + "karma-jasmine": "~0.1.5", + "karma-ng-html2js-preprocessor": "~0.1.0", + "karma-chrome-launcher": "~0.1.4", + "karma-firefox-launcher": "~0.1.3", + "karma-sauce-launcher": "~0.2.10", + "gulp": "~3.8.6", + "gulp-angular-templatecache": "~1.2.1", + "gulp-concat": "~2.3.3", + "gulp-uglify": "~0.3.1", + "gulp-jshint": "~1.7.1", + "gulp-template": "~0.1.1", + "gulp-header": "~1.0.5", + "gulp-htmlmin": "~0.1.3" } } diff --git a/client/src/app/app.js b/client/src/app/app.js index 3e630dcf..73bb52ef 100644 --- a/client/src/app/app.js +++ b/client/src/app/app.js @@ -10,11 +10,12 @@ angular.module('app', [ 'security', 'directives.crud', 'templates.app', - 'templates.common']); + 'templates.common', + 'ui.bootstrap.tpls']); angular.module('app').constant('MONGOLAB_CONFIG', { - baseUrl: '/databases/', - dbName: 'ascrum' + BASE_URL: '/databases/', + DB_NAME: 'ascrum' }); //TODO: move those messages to a separate module diff --git a/client/src/assets/img/glyphicons-halflings-white.png b/client/src/assets/img/glyphicons-halflings-white.png deleted file mode 100644 index 3bf6484a..00000000 Binary files a/client/src/assets/img/glyphicons-halflings-white.png and /dev/null differ diff --git a/client/src/assets/img/glyphicons-halflings.png b/client/src/assets/img/glyphicons-halflings.png deleted file mode 100644 index a9969993..00000000 Binary files a/client/src/assets/img/glyphicons-halflings.png and /dev/null differ diff --git a/client/src/common/resources/backlog.js b/client/src/common/resources/backlog.js index 98770b00..b31bf646 100644 --- a/client/src/common/resources/backlog.js +++ b/client/src/common/resources/backlog.js @@ -1,6 +1,6 @@ -angular.module('resources.productbacklog', ['mongolabResource']); -angular.module('resources.productbacklog').factory('ProductBacklog', ['mongolabResource', function (mongolabResource) { - var ProductBacklog = mongolabResource('productbacklog'); +angular.module('resources.productbacklog', ['mongolabResourceHttp']); +angular.module('resources.productbacklog').factory('ProductBacklog', ['$mongolabResourceHttp', function ($mongolabResourceHttp) { + var ProductBacklog = $mongolabResourceHttp('productbacklog'); ProductBacklog.forProject = function (projectId) { return ProductBacklog.query({projectId:projectId}); diff --git a/client/src/common/resources/projects.js b/client/src/common/resources/projects.js index 998cd3cb..a35a3e5a 100644 --- a/client/src/common/resources/projects.js +++ b/client/src/common/resources/projects.js @@ -1,7 +1,7 @@ -angular.module('resources.projects', ['mongolabResource']); -angular.module('resources.projects').factory('Projects', ['mongolabResource', function ($mongolabResource) { +angular.module('resources.projects', ['mongolabResourceHttp']); +angular.module('resources.projects').factory('Projects', ['$mongolabResourceHttp', function ($mongolabResourceHttp) { - var Projects = $mongolabResource('projects'); + var Projects = $mongolabResourceHttp('projects'); Projects.forUser = function(userId, successcb, errorcb) { //TODO: get projects for this user only (!) diff --git a/client/src/common/resources/sprints.js b/client/src/common/resources/sprints.js index 6d3fb827..6bd987eb 100644 --- a/client/src/common/resources/sprints.js +++ b/client/src/common/resources/sprints.js @@ -1,7 +1,7 @@ -angular.module('resources.sprints', ['mongolabResource']); -angular.module('resources.sprints').factory('Sprints', ['mongolabResource', function (mongolabResource) { +angular.module('resources.sprints', ['mongolabResourceHttp']); +angular.module('resources.sprints').factory('Sprints', ['$mongolabResourceHttp', function ($mongolabResourceHttp) { - var Sprints = mongolabResource('sprints'); + var Sprints = $mongolabResourceHttp('sprints'); Sprints.forProject = function (projectId) { return Sprints.query({projectId:projectId}); }; diff --git a/client/src/common/resources/tasks.js b/client/src/common/resources/tasks.js index aeb8f7c5..8d2f679f 100644 --- a/client/src/common/resources/tasks.js +++ b/client/src/common/resources/tasks.js @@ -1,7 +1,7 @@ -angular.module('resources.tasks', ['mongolabResource']); -angular.module('resources.tasks').factory('Tasks', ['mongolabResource', function (mongolabResource) { +angular.module('resources.tasks', ['mongolabResourceHttp']); +angular.module('resources.tasks').factory('Tasks', ['$mongolabResourceHttp', function ($mongolabResourceHttp) { - var Tasks = mongolabResource('tasks'); + var Tasks = $mongolabResourceHttp('tasks'); Tasks.statesEnum = ['TODO', 'IN_DEV', 'BLOCKED', 'IN_TEST', 'DONE']; diff --git a/client/src/common/resources/users.js b/client/src/common/resources/users.js index 047b1647..40784c4f 100644 --- a/client/src/common/resources/users.js +++ b/client/src/common/resources/users.js @@ -1,7 +1,7 @@ -angular.module('resources.users', ['mongolabResource']); -angular.module('resources.users').factory('Users', ['mongolabResource', function (mongoResource) { +angular.module('resources.users', ['mongolabResourceHttp']); +angular.module('resources.users').factory('Users', ['$mongolabResourceHttp', function ($mongolabResourceHttp) { - var userResource = mongoResource('users'); + var userResource = $mongolabResourceHttp('users'); userResource.prototype.getFullName = function () { return this.lastName + " " + this.firstName + " (" + this.email + ")"; }; diff --git a/client/src/common/security/interceptor.js b/client/src/common/security/interceptor.js index 3c7ec2f0..c67ddb2f 100644 --- a/client/src/common/security/interceptor.js +++ b/client/src/common/security/interceptor.js @@ -2,22 +2,21 @@ angular.module('security.interceptor', ['security.retryQueue']) // This http interceptor listens for authentication failures .factory('securityInterceptor', ['$injector', 'securityRetryQueue', function($injector, queue) { - return function(promise) { - // Intercept failed requests - return promise.then(null, function(originalResponse) { + return { + responseError: function(originalResponse) { if(originalResponse.status === 401) { // The request bounced because it was not authorized - add a new request to the retry queue - promise = queue.pushRetryFn('unauthorized-server', function retryRequest() { + return queue.pushRetryFn('unauthorized-server', function retryRequest() { // We must use $injector to get the $http service to prevent circular dependency return $injector.get('$http')(originalResponse.config); }); } - return promise; - }); + return originalResponse; + } }; }]) // We have to add the interceptor to the queue as a string because the interceptor depends upon service instances that are not available in the config block. .config(['$httpProvider', function($httpProvider) { - $httpProvider.responseInterceptors.push('securityInterceptor'); + $httpProvider.interceptors.push('securityInterceptor'); }]); \ No newline at end of file diff --git a/client/src/common/security/security.js b/client/src/common/security/security.js index 34bd3f15..eb89e7f5 100644 --- a/client/src/common/security/security.js +++ b/client/src/common/security/security.js @@ -2,10 +2,10 @@ angular.module('security.service', [ 'security.retryQueue', // Keeps track of failed requests that need to be retried once the user logs in 'security.login', // Contains the login form template and controller - 'ui.bootstrap.dialog' // Used to display the login form as a modal dialog. + 'ui.bootstrap.modal' // Used to display the login form as a modal dialog. ]) -.factory('security', ['$http', '$q', '$location', 'securityRetryQueue', '$dialog', function($http, $q, $location, queue, $dialog) { +.factory('security', ['$http', '$q', '$location', 'securityRetryQueue', '$modal', function($http, $q, $location, queue, $modal) { // Redirect to the given url (defaults to '/') function redirect(url) { @@ -19,8 +19,8 @@ angular.module('security.service', [ if ( loginDialog ) { throw new Error('Trying to open a dialog that is already open!'); } - loginDialog = $dialog.dialog(); - loginDialog.open('security/login/form.tpl.html', 'LoginFormController').then(onLoginDialogClose); + loginDialog = $modal.open({ templateUrl:'security/login/form.tpl.html', controller: 'LoginFormController'}); + loginDialog.result.then(onLoginDialogClose); } function closeLoginDialog(success) { if (loginDialog) { @@ -102,7 +102,7 @@ angular.module('security.service', [ isAuthenticated: function(){ return !!service.currentUser; }, - + // Is the current user an adminstrator? isAdmin: function() { return !!(service.currentUser && service.currentUser.admin); diff --git a/client/src/common/services/crud.js b/client/src/common/services/crud.js index 122755a5..c54f4e6d 100644 --- a/client/src/common/services/crud.js +++ b/client/src/common/services/crud.js @@ -73,7 +73,7 @@ angular.module('services.crud').factory('crudListMethods', ['$location', functio $location.path(pathPrefix+'/new'); }; - mixin['edit'] = function (itemId) { + mixin.edit = function (itemId) { $location.path(pathPrefix+'/'+itemId); }; diff --git a/client/src/index.html b/client/src/index.html index 599e8705..eb26ad15 100644 --- a/client/src/index.html +++ b/client/src/index.html @@ -1,12 +1,12 @@
- + - - - + + + diff --git a/client/src/less/stylesheet.less b/client/src/less/stylesheet.less deleted file mode 100644 index c4aa4751..00000000 --- a/client/src/less/stylesheet.less +++ /dev/null @@ -1,62 +0,0 @@ -/*! - * Bootstrap v2.1.1 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */ - -// CSS Reset -@import "../../vendor/bootstrap/reset.less"; - -// Core variables and mixins -@import "variables.less"; // Modify this for custom colors, font-sizes, etc -@import "../../vendor/bootstrap/mixins.less"; - -// Grid system and page structure -@import "../../vendor/bootstrap/scaffolding.less"; -@import "../../vendor/bootstrap/grid.less"; -@import "../../vendor/bootstrap/layouts.less"; - -// Base CSS -@import "../../vendor/bootstrap/type.less"; -@import "../../vendor/bootstrap/code.less"; -@import "../../vendor/bootstrap/forms.less"; -@import "../../vendor/bootstrap/tables.less"; - -// Components: common -@import "../../vendor/bootstrap/sprites.less"; -@import "../../vendor/bootstrap/dropdowns.less"; -@import "../../vendor/bootstrap/wells.less"; -@import "../../vendor/bootstrap/component-animations.less"; -@import "../../vendor/bootstrap/close.less"; - -// Components: Buttons & Alerts -@import "../../vendor/bootstrap/buttons.less"; -@import "../../vendor/bootstrap/button-groups.less"; -@import "../../vendor/bootstrap/alerts.less"; // Note: alerts share common CSS with buttons and thus have styles in buttons.less - -// Components: Nav -@import "../../vendor/bootstrap/navs.less"; -@import "../../vendor/bootstrap/navbar.less"; -@import "../../vendor/bootstrap/breadcrumbs.less"; -@import "../../vendor/bootstrap/pagination.less"; -@import "../../vendor/bootstrap/pager.less"; - -// Components: Popovers -@import "../../vendor/bootstrap/modals.less"; -@import "../../vendor/bootstrap/tooltip.less"; -@import "../../vendor/bootstrap/popovers.less"; - -// Components: Misc -@import "../../vendor/bootstrap/thumbnails.less"; -@import "../../vendor/bootstrap/labels-badges.less"; -@import "../../vendor/bootstrap/progress-bars.less"; -@import "../../vendor/bootstrap/accordion.less"; -@import "../../vendor/bootstrap/carousel.less"; -@import "../../vendor/bootstrap/hero-unit.less"; - -// Utility classes -@import "../../vendor/bootstrap/utilities.less"; // Has to be last to override when necessary diff --git a/client/src/less/variables.less b/client/src/less/variables.less deleted file mode 100644 index 7e784f3d..00000000 --- a/client/src/less/variables.less +++ /dev/null @@ -1,279 +0,0 @@ -// -// Variables -// -------------------------------------------------- - - -// Global values -// -------------------------------------------------- - - -// Grays -// ------------------------- -@black: #000; -@grayDarker: #222; -@grayDark: #333; -@gray: #555; -@grayLight: #999; -@grayLighter: #eee; -@white: #fff; - - -// Accent colors -// ------------------------- -@blue: #049cdb; -@blueDark: #0064cd; -@green: #46a546; -@red: #9d261d; -@yellow: #ffc40d; -@orange: #f89406; -@pink: #c3325f; -@purple: #7a43b6; - - -// Scaffolding -// ------------------------- -@bodyBackground: @white; -@textColor: @grayDark; - - -// Links -// ------------------------- -@linkColor: #08c; -@linkColorHover: darken(@linkColor, 15%); - - -// Typography -// ------------------------- -@sansFontFamily: "Helvetica Neue", Helvetica, Arial, sans-serif; -@serifFontFamily: Georgia, "Times New Roman", Times, serif; -@monoFontFamily: Monaco, Menlo, Consolas, "Courier New", monospace; - -@baseFontSize: 14px; -@baseFontFamily: @sansFontFamily; -@baseLineHeight: 20px; -@altFontFamily: @serifFontFamily; - -@headingsFontFamily: inherit; // empty to use BS default, @baseFontFamily -@headingsFontWeight: bold; // instead of browser default, bold -@headingsColor: inherit; // empty to use BS default, @textColor - -// Tables -// ------------------------- -@tableBackground: transparent; // overall background-color -@tableBackgroundAccent: #f9f9f9; // for striping -@tableBackgroundHover: #f5f5f5; // for hover -@tableBorder: #ddd; // table and cell border - -// Buttons -// ------------------------- -@btnBackground: @white; -@btnBackgroundHighlight: darken(@white, 10%); -@btnBorder: #bbb; - -@btnPrimaryBackground: @linkColor; -@btnPrimaryBackgroundHighlight: spin(@btnPrimaryBackground, 20%); - -@btnInfoBackground: #5bc0de; -@btnInfoBackgroundHighlight: #2f96b4; - -@btnSuccessBackground: #62c462; -@btnSuccessBackgroundHighlight: #51a351; - -@btnWarningBackground: lighten(@orange, 15%); -@btnWarningBackgroundHighlight: @orange; - -@btnDangerBackground: #ee5f5b; -@btnDangerBackgroundHighlight: #bd362f; - -@btnInverseBackground: #444; -@btnInverseBackgroundHighlight: @grayDarker; - - -// Forms -// ------------------------- -@inputBackground: @white; -@inputBorder: #ccc; -@inputBorderRadius: 3px; -@inputDisabledBackground: @grayLighter; -@formActionsBackground: #f5f5f5; - -// Dropdowns -// ------------------------- -@dropdownBackground: @white; -@dropdownBorder: rgba(0,0,0,.2); -@dropdownDividerTop: #e5e5e5; -@dropdownDividerBottom: @white; - -@dropdownLinkColor: @grayDark; -@dropdownLinkColorHover: @white; -@dropdownLinkColorActive: @dropdownLinkColor; - -@dropdownLinkBackgroundActive: @linkColor; -@dropdownLinkBackgroundHover: @dropdownLinkBackgroundActive; - - - -// COMPONENT VARIABLES -// -------------------------------------------------- - -// Z-index master list -// ------------------------- -// Used for a bird's eye view of components dependent on the z-axis -// Try to avoid customizing these :) -@zindexDropdown: 1000; -@zindexPopover: 1010; -@zindexTooltip: 1030; -@zindexFixedNavbar: 1030; -@zindexModalBackdrop: 1040; -@zindexModal: 1050; - - -// Sprite icons path -// ------------------------- -@iconSpritePath: "/static/img/glyphicons-halflings.png"; -@iconWhiteSpritePath: "/static/img/glyphicons-halflings-white.png"; - - -// Input placeholder text color -// ------------------------- -@placeholderText: @grayLight; - - -// Hr border color -// ------------------------- -@hrBorder: @grayLighter; - - -// Horizontal forms & lists -// ------------------------- -@horizontalComponentOffset: 180px; - - -// Wells -// ------------------------- -@wellBackground: #f5f5f5; - - -// Navbar -// ------------------------- -@navbarCollapseWidth: 979px; - -@navbarHeight: 40px; -@navbarBackgroundHighlight: #ffffff; -@navbarBackground: darken(@navbarBackgroundHighlight, 5%); -@navbarBorder: darken(@navbarBackground, 12%); - -@navbarText: #777; -@navbarLinkColor: #777; -@navbarLinkColorHover: @grayDark; -@navbarLinkColorActive: @gray; -@navbarLinkBackgroundHover: transparent; -@navbarLinkBackgroundActive: darken(@navbarBackground, 5%); - -@navbarBrandColor: @navbarLinkColor; - -// Inverted navbar -@navbarInverseBackground: #111111; -@navbarInverseBackgroundHighlight: #222222; -@navbarInverseBorder: #252525; - -@navbarInverseText: @grayLight; -@navbarInverseLinkColor: @grayLight; -@navbarInverseLinkColorHover: @white; -@navbarInverseLinkColorActive: @navbarInverseLinkColorHover; -@navbarInverseLinkBackgroundHover: transparent; -@navbarInverseLinkBackgroundActive: @navbarInverseBackground; - -@navbarInverseSearchBackground: lighten(@navbarInverseBackground, 25%); -@navbarInverseSearchBackgroundFocus: @white; -@navbarInverseSearchBorder: @navbarInverseBackground; -@navbarInverseSearchPlaceholderColor: #ccc; - -@navbarInverseBrandColor: @navbarInverseLinkColor; - - -// Pagination -// ------------------------- -@paginationBackground: #fff; -@paginationBorder: #ddd; -@paginationActiveBackground: #f5f5f5; - - -// Hero unit -// ------------------------- -@heroUnitBackground: @grayLighter; -@heroUnitHeadingColor: inherit; -@heroUnitLeadColor: inherit; - - -// Form states and alerts -// ------------------------- -@warningText: #c09853; -@warningBackground: #fcf8e3; -@warningBorder: darken(spin(@warningBackground, -10), 3%); - -@errorText: #b94a48; -@errorBackground: #f2dede; -@errorBorder: darken(spin(@errorBackground, -10), 3%); - -@successText: #468847; -@successBackground: #dff0d8; -@successBorder: darken(spin(@successBackground, -10), 5%); - -@infoText: #3a87ad; -@infoBackground: #d9edf7; -@infoBorder: darken(spin(@infoBackground, -10), 7%); - - -// Tooltips and popovers -// ------------------------- -@tooltipColor: #fff; -@tooltipBackground: #000; -@tooltipArrowWidth: 5px; -@tooltipArrowColor: @tooltipBackground; - -@popoverBackground: #fff; -@popoverArrowWidth: 10px; -@popoverArrowColor: #fff; -@popoverTitleBackground: darken(@popoverBackground, 3%); - -// Special enhancement for popovers -@popoverArrowOuterWidth: @popoverArrowWidth + 1; -@popoverArrowOuterColor: rgba(0,0,0,.25); - - - -// GRID -// -------------------------------------------------- - - -// Default 940px grid -// ------------------------- -@gridColumns: 12; -@gridColumnWidth: 60px; -@gridGutterWidth: 20px; -@gridRowWidth: (@gridColumns * @gridColumnWidth) + (@gridGutterWidth * (@gridColumns - 1)); - -// 1200px min -@gridColumnWidth1200: 70px; -@gridGutterWidth1200: 30px; -@gridRowWidth1200: (@gridColumns * @gridColumnWidth1200) + (@gridGutterWidth1200 * (@gridColumns - 1)); - -// 768px-979px -@gridColumnWidth768: 42px; -@gridGutterWidth768: 20px; -@gridRowWidth768: (@gridColumns * @gridColumnWidth768) + (@gridGutterWidth768 * (@gridColumns - 1)); - - -// Fluid grid -// ------------------------- -@fluidGridColumnWidth: percentage(@gridColumnWidth/@gridRowWidth); -@fluidGridGutterWidth: percentage(@gridGutterWidth/@gridRowWidth); - -// 1200px min -@fluidGridColumnWidth1200: percentage(@gridColumnWidth1200/@gridRowWidth1200); -@fluidGridGutterWidth1200: percentage(@gridGutterWidth1200/@gridRowWidth1200); - -// 768px-979px -@fluidGridColumnWidth768: percentage(@gridColumnWidth768/@gridRowWidth768); -@fluidGridGutterWidth768: percentage(@gridGutterWidth768/@gridRowWidth768); diff --git a/client/test/config/unit.js b/client/test/config/unit.js deleted file mode 100644 index ceed8d02..00000000 --- a/client/test/config/unit.js +++ /dev/null @@ -1,57 +0,0 @@ -// base path, that will be used to resolve files and exclude -basePath = '../..'; - -// list of files / patterns to load in the browser -files = [ - JASMINE, - JASMINE_ADAPTER, - 'vendor/jquery/jquery.js', - 'vendor/angular/angular.js', - 'vendor/angular/angular-route.js', - 'vendor/mongolab/mongolab-resource.js', - 'test/vendor/angular/angular-mocks.js', - 'vendor/angular-ui/**/*.js', - 'src/**/*.js', - 'test/unit/**/*.spec.js', - 'dist/templates/**/*.js' -]; - -// use dots reporter, as travis terminal does not support escaping sequences -// possible values: 'dots' || 'progress' -reporters = 'progress'; - -// these are default values, just to show available options - -// web server port -port = 8089; - -// cli runner port -runnerPort = 9109; - -urlRoot = '/__test/'; - -// enable / disable colors in the output (reporters and logs) -colors = true; - -// level of logging -// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG -logLevel = LOG_INFO; - -// enable / disable watching file and executing tests whenever any file changes -autoWatch = false; - -// polling interval in ms (ignored on OS that support inotify) -autoWatchInterval = 0; - -// Start these browsers, currently available: -// - Chrome -// - ChromeCanary -// - Firefox -// - Opera -// - Safari -// - PhantomJS -browsers = ['Chrome']; - -// Continuous Integration mode -// if true, it capture browsers, run tests and exit -singleRun = true; diff --git a/client/test/unit/common/directives/crud/edit.spec.js b/client/test/unit/common/directives/crud/edit.spec.js index 9c74b25e..c9dc7379 100644 --- a/client/test/unit/common/directives/crud/edit.spec.js +++ b/client/test/unit/common/directives/crud/edit.spec.js @@ -228,17 +228,20 @@ describe('crud-edit directive', function () { expect(scope.getCssClasses('someField').success).toBeFalsy(); someField.$setValidity('required', false); + scope.$digest(); expect(scope.getCssClasses('someField').error).toBeFalsy(); expect(scope.getCssClasses('someField').success).toBeFalsy(); someField.$setViewValue('original'); // This makes the form dirty but identical to the original someField.$setValidity('required', true); + scope.$digest(); expect(scope.getCssClasses('someField').error).toBeFalsy(); expect(scope.getCssClasses('someField').success).toBeFalsy(); someField.$setValidity('required', false); + scope.$digest(); expect(scope.getCssClasses('someField').error).toBeFalsy(); expect(scope.getCssClasses('someField').success).toBeFalsy(); diff --git a/client/test/unit/common/security/authorization.spec.js b/client/test/unit/common/security/authorization.spec.js index 7fd95e47..0f64459f 100644 --- a/client/test/unit/common/security/authorization.spec.js +++ b/client/test/unit/common/security/authorization.spec.js @@ -4,12 +4,13 @@ describe('securityAuthorization', function() { angular.module('test', []).value('I18N.MESSAGES', {}); beforeEach(module('test', 'security.authorization', 'security/login/form.tpl.html')); + beforeEach(module('template/modal/backdrop.html', 'template/modal/window.html')); beforeEach(inject(function($injector) { $rootScope = $injector.get('$rootScope'); securityAuthorization = $injector.get('securityAuthorization'); security = $injector.get('security'); queue = $injector.get('securityRetryQueue'); - + userResponse = { user: { id: '1234567890', email: 'jo@bloggs.com', firstName: 'Jo', lastName: 'Bloggs'} }; resolved = false; @@ -72,4 +73,3 @@ describe('securityAuthorization', function() { }); }); }); - \ No newline at end of file diff --git a/client/test/unit/common/security/interceptor.spec.js b/client/test/unit/common/security/interceptor.spec.js index 24ca9c67..6f2401d2 100644 --- a/client/test/unit/common/security/interceptor.spec.js +++ b/client/test/unit/common/security/interceptor.spec.js @@ -6,35 +6,20 @@ describe('securityInterceptor', function() { beforeEach(inject(function($injector) { queue = $injector.get('securityRetryQueue'); interceptor = $injector.get('securityInterceptor'); - wrappedPromise = {}; - promise = { - then: jasmine.createSpy('then').andReturn(wrappedPromise) - }; })); - it('accepts and returns a promise', function() { - var newPromise = interceptor(promise); - expect(promise.then).toHaveBeenCalled(); - expect(promise.then.mostRecentCall.args[0]).toBe(null); - expect(newPromise).toBe(wrappedPromise); - }); - it('does not intercept non-401 error responses', function() { var httpResponse = { status: 400 }; - interceptor(promise); - var errorHandler = promise.then.mostRecentCall.args[1]; - expect(errorHandler(httpResponse)).toBe(promise); + expect(interceptor.responseError(httpResponse)).toBe(httpResponse); }); it('intercepts 401 error responses and adds it to the retry queue', function() { var notAuthResponse = { status: 401 }; - interceptor(promise); - var errorHandler = promise.then.mostRecentCall.args[1]; - var newPromise = errorHandler(notAuthResponse); + interceptor.responseError(notAuthResponse); expect(queue.hasMore()).toBe(true); expect(queue.retryReason()).toBe('unauthorized-server'); }); diff --git a/client/test/unit/common/security/security.spec.js b/client/test/unit/common/security/security.spec.js index 0767c32a..00832b18 100644 --- a/client/test/unit/common/security/security.spec.js +++ b/client/test/unit/common/security/security.spec.js @@ -1,9 +1,10 @@ describe('security', function() { var $rootScope, $http, $httpBackend, status, userInfo; - + angular.module('test',[]).constant('I18N.MESSAGES', messages = {}); beforeEach(module('security', 'test', 'security/login/form.tpl.html')); + beforeEach(module('template/modal/backdrop.html', 'template/modal/window.html')); beforeEach(inject(function(_$rootScope_, _$httpBackend_, _$http_) { $rootScope = _$rootScope_; $httpBackend = _$httpBackend_; @@ -38,7 +39,7 @@ describe('security', function() { $httpBackend.expect('POST', '/login'); service.login('email', 'password'); $httpBackend.flush(); - expect(service.currentUser).toBe(userInfo); + expect(service.currentUser).toEqual(userInfo); }); it('calls queue.retry on a successful login', function() { $httpBackend.when('POST', '/login').respond(200, { user: userInfo }); @@ -48,7 +49,7 @@ describe('security', function() { $httpBackend.flush(); $rootScope.$digest(); expect(queue.retryAll).toHaveBeenCalled(); - expect(service.currentUser).toBe(userInfo); + expect(service.currentUser).toEqual(userInfo); }); it('does not call queue.retryAll after a login failure', function() { $httpBackend.when('POST', '/login').respond(200, { user: null }); @@ -116,14 +117,14 @@ describe('security', function() { service.currentUser = userInfo; expect(service.isAuthenticated()).toBe(true); expect(service.isAdmin()).toBe(false); - expect(service.currentUser).toBe(userInfo); + expect(service.currentUser).toEqual(userInfo); }); it("should be admin if we update with admin user info", function() { var userInfo = { admin: true }; service.currentUser = userInfo; expect(service.isAuthenticated()).toBe(true); expect(service.isAdmin()).toBe(true); - expect(service.currentUser).toBe(userInfo); + expect(service.currentUser).toEqual(userInfo); }); it("should not be authenticated or admin if we clear the user", function() { @@ -131,7 +132,7 @@ describe('security', function() { service.currentUser = userInfo; expect(service.isAuthenticated()).toBe(true); expect(service.isAdmin()).toBe(true); - expect(service.currentUser).toBe(userInfo); + expect(service.currentUser).toEqual(userInfo); service.currentUser = null; expect(service.isAuthenticated()).toBe(false); @@ -147,7 +148,7 @@ describe('security', function() { service.requestCurrentUser().then(function(data) { resolved = true; expect(service.isAuthenticated()).toBe(true); - expect(service.currentUser).toBe(userInfo); + expect(service.currentUser).toEqual(userInfo); }); $httpBackend.flush(); expect(resolved).toBe(true); @@ -158,7 +159,7 @@ describe('security', function() { expect(service.isAuthenticated()).toBe(true); service.requestCurrentUser().then(function(data) { resolved = true; - expect(service.currentUser).toBe(userInfo); + expect(service.currentUser).toEqual(userInfo); }); expect(resolved).toBe(true); }); diff --git a/client/test/vendor/angular/angular-mocks.js b/client/test/vendor/angular/angular-mocks.js deleted file mode 100644 index 0fac592b..00000000 --- a/client/test/vendor/angular/angular-mocks.js +++ /dev/null @@ -1,1846 +0,0 @@ -/** - * @license AngularJS v1.1.4 - * (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. - * - * - *
- * describe('$exceptionHandlerProvider', function() {
- *
- * it('should capture log messages and exceptions', function() {
- *
- * module(function($exceptionHandlerProvider) {
- * $exceptionHandlerProvider.mode('log');
- * });
- *
- * inject(function($log, $exceptionHandler, $timeout) {
- * $timeout(function() { $log.log(1); });
- * $timeout(function() { $log.log(2); throw 'banana peel'; });
- * $timeout(function() { $log.log(3); });
- * expect($exceptionHandler.errors).toEqual([]);
- * expect($log.assertEmpty());
- * $timeout.flush();
- * expect($exceptionHandler.errors).toEqual(['banana peel']);
- * expect($log.log.logs).toEqual([[1], [2], [3]]);
- * });
- * });
- * });
- *
- */
-
-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 thrown, for this case the `log` mode stores an
- * array of errors in `$exceptionHandler.errors`, to allow later assertion of them.
- * 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 constructor 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".
- *
- * - * 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; - * newYearInBratislava.getSeconds() => 0; - *- * - */ - 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.getMilliseconds = function() { - return self.date.getMilliseconds(); - }; - - 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 = ['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.createMockWindow - * @description - * - * This function creates a mock window object useful for controlling access ot setTimeout, but mocking out - * sufficient window's properties to allow Angular to execute. - * - * @example - * - *
- beforeEach(module(function($provide) {
- $provide.value('$window', window = angular.mock.createMockWindow());
- }));
-
- it('should do something', inject(function($window) {
- var val = null;
- $window.setTimeout(function() { val = 123; }, 10);
- expect(val).toEqual(null);
- window.setTimeout.expect(10).process();
- expect(val).toEqual(123);
- });
- *
- *
- */
-angular.mock.createMockWindow = function() {
- var mockWindow = {};
- var setTimeoutQueue = [];
-
- mockWindow.document = window.document;
- mockWindow.getComputedStyle = angular.bind(window, window.getComputedStyle);
- mockWindow.scrollTo = angular.bind(window, window.scrollTo);
- mockWindow.navigator = window.navigator;
- mockWindow.setTimeout = function(fn, delay) {
- setTimeoutQueue.push({fn: fn, delay: delay});
- };
- mockWindow.setTimeout.queue = setTimeoutQueue;
- mockWindow.setTimeout.expect = function(delay) {
- if (setTimeoutQueue.length > 0) {
- return {
- process: function() {
- setTimeoutQueue.shift().fn();
- }
- };
- } else {
- expect('SetTimoutQueue empty. Expecting delay of ').toEqual(delay);
- }
- };
-
- return mockWindow;
-};
-
-/**
- * @ngdoc function
- * @name angular.mock.dump
- * @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('');
- 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.
- *
- *
- * | Request expectations | Backend definitions | |
|---|---|---|
| Syntax | - *.expect(...).respond(...) | - *.when(...).respond(...) | - *
| Typical usage | - *strict unit tests | - *loose (black-box) unit testing | - *
| Fulfills multiple requests | - *NO | - *YES | - *
| Order of requests matters | - *YES | - *NO | - *
| Request required | - *YES | - *NO | - *
| Response required | - *optional (see below) | - *YES | - *
- // 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 $httpBackend;
-
- 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();
- });
-
- */
-angular.mock.$HttpBackendProvider = function() {
- this.$get = ['$rootScope', 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($rootScope, $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) {
- $rootScope.$digest();
- 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.
- *
- * - * afterEach($httpBackend.verifyExpectations); - *- */ - $httpBackend.verifyNoOutstandingExpectation = function() { - $rootScope.$digest(); - 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. - * - *
- * afterEach($httpBackend.verifyNoOutstandingRequest); - *- */ - $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" and "verifyNoPendingTasks" methods. - */ - -angular.mock.$TimeoutDecorator = function($delegate, $browser) { - - /** - * @ngdoc method - * @name ngMock.$timeout#flush - * @methodOf ngMock.$timeout - * @description - * - * Flushes the queue of pending tasks. - */ - $delegate.flush = function() { - $browser.defer.flush(); - }; - - /** - * @ngdoc method - * @name ngMock.$timeout#verifyNoPendingTasks - * @methodOf ngMock.$timeout - * @description - * - * Verifies that there are no pending tasks that need to be flushed. - */ - $delegate.verifyNoPendingTasks = function() { - if ($browser.deferredFns.length) { - throw Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + - formatPendingTasksAsString($browser.deferredFns)); - } - }; - - function formatPendingTasksAsString(tasks) { - var result = []; - angular.forEach(tasks, function(task) { - result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}'); - }); - - return result.join(', '); - } - - return $delegate; -}; - -/** - * - */ -angular.mock.$RootElementProvider = function() { - this.$get = function() { - return angular.element(''); - } -}; - -/** - * @ngdoc overview - * @name ngMock - * @description - * - * The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful - * mocks to the {@link AUTO.$injector $injector}. - */ -angular.module('ngMock', ['ng']).provider({ - $browser: angular.mock.$BrowserProvider, - $exceptionHandler: angular.mock.$ExceptionHandlerProvider, - $log: angular.mock.$LogProvider, - $httpBackend: angular.mock.$HttpBackendProvider, - $rootElement: angular.mock.$RootElementProvider -}).config(function($provide) { - $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); -}); - -/** - * @ngdoc overview - * @name ngMockE2E - * @description - * - * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing. - * Currently there is only one mock present in this module - - * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. - */ -angular.module('ngMockE2E', ['ng']).config(function($provide) { - $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); -}); - -/** - * @ngdoc object - * @name ngMockE2E.$httpBackend - * @description - * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of - * applications that use the {@link ng.$http $http service}. - * - * *Note*: For fake http backend implementation suitable for unit testing please see - * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. - * - * This implementation can be used to respond with static or dynamic responses via the `when` api - * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the - * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch - * templates from a webserver). - * - * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application - * is being developed with the real backend api replaced with a mock, it is often desirable for - * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch - * templates or static files from the webserver). To configure the backend with this behavior - * use the `passThrough` request handler of `when` instead of `respond`. - * - * Additionally, we don't want to manually have to flush mocked out requests like we do during unit - * testing. For this reason the e2e $httpBackend automatically flushes mocked out requests - * automatically, closely simulating the behavior of the XMLHttpRequest object. - * - * To setup the application to run with this http backend, you have to create a module that depends - * on the `ngMockE2E` and your application modules and defines the fake backend: - * - *
- * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
- * myAppDev.run(function($httpBackend) {
- * phones = [{name: 'phone1'}, {name: 'phone2'}];
- *
- * // returns the current list of phones
- * $httpBackend.whenGET('/phones').respond(phones);
- *
- * // adds a new phone to the phones array
- * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
- * phones.push(angular.fromJSON(data));
- * });
- * $httpBackend.whenGET(/^\/templates\//).passThrough();
- * //...
- * });
- *
- *
- * Afterwards, bootstrap your app with this new module.
- */
-
-/**
- * @ngdoc method
- * @name ngMockE2E.$httpBackend#when
- * @methodOf ngMockE2E.$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` and `passThrough` methods 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).
- * - passThrough – `{function()}` – Any request matching a backend definition with `passThrough`
- * handler, will be pass through to the real backend (an XHR request will be made to the
- * server.
- */
-
-/**
- * @ngdoc method
- * @name ngMockE2E.$httpBackend#whenGET
- * @methodOf ngMockE2E.$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` and `passThrough` methods that
- * control how a matched request is handled.
- */
-
-/**
- * @ngdoc method
- * @name ngMockE2E.$httpBackend#whenHEAD
- * @methodOf ngMockE2E.$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` and `passThrough` methods that
- * control how a matched request is handled.
- */
-
-/**
- * @ngdoc method
- * @name ngMockE2E.$httpBackend#whenDELETE
- * @methodOf ngMockE2E.$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` and `passThrough` methods that
- * control how a matched request is handled.
- */
-
-/**
- * @ngdoc method
- * @name ngMockE2E.$httpBackend#whenPOST
- * @methodOf ngMockE2E.$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` and `passThrough` methods that
- * control how a matched request is handled.
- */
-
-/**
- * @ngdoc method
- * @name ngMockE2E.$httpBackend#whenPUT
- * @methodOf ngMockE2E.$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` and `passThrough` methods that
- * control how a matched request is handled.
- */
-
-/**
- * @ngdoc method
- * @name ngMockE2E.$httpBackend#whenPATCH
- * @methodOf ngMockE2E.$httpBackend
- * @description
- * Creates a new backend definition for PATCH 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` and `passThrough` methods that
- * control how a matched request is handled.
- */
-
-/**
- * @ngdoc method
- * @name ngMockE2E.$httpBackend#whenJSONP
- * @methodOf ngMockE2E.$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` and `passThrough` methods that
- * control how a matched request is handled.
- */
-angular.mock.e2e = {};
-angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
-
-
-angular.mock.clearDataCache = function() {
- var key,
- cache = angular.element.cache;
-
- for(key in cache) {
- if (cache.hasOwnProperty(key)) {
- var handle = cache[key].handle;
-
- handle && angular.element(handle.elem).unbind();
- delete cache[key];
- }
- }
-};
-
-
-window.jstestdriver && (function(window) {
- /**
- * Global method to output any number of objects into JSTD console. Useful for debugging.
- */
- window.dump = function() {
- var args = [];
- angular.forEach(arguments, function(arg) {
- args.push(angular.mock.dump(arg));
- });
- jstestdriver.console.log.apply(jstestdriver.console, args);
- if (window.console) {
- window.console.log.apply(window.console, args);
- }
- };
-})(window);
-
-
-(window.jasmine || window.mocha) && (function(window) {
-
- var currentSpec = null;
-
- beforeEach(function() {
- currentSpec = this;
- });
-
- afterEach(function() {
- var injector = currentSpec.$injector;
-
- currentSpec.$injector = null;
- currentSpec.$modules = null;
- currentSpec = null;
-
- if (injector) {
- injector.get('$rootElement').unbind();
- injector.get('$browser').pollFns.length = 0;
- }
-
- angular.mock.clearDataCache();
-
- // clean up jquery's fragment cache
- angular.forEach(angular.element.fragments, function(val, key) {
- delete angular.element.fragments[key];
- });
-
- MockXhr.$$lastInstance = null;
-
- angular.forEach(angular.callbacks, function(val, key) {
- delete angular.callbacks[key];
- });
- angular.callbacks.counter = 0;
- });
-
- function isSpecRunning() {
- return currentSpec && (window.mocha || currentSpec.queue.running);
- }
-
- /**
- * @ngdoc function
- * @name angular.mock.module
- * @description
- *
- * *NOTE*: This function is also published on window for easy access.
- *
- * angular.module('myApplicationModule', [])
- * .value('mode', 'app')
- * .value('version', 'v1.0.1');
- *
- *
- * describe('MyApp', function() {
- *
- * // You need to load modules that you want to test,
- * // it loads only the "ng" module by default.
- * beforeEach(module('myApplicationModule'));
- *
- *
- * // inject() is used to inject arguments of all given functions
- * it('should provide a version', inject(function(mode, version) {
- * expect(version).toEqual('v1.0.1');
- * expect(mode).toEqual('app');
- * }));
- *
- *
- * // The inject and module method can also be used inside of the it or beforeEach
- * it('should override a version and test the new version is injected', function() {
- * // module() takes functions or strings (module aliases)
- * module(function($provide) {
- * $provide.value('version', 'overridden'); // override version here
- * });
- *
- * inject(function(version) {
- * expect(version).toEqual('overridden');
- * });
- * ));
- * });
- *
- *
- *
- * @param {...Function} fns any number of functions which will be injected using the injector.
- */
- window.inject = angular.mock.inject = function() {
- var blockFns = Array.prototype.slice.call(arguments, 0);
- var errorForStack = new Error('Declaration Location');
- return isSpecRunning() ? workFn() : workFn;
- /////////////////////
- function workFn() {
- var modules = currentSpec.$modules || [];
-
- modules.unshift('ngMock');
- modules.unshift('ng');
- var injector = currentSpec.$injector;
- if (!injector) {
- injector = currentSpec.$injector = angular.injector(modules);
- }
- for(var i = 0, ii = blockFns.length; i < ii; i++) {
- try {
- injector.invoke(blockFns[i] || angular.noop, this);
- } catch (e) {
- if(e.stack && errorForStack) e.stack += '\n' + errorForStack.stack;
- throw e;
- } finally {
- errorForStack = null;
- }
- }
- }
- };
-})(window);
\ No newline at end of file
diff --git a/client/vendor/angular-ui/bootstrap/ui-bootstrap-custom-0.1.0-SNAPSHOT.js b/client/vendor/angular-ui/bootstrap/ui-bootstrap-custom-0.1.0-SNAPSHOT.js
deleted file mode 100644
index c8cc1b6d..00000000
--- a/client/vendor/angular-ui/bootstrap/ui-bootstrap-custom-0.1.0-SNAPSHOT.js
+++ /dev/null
@@ -1,345 +0,0 @@
-angular.module("ui.bootstrap", ["ui.bootstrap.dialog"]);
-
-// The `$dialogProvider` can be used to configure global defaults for your
-// `$dialog` service.
-var dialogModule = angular.module('ui.bootstrap.dialog', ['ui.bootstrap.transition']);
-
-dialogModule.controller('MessageBoxController', ['$scope', 'dialog', 'model', function($scope, dialog, model){
- $scope.title = model.title;
- $scope.message = model.message;
- $scope.buttons = model.buttons;
- $scope.close = function(res){
- dialog.close(res);
- };
-}]);
-
-dialogModule.provider("$dialog", function(){
-
- // The default options for all dialogs.
- var defaults = {
- backdrop: true,
- modalClass: 'modal',
- backdropClass: 'modal-backdrop',
- transitionClass: 'fade',
- triggerClass: 'in',
- resolve:{},
- backdropFade: false,
- modalFade:false,
- keyboard: true, // close with esc key
- backdropClick: true // only in conjunction with backdrop=true
- /* other options: template, templateUrl, controller */
- };
-
- var globalOptions = {};
-
- // The `options({})` allows global configuration of all dialogs in the application.
- //
- // var app = angular.module('App', ['ui.bootstrap.dialog'], function($dialogProvider){
- // // don't close dialog when backdrop is clicked by default
- // $dialogProvider.options({backdropClick: false});
- // });
- this.options = function(value){
- globalOptions = value;
- };
-
- // Returns the actual `$dialog` service that is injected in controllers
- this.$get = ["$http", "$document", "$compile", "$rootScope", "$controller", "$templateCache", "$q", "$transition",
- function ($http, $document, $compile, $rootScope, $controller, $templateCache, $q, $transition) {
-
- var body = $document.find('body');
-
- function createElement(clazz) {
- var el = angular.element("