<commit_before>'use strict';

var chai = require('chai')
  , Sequelize = require('../../../index')
  , Promise = Sequelize.Promise
  , expect = chai.expect
  , Support = require(__dirname + '/../../support')
  , DataTypes = require(__dirname + '/../../../lib/data-types')
  , dialect = Support.getTestDialect()
  , datetime = require('chai-datetime');

chai.use(datetime);
chai.config.includeStack = true;

describe(Support.getTestDialectTeaser('Model'), function() {
  describe('attributes', function() {
    describe('types', function() {
      describe('VIRTUAL', function() {
        beforeEach(function() {
          this.User = this.sequelize.define('user', {
            storage: Sequelize.STRING,
            field1: {
              type: Sequelize.VIRTUAL,
              set: function(val) {
                this.setDataValue('storage', val);
                this.setDataValue('field1', val);
              },
              get: function() {
                return this.getDataValue('field1');
              }
            },
            field2: {
              type: Sequelize.VIRTUAL,
              get: function() {
                return 42;
              }
            },
            virtualWithDefault: {
              type: Sequelize.VIRTUAL,
              defaultValue: 'cake'
            }
          }, { timestamps: false });

          this.Task = this.sequelize.define('task', {});
          this.Project = this.sequelize.define('project', {});

          this.Task.belongsTo(this.User);
          this.Project.hasMany(this.User);
          this.User.hasMany(this.Project);

          this.sqlAssert = function(sql) {
            expect(sql.indexOf('field1')).to.equal(-1);
            expect(sql.indexOf('field2')).to.equal(-1);
          };

          return this.sequelize.sync({ force: true });
        });

        it('should not be ignored in dataValues get', function() {
          var user = this.User.build({
            field1: 'field1_value',
            field2: 'field2_value'
          });

          expect(user.get()).to.deep.equal({ storage: 'field1_value', field1: 'field1_value', virtualWithDefault: 'cake', field2: 42, id: null });
        });

        it('should be ignored in table creation', function() {
          return this.sequelize.getQueryInterface().describeTable(this.User.tableName).then(function(fields) {
            expect(Object.keys(fields).length).to.equal(2);
          });
        });

        it('should be ignored in find, findAll and includes', function() {
          return Promise.all([
            this.User.find().on('sql', this.sqlAssert),
            this.User.findAll().on('sql', this.sqlAssert),
            this.Task.findAll({
              include: [
                this.User
              ]
            }).on('sql', this.sqlAssert),
            this.Project.findAll({
              include: [
                this.User
              ]
            }).on('sql', this.sqlAssert)
          ]);
        });

        it('should allow me to store selected values', function() {
          var Post = this.sequelize.define('Post', {
              text: Sequelize.TEXT,
              someBoolean: {
                type: Sequelize.VIRTUAL
              }
            });

          return this.sequelize.sync({ force: true}).then(function() {
            return Post.bulkCreate([{ text: 'text1' },{ text: 'text2' }]);
          }).then(function() {
            var boolQuery = 'EXISTS(SELECT 1) AS "someBoolean"';
            if (dialect === 'mssql') {
              boolQuery = 'CAST(CASE WHEN EXISTS(SELECT 1) THEN 1 ELSE 0 END AS BIT) AS "someBoolean"';
            }

            return Post.find({ attributes: ['id', 'text', Sequelize.literal(boolQuery)] });
          }).then(function(post) {
            expect(post.get('someBoolean')).to.be.ok;
            expect(post.get().someBoolean).to.be.ok;
          });
        });

        it('should be ignored in create and updateAttributes', function() {
          return this.User.create({
            field1: 'something'
          }).then(function(user) {
            // We already verified that the virtual is not added to the table definition, so if this succeeds, were good

            expect(user.virtualWithDefault).to.equal('cake');
            expect(user.storage).to.equal('something');
            return user.updateAttributes({
              field1: 'something else'
            });
          }).then(function(user) {
            expect(user.virtualWithDefault).to.equal('cake');
            expect(user.storage).to.equal('something else');
          });
        });

        it('should be ignored in bulkCreate and and bulkUpdate', function() {
          var self = this;
          return this.User.bulkCreate([{
            field1: 'something'
          }]).on('sql', this.sqlAssert).then(function() {
            return self.User.findAll();
          }).then(function(users) {
            expect(users[0].storage).to.equal('something');
          });
        });
      });
    });
  });
});
<commit_msg>fix virtual attribute test relying on a faulty assumption<commit_after>'use strict';

var chai = require('chai')
  , Sequelize = require('../../../index')
  , Promise = Sequelize.Promise
  , expect = chai.expect
  , Support = require(__dirname + '/../../support')
  , DataTypes = require(__dirname + '/../../../lib/data-types')
  , dialect = Support.getTestDialect()
  , datetime = require('chai-datetime');

chai.use(datetime);
chai.config.includeStack = true;

describe(Support.getTestDialectTeaser('Model'), function() {
  describe('attributes', function() {
    describe('types', function() {
      describe('VIRTUAL', function() {
        beforeEach(function() {
          this.User = this.sequelize.define('user', {
            storage: Sequelize.STRING,
            field1: {
              type: Sequelize.VIRTUAL,
              set: function(val) {
                this.setDataValue('storage', val);
                this.setDataValue('field1', val);
              },
              get: function() {
                return this.getDataValue('field1');
              }
            },
            field2: {
              type: Sequelize.VIRTUAL,
              get: function() {
                return 42;
              }
            },
            virtualWithDefault: {
              type: Sequelize.VIRTUAL,
              defaultValue: 'cake'
            }
          }, { timestamps: false });

          this.Task = this.sequelize.define('task', {});
          this.Project = this.sequelize.define('project', {});

          this.Task.belongsTo(this.User);
          this.Project.hasMany(this.User);
          this.User.hasMany(this.Project);

          this.sqlAssert = function(sql) {
            expect(sql.indexOf('field1')).to.equal(-1);
            expect(sql.indexOf('field2')).to.equal(-1);
          };

          return this.sequelize.sync({ force: true });
        });

        it('should not be ignored in dataValues get', function() {
          var user = this.User.build({
            field1: 'field1_value',
            field2: 'field2_value'
          });

          expect(user.get()).to.deep.equal({ storage: 'field1_value', field1: 'field1_value', virtualWithDefault: 'cake', field2: 42, id: null });
        });

        it('should be ignored in table creation', function() {
          return this.sequelize.getQueryInterface().describeTable(this.User.tableName).then(function(fields) {
            expect(Object.keys(fields).length).to.equal(2);
          });
        });

        it('should be ignored in find, findAll and includes', function() {
          return Promise.all([
            this.User.find().on('sql', this.sqlAssert),
            this.User.findAll().on('sql', this.sqlAssert),
            this.Task.findAll({
              include: [
                this.User
              ]
            }).on('sql', this.sqlAssert),
            this.Project.findAll({
              include: [
                this.User
              ]
            }).on('sql', this.sqlAssert)
          ]);
        });

        it('should allow me to store selected values', function() {
          var Post = this.sequelize.define('Post', {
              text: Sequelize.TEXT,
              someBoolean: {
                type: Sequelize.VIRTUAL
              }
            });

          return this.sequelize.sync({ force: true}).then(function() {
            return Post.bulkCreate([{ text: 'text1' },{ text: 'text2' }]);
          }).then(function() {
            var boolQuery = 'EXISTS(SELECT 1) AS "someBoolean"';
            if (dialect === 'mssql') {
              boolQuery = 'CAST(CASE WHEN EXISTS(SELECT 1) THEN 1 ELSE 0 END AS BIT) AS "someBoolean"';
            }

            return Post.find({ attributes: ['id', 'text', Sequelize.literal(boolQuery)] });
          }).then(function(post) {
            expect(post.get('someBoolean')).to.be.ok;
            expect(post.get().someBoolean).to.be.ok;
          });
        });

        it('should be ignored in create and updateAttributes', function() {
          return this.User.create({
            field1: 'something'
          }).then(function(user) {
            // We already verified that the virtual is not added to the table definition, so if this succeeds, were good

            expect(user.virtualWithDefault).to.equal('cake');
            expect(user.storage).to.equal('something');
            return user.updateAttributes({
              field1: 'something else'
            }, {
              fields: ['storage']
            });
          }).then(function(user) {
            expect(user.virtualWithDefault).to.equal('cake');
            expect(user.storage).to.equal('something else');
          });
        });

        it('should be ignored in bulkCreate and and bulkUpdate', function() {
          var self = this;
          return this.User.bulkCreate([{
            field1: 'something'
          }]).on('sql', this.sqlAssert).then(function() {
            return self.User.findAll();
          }).then(function(users) {
            expect(users[0].storage).to.equal('something');
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : config.build.env

module.exports = merge(baseWebpackConfig, {
  module: {
    loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  vue: {
    loaders: utils.cssLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    // extract css into its own file
    new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    })
  ]
})
<commit_msg>only bundle js files in vendor.js (#143)<commit_after>var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : config.build.env

module.exports = merge(baseWebpackConfig, {
  module: {
    loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  vue: {
    loaders: utils.cssLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    // extract css into its own file
    new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    })
  ]
})
<|endoftext|>


<commit_before>angular.module('app.services').service('HLFilters', HLFilters);

function HLFilters() {
    this.updateFilterQuery = (viewModel, hasClearButtons) => {
        // Update the filter based on the separate filters.
        let filterStrings = [];
        let specialFilterStrings = [];
        let separateFilterStrings = [];
        let filterList = viewModel.filterList;

        let filterQuery = '';

        if (hasClearButtons) {
            this._displayClearButtons(viewModel);
        }

        if (viewModel.filterSpecialList) {
            filterList = filterList.concat(viewModel.filterSpecialList);
        }

        filterList.forEach(filter => {
            if (filter.id && filter.id === 'is_archived') {
                if (!filter.selected) {
                    filterStrings.push('is_archived:false');
                }
            } else if (filter.selected) {
                if (filter.isSpecialFilter) {
                    if (filter.separate) {
                        separateFilterStrings.push(filter.value);
                    } else {
                        specialFilterStrings.push(filter.value);
                    }
                } else {
                    filterStrings.push(filter.value);
                }
            }
        });

        if (viewModel.table.dueDateFilter) {
            filterStrings.push(viewModel.table.dueDateFilter);
        }

        // If we have a special filter, we join them OR-wise.
        if (specialFilterStrings.length) {
            filterStrings.push('(' + specialFilterStrings.join(' OR ') + ')');
        }

        if (separateFilterStrings.length) {
            filterStrings.push('(' + separateFilterStrings.join(' OR ') + ')');
        }

        if (viewModel.table.usersFilter) {
            filterStrings.push('(' + viewModel.table.usersFilter + ')');
        }

        // Finally join all filters AND-wise.
        viewModel.table.filterQuery = filterStrings.join(' AND ');
    };

    this._displayClearButtons = viewModel => {
        viewModel.displayFilterClear = false;
        viewModel.displaySpecialFilterClear = false;

        viewModel.filterList.forEach(filter => {
            if (filter.selected) {
                viewModel.displayFilterClear = true;
            }
        });

        if (viewModel.filterSpecialList) {
            viewModel.filterSpecialList.forEach(filter => {
                if (filter.selected) {
                    viewModel.displaySpecialFilterClear = true;
                }
            });
        }
    };

    this.clearFilters = (viewModel, clearSpecial) => {
        if (clearSpecial) {
            viewModel.filterSpecialList.forEach(filter => {
                filter.selected = false;
            });
        } else {
            viewModel.filterList.forEach(filter => {
                filter.selected = false;
            });
        }

        viewModel.updateFilterQuery();
    };

    this.getStoredSelections = (filterList, storedFilterList) => {
        if (storedFilterList) {
            // Stored filter list exists, merge the selections from with the stored values.
            storedFilterList.forEach(storedFilter => {
                filterList.forEach(filter => {
                    if (storedFilter.name === filter.name) {
                        filter.selected = storedFilter.selected;
                    }
                });
            });
        }
    };
}
<commit_msg>Removed useless variable<commit_after>angular.module('app.services').service('HLFilters', HLFilters);

function HLFilters() {
    this.updateFilterQuery = (viewModel, hasClearButtons) => {
        // Update the filter based on the separate filters.
        let filterStrings = [];
        let specialFilterStrings = [];
        let separateFilterStrings = [];
        let filterList = viewModel.filterList;

        if (hasClearButtons) {
            this._displayClearButtons(viewModel);
        }

        if (viewModel.filterSpecialList) {
            filterList = filterList.concat(viewModel.filterSpecialList);
        }

        filterList.forEach(filter => {
            if (filter.id && filter.id === 'is_archived') {
                if (!filter.selected) {
                    filterStrings.push('is_archived:false');
                }
            } else if (filter.selected) {
                if (filter.isSpecialFilter) {
                    if (filter.separate) {
                        separateFilterStrings.push(filter.value);
                    } else {
                        specialFilterStrings.push(filter.value);
                    }
                } else {
                    filterStrings.push(filter.value);
                }
            }
        });

        if (viewModel.table.dueDateFilter) {
            filterStrings.push(viewModel.table.dueDateFilter);
        }

        // If we have a special filter, we join them OR-wise.
        if (specialFilterStrings.length) {
            filterStrings.push('(' + specialFilterStrings.join(' OR ') + ')');
        }

        if (separateFilterStrings.length) {
            filterStrings.push('(' + separateFilterStrings.join(' OR ') + ')');
        }

        if (viewModel.table.usersFilter) {
            filterStrings.push('(' + viewModel.table.usersFilter + ')');
        }

        // Finally join all filters AND-wise.
        viewModel.table.filterQuery = filterStrings.join(' AND ');
    };

    this._displayClearButtons = viewModel => {
        viewModel.displayFilterClear = false;
        viewModel.displaySpecialFilterClear = false;

        viewModel.filterList.forEach(filter => {
            if (filter.selected) {
                viewModel.displayFilterClear = true;
            }
        });

        if (viewModel.filterSpecialList) {
            viewModel.filterSpecialList.forEach(filter => {
                if (filter.selected) {
                    viewModel.displaySpecialFilterClear = true;
                }
            });
        }
    };

    this.clearFilters = (viewModel, clearSpecial) => {
        if (clearSpecial) {
            viewModel.filterSpecialList.forEach(filter => {
                filter.selected = false;
            });
        } else {
            viewModel.filterList.forEach(filter => {
                filter.selected = false;
            });
        }

        viewModel.updateFilterQuery();
    };

    this.getStoredSelections = (filterList, storedFilterList) => {
        if (storedFilterList) {
            // Stored filter list exists, merge the selections from with the stored values.
            storedFilterList.forEach(storedFilter => {
                filterList.forEach(filter => {
                    if (storedFilter.name === filter.name) {
                        filter.selected = storedFilter.selected;
                    }
                });
            });
        }
    };
}
<|endoftext|>


<commit_before>/*
* Name :  LineChart.js
* Module : UnitTest
* Location : /frontend/test/unit/Model
*
* History :
* Version       Date        Programmer                  Description
* =================================================================================================
* 0.1.3			2015-06-26	Maria Giovanna Chinellato   Fix code
*
* 0.1.2         2015-05-19  Maria Giovanna Chinellato   Fix code
*
* 0.1.1			2015-05-19	Maria Giovanna Chinellato	Fix test of Model::MapChart
*
* 0.1.0			2015-05-19	Francesco Rossetto			Add test of Model::MapChart.js
*
* 0.0.1			2015-05-18	Francesco Rossetto			Initial code
* =================================================================================================
*
*/

describe('MapChart', function(){
	'use strict';

	var MapChartFactory;
	var MapChartFlowFactory;

	beforeEach(angular.mock.module('norris-nrti'));

	beforeEach(inject(function(_MapChartFactory_, $injector){
		MapChartFactory = _MapChartFactory_;
		MapChartFlowFactory = $injector.get('MapChartFlowFactory');
	}));

	describe('Constructor', function(){

		var json = {
			'title' : 'fottutissimografico',
			'socketURL' : 'localhost/page1/grafico1'
		};

		var MapChart;

		beforeEach(function(){
			MapChart = MapChartFactory.build(json);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('MapChart created', function(){
			expect(MapChart).toBeDefined();
		});

		it('graph Constructor called', function(){
			expect(MapChart.getTitle()).toEqual('fottutissimografico');
		});
		it('graph Constructor called', function(){
			expect(MapChart.getUrl()).toEqual('localhost/page1/grafico1');
		});
		it('graph created with the correct legendOnPoint', function(){
			expect(MapChart.getLegendOnPoint()).toEqual(false);
		});
		it('graph created with the correct latitude', function(){
			expect(MapChart.getLatitude()).toEqual(45.4113311);
		});
		it('graph created with the correct longitude', function(){
			expect(MapChart.getLongitude()).toEqual(11.8876318);
		});
		it('graph created with the correct mapType', function(){
			expect(MapChart.getMapType()).toEqual('roadmap');
		});
		it('graph created with the correct zoom', function(){
			expect(MapChart.getZoomable()).toEqual(true);
		});
		it('graph created with the correct drag', function(){
			expect(MapChart.getDraggable()).toEqual(true);
		});
		it('graph created with the correct mapWidth', function(){
			expect(MapChart.getMapWidth()).toEqual(0);
		});
		it('graph created with the correct mapHeight', function(){
			expect(MapChart.getMapHeight()).toEqual(0);
		});

	});

	/*deeescribe('split', function(){
		var res;
		var json = {};
		var json1 = json;
		json = json1;
		json = {
			'title' : 'grafico',
			'height' : 300,
			'width' : 300,
			'enabledLegend' : true,
			'legend' : {},
			'horizontalGrid' : true,
			'verticalGrid' : true,
			'latitude' : 4,
			'longitude' : 4,
			'scale' : 1001,
			'mapType' : 'roadmap',
			'zoom' : true
		};
		var g = {
			'title' : 'grafico',
			'height' : 300,
			'width' : 300,
			'enabledLegend' : true,
			'legend' : {},
			'horizontalGrid' : true,
			'verticalGrid' : true
		};
		var l = {
			'latitude' : 4,
			'longitude' : 4,
			'scale' : 1001,
			'mapType' : 'roadmap',
			'zoom' : true
		};

		beforeEach(function(){
			res = MapChart.prototype.test('split(json)');
		});

		it('json splitted in the correct way', function(){
			expect(res.graphJson).toEqual(g);
			expect(res.mapJson).toEqual(l);
		});

	});*/

	describe('#updateParameters', function(){
		var json = {
			'title' : 'graficonuovo',
			'height' : 400,
			'width' : 400,
			'enableLegend' : true,
			'legend' : { position: 'N' },
			'horizontalGrid' : false,
			'verticalGrid' : false,
			'legendOnPoint' : false,
			'latitude' : 3,
			'longitude' : 3,
			'scale' : 999,
			'mapType' : 'terrain',
			'zoom' : false,
			'flows' : [{'ID' : 'f1'},{'ID' : 'f2'},{'ID' : 'f3'}]
		};
		var MapChart;

		beforeEach(function(){
			MapChart = MapChartFactory.build();
			MapChart.updateParameters(json);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('MapChart created', function(){
			expect(MapChart).toBeDefined();
		});

		it('graph updated with the correct legendOnPoint', function(){
			expect(MapChart.getLegendOnPoint()).toEqual(false);
		});
		it('graph updated with the correct height', function(){
			expect(MapChart.getHeight()).toEqual(400);
		});
		it('graph updated with the correct width', function(){
			expect(MapChart.getWidth()).toEqual(400);
		});
		it('graph updated with the correct latitude', function(){
			expect(MapChart.getLatitude()).toEqual(3);
		});
		it('graph updated with the correct longitude', function(){
			expect(MapChart.getLongitude()).toEqual(3);
		});
		it('graph updated with the correct mapType', function(){
			expect(MapChart.getMapType()).toEqual('terrain');
		});
		it('graph updated with the correct zoom', function(){
			expect(MapChart.getZoomable()).toEqual(false);
		});
		it('graph update with the correct drag', function(){
			expect(MapChart.getDraggable()).toEqual(true);
		});
		it('graph updated with the correct flows', function(){
            expect(MapChart.getFlowList().length).toEqual(3);
        });
        it('graph updated with the correct mapWidth', function(){
			expect(MapChart.getMapWidth()).toEqual(0);
		});
		it('graph updated with the correct mapHeight', function(){
			expect(MapChart.getMapHeight()).toEqual(0);
		});

	});

	describe('#addFlow', function(){

		var json = {
			'ID' : 	'flusso1',
		};

		var fJson = {
			'name' : 'flusso1',
			'marker' : {'type' : 'shape', 'shape' : 'circle', 'icon' : null, 'text' : null},
			'maxItems' : '45',
			'trace' : {'type' : 'none'}
		};

		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build(fJson);
			MapChart = MapChartFactory.build();
			MapChart.addFlow(json.ID, newFlow);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('add flow into mapchart', function(){
			expect(MapChart.getFlowList().length).toEqual(1);
		});

	});

	describe('#deleteFlow', function(){

		var json1 = {
			'ID' : 	'flusso1',
			'name' : 'sonda 1'
		};

		var json2 = {
			'ID' : 	'flusso2',
			'name' : 'sonda 2'
		};
		var MapChart, Flow1, Flow2;

		beforeEach(function(){
			Flow1 = MapChartFlowFactory.build();
			Flow2 = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(json1.ID, Flow1);
			MapChart.addFlow(json2.ID, Flow2);
			MapChart.deleteFlow('flusso1');
		});

		afterEach(function(){
			Flow1 = null;
			Flow2 = null;
			MapChart = null;
		});

		it('delete flow from graph', function(){
			expect(MapChart.getFlowList().length).toEqual(1);
		});

	});

	describe('#replaceData', function(){

		var json1 = {
			'ID' : 	'flusso1',
			'name' : 'sonda 1',
			'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }, {'NorrisRecordID' : 'record3', 'value' : [4,4] }]
		};

		var json = {
			'ID' : 'flusso1',
			'records' :	[{'NorrisRecordID' : 'record4', 'value' : [5,5] }, {'NorrisRecordID' : 'record5', 'value' : [6,6] }]
		};

		var MapChart, Flow;

		beforeEach(function(){
			Flow = MapChartFlowFactory.build();
			Flow.initializeData(json1);
			MapChart = MapChartFactory.build();
			MapChart.addFlow(json1.ID, Flow);
			MapChart.replaceData(json);
		});

		afterEach(function(){
			Flow = null;
			MapChart = null;
		});

		it('delete flow from graph', function(){
			expect(MapChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(5);
			expect(MapChart.getFlowList()[0].flow.getData()[1].value[0]).toEqual(6);
		});

	});

	describe('#initializeData', function(){

		var data = [
			{
				'ID' : '1',
				'records' : [{ 'NorrisRecordID' : '234321', 'value' : [0,1]},{}]
			}
		];

		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(data[0].ID, newFlow);
			MapChart.initializeData(data);
		});
		afterEach(function(){
			MapChart = null;
		});

		it('inizialize flowList', function(){
			expect(MapChart.getFlowList()[0].flow.getData().length).toEqual(2);
		});
	});

	describe('#inPlaceUpdate', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];
		var data1 = 	{
			'ID' : '2',
			'NorrisRecordID' : 'record2',
			'value' : [4,4]
		};
		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(data[0].ID, newFlow);
			MapChart.initializeData(data);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('inizialize flowList', function(){
			expect(MapChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(3);
			MapChart.inPlaceUpdate(data1);
			expect(MapChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(4);
		});
	});

	describe('#streamUpdate', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];
		var data1 = 	{
			'ID' : '2',
			'records' : [{
				'NorrisRecordID' : 'record2',
				'value' : [4,4]
			}]
		};
		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(data[0].ID, newFlow);
			MapChart.initializeData(data);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('inizialize flowList', function(){
			expect(MapChart.getFlowList()[0].flow.getData().length).toEqual(1);
			MapChart.streamUpdate(data1);
			expect(MapChart.getFlowList()[0].flow.getData().length).toEqual(2);
		});
	});

	describe('#deleteData', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];

		var delData = {
			'ID' : '2',
			'NorrisRecordID' : 'record2'
		};

		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(data[0].ID, newFlow);
			MapChart.initializeData(data);
			MapChart.deleteData(delData);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('deleteData in the correct way', function(){
			expect(MapChart.getFlowList()[0].flow.getData().length).toEqual(0);
		});
	});

});<commit_msg>fix map chart spec<commit_after>/*
* Name :  LineChart.js
* Module : UnitTest
* Location : /frontend/test/unit/Model
*
* History :
* Version       Date        Programmer                  Description
* =================================================================================================
* 0.1.3			2015-06-26	Maria Giovanna Chinellato   Fix code
*
* 0.1.2         2015-05-19  Maria Giovanna Chinellato   Fix code
*
* 0.1.1			2015-05-19	Maria Giovanna Chinellato	Fix test of Model::MapChart
*
* 0.1.0			2015-05-19	Francesco Rossetto			Add test of Model::MapChart.js
*
* 0.0.1			2015-05-18	Francesco Rossetto			Initial code
* =================================================================================================
*
*/

describe('MapChart', function(){
	'use strict';

	var MapChartFactory;
	var MapChartFlowFactory;

	beforeEach(angular.mock.module('norris-nrti'));

	beforeEach(inject(function(_MapChartFactory_, $injector){
		MapChartFactory = _MapChartFactory_;
		MapChartFlowFactory = $injector.get('MapChartFlowFactory');
	}));

	describe('Constructor', function(){

		var json = {
			'title' : 'fottutissimografico',
			'socketURL' : 'localhost/page1/grafico1'
		};

		var MapChart;

		beforeEach(function(){
			MapChart = MapChartFactory.build(json);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('MapChart created', function(){
			expect(MapChart).toBeDefined();
		});

		it('graph Constructor called', function(){
			expect(MapChart.getTitle()).toEqual('fottutissimografico');
		});
		it('graph Constructor called', function(){
			expect(MapChart.getUrl()).toEqual('localhost/page1/grafico1');
		});
		it('graph created with the correct legendOnPoint', function(){
			expect(MapChart.getLegendOnPoint()).toEqual(false);
		});
		it('graph created with the correct latitude', function(){
			expect(MapChart.getLatitude()).toEqual(45.4113311);
		});
		it('graph created with the correct longitude', function(){
			expect(MapChart.getLongitude()).toEqual(11.8876318);
		});
		it('graph created with the correct mapType', function(){
			expect(MapChart.getMapType()).toEqual('roadmap');
		});
		it('graph created with the correct zoom', function(){
			expect(MapChart.getZoomable()).toEqual(true);
		});
		it('graph created with the correct drag', function(){
			expect(MapChart.getDraggable()).toEqual(true);
		});
		it('graph created with the correct mapWidth', function(){
			expect(MapChart.getMapWidth()).toEqual(0);
		});
		it('graph created with the correct mapHeight', function(){
			expect(MapChart.getMapHeight()).toEqual(0);
		});

	});

	/*deeescribe('split', function(){
		var res;
		var json = {};
		var json1 = json;
		json = json1;
		json = {
			'title' : 'grafico',
			'height' : 300,
			'width' : 300,
			'enabledLegend' : true,
			'legend' : {},
			'horizontalGrid' : true,
			'verticalGrid' : true,
			'latitude' : 4,
			'longitude' : 4,
			'scale' : 1001,
			'mapType' : 'roadmap',
			'zoom' : true
		};
		var g = {
			'title' : 'grafico',
			'height' : 300,
			'width' : 300,
			'enabledLegend' : true,
			'legend' : {},
			'horizontalGrid' : true,
			'verticalGrid' : true
		};
		var l = {
			'latitude' : 4,
			'longitude' : 4,
			'scale' : 1001,
			'mapType' : 'roadmap',
			'zoom' : true
		};

		beforeEach(function(){
			res = MapChart.prototype.test('split(json)');
		});

		it('json splitted in the correct way', function(){
			expect(res.graphJson).toEqual(g);
			expect(res.mapJson).toEqual(l);
		});

	});*/

	describe('#updateParameters', function(){
		var json = {
			'title' : 'graficonuovo',
			'height' : 400,
			'width' : 400,
			'mapWidth' : 0,
			'mapHeight' : 0,
			'enableLegend' : true,
			'legend' : { position: 'N' },
			'horizontalGrid' : false,
			'verticalGrid' : false,
			'legendOnPoint' : false,
			'latitude' : 3,
			'longitude' : 3,
			'scale' : 999,
			'mapType' : 'terrain',
			'drag' : true,
			'zoom' : false,
			'flows' : [{'ID' : 'f1'},{'ID' : 'f2'},{'ID' : 'f3'}]
		};
		var MapChart;

		beforeEach(function(){
			MapChart = MapChartFactory.build();
			MapChart.updateParameters(json);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('MapChart created', function(){
			expect(MapChart).toBeDefined();
		});

		it('graph updated with the correct legendOnPoint', function(){
			expect(MapChart.getLegendOnPoint()).toEqual(false);
		});
		it('graph updated with the correct height', function(){
			expect(MapChart.getHeight()).toEqual(400);
		});
		it('graph updated with the correct width', function(){
			expect(MapChart.getWidth()).toEqual(400);
		});
		it('graph updated with the correct legend', function(){
			expect(MapChart.getLegend()).not.toEqual(null);
		});
		it('graph updated with the correct latitude', function(){
			expect(MapChart.getLatitude()).toEqual(3);
		});
		it('graph updated with the correct longitude', function(){
			expect(MapChart.getLongitude()).toEqual(3);
		});
		it('graph updated with the correct mapType', function(){
			expect(MapChart.getMapType()).toEqual('terrain');
		});
		it('graph updated with the correct zoom', function(){
			expect(MapChart.getZoomable()).toEqual(false);
		});
		it('graph update with the correct drag', function(){
			expect(MapChart.getDraggable()).toEqual(true);
		});
		it('graph updated with the correct flows', function(){
            expect(MapChart.getFlowList().length).toEqual(3);
        });
        it('graph updated with the correct mapWidth', function(){
			expect(MapChart.getMapWidth()).toEqual(0);
		});
		it('graph updated with the correct mapHeight', function(){
			expect(MapChart.getMapHeight()).toEqual(0);
		});

	});

	describe('#addFlow', function(){

		var json = {
			'ID' : 	'flusso1',
		};

		var fJson = {
			'name' : 'flusso1',
			'marker' : {'type' : 'shape', 'shape' : 'circle', 'icon' : null, 'text' : null},
			'maxItems' : '45',
			'trace' : {'type' : 'none'}
		};

		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build(fJson);
			MapChart = MapChartFactory.build();
			MapChart.addFlow(json.ID, newFlow);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('add flow into mapchart', function(){
			expect(MapChart.getFlowList().length).toEqual(1);
		});

	});

	describe('#deleteFlow', function(){

		var json1 = {
			'ID' : 	'flusso1',
			'name' : 'sonda 1'
		};

		var json2 = {
			'ID' : 	'flusso2',
			'name' : 'sonda 2'
		};
		var MapChart, Flow1, Flow2;

		beforeEach(function(){
			Flow1 = MapChartFlowFactory.build();
			Flow2 = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(json1.ID, Flow1);
			MapChart.addFlow(json2.ID, Flow2);
			MapChart.deleteFlow('flusso1');
		});

		afterEach(function(){
			Flow1 = null;
			Flow2 = null;
			MapChart = null;
		});

		it('delete flow from graph', function(){
			expect(MapChart.getFlowList().length).toEqual(1);
		});

	});

	describe('#replaceData', function(){

		var json1 = {
			'ID' : 	'flusso1',
			'name' : 'sonda 1',
			'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }, {'NorrisRecordID' : 'record3', 'value' : [4,4] }]
		};

		var json = {
			'ID' : 'flusso1',
			'records' :	[{'NorrisRecordID' : 'record4', 'value' : [5,5] }, {'NorrisRecordID' : 'record5', 'value' : [6,6] }]
		};

		var MapChart, Flow;

		beforeEach(function(){
			Flow = MapChartFlowFactory.build();
			Flow.initializeData(json1);
			MapChart = MapChartFactory.build();
			MapChart.addFlow(json1.ID, Flow);
			MapChart.replaceData(json);
		});

		afterEach(function(){
			Flow = null;
			MapChart = null;
		});

		it('delete flow from graph', function(){
			expect(MapChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(5);
			expect(MapChart.getFlowList()[0].flow.getData()[1].value[0]).toEqual(6);
		});

	});

	describe('#initializeData', function(){

		var data = [
			{
				'ID' : '1',
				'records' : [{ 'NorrisRecordID' : '234321', 'value' : [0,1]},{}]
			}
		];

		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(data[0].ID, newFlow);
			MapChart.initializeData(data);
		});
		afterEach(function(){
			MapChart = null;
		});

		it('inizialize flowList', function(){
			expect(MapChart.getFlowList()[0].flow.getData().length).toEqual(2);
		});
	});

	describe('#inPlaceUpdate', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];
		var data1 = 	{
			'ID' : '2',
			'NorrisRecordID' : 'record2',
			'value' : [4,4]
		};
		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(data[0].ID, newFlow);
			MapChart.initializeData(data);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('inizialize flowList', function(){
			expect(MapChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(3);
			MapChart.inPlaceUpdate(data1);
			expect(MapChart.getFlowList()[0].flow.getData()[0].value[0]).toEqual(4);
		});
	});

	describe('#streamUpdate', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];
		var data1 = 	{
			'ID' : '2',
			'records' : [{
				'NorrisRecordID' : 'record2',
				'value' : [4,4]
			}]
		};
		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(data[0].ID, newFlow);
			MapChart.initializeData(data);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('inizialize flowList', function(){
			expect(MapChart.getFlowList()[0].flow.getData().length).toEqual(1);
			MapChart.streamUpdate(data1);
			expect(MapChart.getFlowList()[0].flow.getData().length).toEqual(2);
		});
	});

	describe('#deleteData', function(){

		var data = [
			{
				'ID' : '2',
				'records' : [{'NorrisRecordID' : 'record2', 'value' : [3,3] }]
			}
		];

		var delData = {
			'ID' : '2',
			'NorrisRecordID' : 'record2'
		};

		var newFlow;
		var MapChart;

		beforeEach(function(){
			newFlow = MapChartFlowFactory.build();
			MapChart = MapChartFactory.build();
			MapChart.addFlow(data[0].ID, newFlow);
			MapChart.initializeData(data);
			MapChart.deleteData(delData);
		});

		afterEach(function(){
			MapChart = null;
		});

		it('deleteData in the correct way', function(){
			expect(MapChart.getFlowList()[0].flow.getData().length).toEqual(0);
		});
	});

});<|endoftext|>


<commit_before>
describe("oboe integration (real http)", function() {

   var isNode = typeof window === "undefined"

   var oboe =     isNode
               ?  require('../../dist/oboe-node.js')
               :  (window.oboe)
               ;

   var ASYNC_TEST_TIMEOUT = 15 * 1000; // 15 seconds

   function url( path ){
      if( isNode ) {
         return 'localhost:4567/' + path;
      } else {
         return '/testServer/' + path;
      }
   }

   it('gets all expected callbacks by time request finishes', function () {

      oboe(url('tenSlowNumbers'))
          .node('![*]', callbackSpy)
          .done(whenDoneFn);

      waitsFor(function () {
         return !!fullResponse
      }, 'the request to complete', ASYNC_TEST_TIMEOUT);

      runs(function () {

         expect(callbackSpy).toHaveBeenCalledWith(0, [0], [fullResponse, 0]);
         expect(callbackSpy).toHaveBeenCalledWith(1, [1], [fullResponse, 1]);
         expect(callbackSpy).toHaveBeenCalledWith(2, [2], [fullResponse, 2]);
         expect(callbackSpy).toHaveBeenCalledWith(3, [3], [fullResponse, 3]);
         expect(callbackSpy).toHaveBeenCalledWith(4, [4], [fullResponse, 4]);
         expect(callbackSpy).toHaveBeenCalledWith(5, [5], [fullResponse, 5]);
         expect(callbackSpy).toHaveBeenCalledWith(6, [6], [fullResponse, 6]);
         expect(callbackSpy).toHaveBeenCalledWith(7, [7], [fullResponse, 7]);
         expect(callbackSpy).toHaveBeenCalledWith(8, [8], [fullResponse, 8]);
         expect(callbackSpy).toHaveBeenCalledWith(9, [9], [fullResponse, 9]);

      });
   })

   it('can abort once some data has been found in streamed response', function () {

      var req = oboe(url('tenSlowNumbers'))
                  .node('![5]', abortCallback);

      waitsFor(theRequestToBeAborted, 'the request to be aborted', ASYNC_TEST_TIMEOUT);

      // in case we didn't abort, wait a little longer. If we didn't really abort we'd get the
      // rest of the data now and the test would fail:
      waitsFor(someSecondsToPass(2), ASYNC_TEST_TIMEOUT);

      runs(function () {
         // because the request was aborted on index array 5, we got 6 numbers (inc zero)
         // not the whole ten.

         expect(req.root()).toEqual([0, 1, 2, 3, 4, 5]);

      });
   })

   it('can abort once some data has been found in not very streamed response', function () {

      // like above but we're getting a static file not the streamed numbers. This means
      // we'll almost certainly read in the whole response as one onprogress it is on localhost
      // and the json is very small

      var req = oboe(url('static/json/firstTenNaturalNumbers.json'))
                  .node('![5]', abortCallback);

      waitsFor(theRequestToBeAborted, 'the request to be aborted', ASYNC_TEST_TIMEOUT);

      // in case we didn't abort, wait a little longer. If we didn't really abort we'd get the
      // rest of the data now and the test would fail:
      waitsFor(someSecondsToPass(2), ASYNC_TEST_TIMEOUT);

      runs(function () {
         // because the request was aborted on index array 5, we got 6 numbers (inc zero)
         // not the whole ten.

         expect(req.root()).toEqual([0, 1, 2, 3, 4, 5]);
      });
   })

   it('gives full json to callback when request finishes', function () {

      oboe.doGet(url('static/json/firstTenNaturalNumbers.json'))
          .done(whenDoneFn);

      waitsFor(function () {
         return !!fullResponse
      }, 'the request to complete', ASYNC_TEST_TIMEOUT)

      runs(function () {
         expect(fullResponse).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
      });
   })

   it('gives header to server side', function () {

      var countGotBack = 0;

      oboe(
          {  url:url('/echoBackHeaders'),
             headers:{'x-snarfu':'SNARF', 'x-foo':'BAR'}
          }

      ).node('x-snarfu',
          function (headerValue) {

             expect(headerValue).toBe('SNARF')
             countGotBack++;

          }).node('x-foo', function (headerValue) {

             expect(headerValue).toBe('BAR')
             countGotBack++;
          })

      waitsFor(function () {
         return countGotBack == 2
      }, 'the request to complete', ASYNC_TEST_TIMEOUT)
   })

   it('can listen for nodes via nodejs-style syntax', function () {

      var countGotBack = 0;

      oboe(
          url('/static/json/firstTenNaturalNumbers.json')
      ).on('node', '!.*', function (number) {
             countGotBack++;
          });

      waitsFor(function () {
         return countGotBack == 10
      }, 'ten callbacks', ASYNC_TEST_TIMEOUT)
   })

   it('can listen for paths via nodejs-style syntax', function () {

      var countGotBack = 0;

      oboe(
          url('/static/json/firstTenNaturalNumbers.json')
      ).on('path', '!.*', function (number) {
             countGotBack++;
          });

      waitsFor(function () {
         return countGotBack == 10
      }, 'ten callbacks', ASYNC_TEST_TIMEOUT)
   })

   it('fires error on 404', function () {

      var gotError = false

      oboe(url('doesNotExist'))
         .fail(function () {

            gotError = true
         });

      waitsFor(function () {
         return gotError
      }, 'the request to fail', ASYNC_TEST_TIMEOUT)
   })

   function someSecondsToPass(waitSecs) {

      function now() {
         // IE8 doesn't have Date.now()
         return new Date().getTime();
      }

      var waitStart = now(),
          waitMs = waitSecs * 1000;

      return function () {
         return now() > (waitStart + waitMs);
      }
   }

   var callbackSpy,
       fullResponse,
       aborted;

   function abortCallback() {
      this.abort();
      aborted = true;
   }

   function theRequestToBeAborted() {
      return aborted
   }

   function whenDoneFn(obj) {
      fullResponse = obj;
   }

   beforeEach(function () {
      aborted = false;
      fullResponse = null;
      callbackSpy = jasmine.createSpy('callbackSpy');
   });

});

<commit_msg>fix some tests to run in the browser properly<commit_after>
describe("oboe integration (real http)", function() {

   var isNode = typeof window === "undefined"

   var oboe =     isNode
               ?  require('../../dist/oboe-node.js')
               :  (window.oboe)
               ;

   var ASYNC_TEST_TIMEOUT = 15 * 1000; // 15 seconds

   function url( path ){
      if( isNode ) {
         return 'localhost:4567/' + path;
      } else {
         return '/testServer/' + path;
      }
   }

   it('gets all expected callbacks by time request finishes', function () {

      oboe(url('tenSlowNumbers'))
          .node('![*]', callbackSpy)
          .done(whenDoneFn);

      waitsFor(function () {
         return !!fullResponse
      }, 'the request to complete', ASYNC_TEST_TIMEOUT);

      runs(function () {

         expect(callbackSpy).toHaveBeenCalledWith(0, [0], [fullResponse, 0]);
         expect(callbackSpy).toHaveBeenCalledWith(1, [1], [fullResponse, 1]);
         expect(callbackSpy).toHaveBeenCalledWith(2, [2], [fullResponse, 2]);
         expect(callbackSpy).toHaveBeenCalledWith(3, [3], [fullResponse, 3]);
         expect(callbackSpy).toHaveBeenCalledWith(4, [4], [fullResponse, 4]);
         expect(callbackSpy).toHaveBeenCalledWith(5, [5], [fullResponse, 5]);
         expect(callbackSpy).toHaveBeenCalledWith(6, [6], [fullResponse, 6]);
         expect(callbackSpy).toHaveBeenCalledWith(7, [7], [fullResponse, 7]);
         expect(callbackSpy).toHaveBeenCalledWith(8, [8], [fullResponse, 8]);
         expect(callbackSpy).toHaveBeenCalledWith(9, [9], [fullResponse, 9]);

      });
   })

   it('can abort once some data has been found in streamed response', function () {

      var req = oboe(url('tenSlowNumbers'))
                  .node('![5]', abortCallback);

      waitsFor(theRequestToBeAborted, 'the request to be aborted', ASYNC_TEST_TIMEOUT);

      // in case we didn't abort, wait a little longer. If we didn't really abort we'd get the
      // rest of the data now and the test would fail:
      waitsFor(someSecondsToPass(2), ASYNC_TEST_TIMEOUT);

      runs(function () {
         // because the request was aborted on index array 5, we got 6 numbers (inc zero)
         // not the whole ten.

         expect(req.root()).toEqual([0, 1, 2, 3, 4, 5]);

      });
   })

   it('can abort once some data has been found in not very streamed response', function () {

      // like above but we're getting a static file not the streamed numbers. This means
      // we'll almost certainly read in the whole response as one onprogress it is on localhost
      // and the json is very small

      var req = oboe(url('static/json/firstTenNaturalNumbers.json'))
                  .node('![5]', abortCallback);

      waitsFor(theRequestToBeAborted, 'the request to be aborted', ASYNC_TEST_TIMEOUT);

      // in case we didn't abort, wait a little longer. If we didn't really abort we'd get the
      // rest of the data now and the test would fail:
      waitsFor(someSecondsToPass(2), ASYNC_TEST_TIMEOUT);

      runs(function () {
         // because the request was aborted on index array 5, we got 6 numbers (inc zero)
         // not the whole ten.

         expect(req.root()).toEqual([0, 1, 2, 3, 4, 5]);
      });
   })

   it('gives full json to callback when request finishes', function () {

      oboe.doGet(url('static/json/firstTenNaturalNumbers.json'))
          .done(whenDoneFn);

      waitsFor(function () {
         return !!fullResponse
      }, 'the request to complete', ASYNC_TEST_TIMEOUT)

      runs(function () {
         expect(fullResponse).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
      });
   })

   it('gives header to server side', function () {

      var countGotBack = 0;

      oboe(
          {  url:url('echoBackHeaders'),
             headers:{'x-snarfu':'SNARF', 'x-foo':'BAR'}
          }

      ).node('x-snarfu', function (headerValue) {

         expect(headerValue).toBe('SNARF')
         countGotBack++;

      }).node('x-foo', function (headerValue) {

         expect(headerValue).toBe('BAR')
         countGotBack++;
      })

      waitsFor(function () {
         return countGotBack == 2
      }, 'the request to complete', ASYNC_TEST_TIMEOUT)
   })

   it('can listen for nodes via nodejs-style syntax', function () {

      var countGotBack = 0;

      oboe(url('static/json/firstTenNaturalNumbers.json'))
         .on('node', '!.*', function (number) {
            countGotBack++;
         });

      waitsFor(function () {
         return countGotBack == 10
      }, 'ten callbacks', ASYNC_TEST_TIMEOUT)
   })

   it('can listen for paths via noeejs-style syntax', function () {

      var countGotBack = 0;

      oboe(url('static/json/firstTenNaturalNumbers.json'))

         .on('path', '!.*', function (number) {
            countGotBack++;
         });

      waitsFor(function () {
         return countGotBack == 10
      }, 'ten callbacks', ASYNC_TEST_TIMEOUT)
   })

   it('fires error on 404', function () {

      var gotError = false

      oboe(url('doesNotExist'))
         .fail(function () {

            gotError = true
         });

      waitsFor(function () {
         return gotError
      }, 'the request to fail', ASYNC_TEST_TIMEOUT)
   })

   function someSecondsToPass(waitSecs) {

      function now() {
         // IE8 doesn't have Date.now()
         return new Date().getTime();
      }

      var waitStart = now(),
          waitMs = waitSecs * 1000;

      return function () {
         return now() > (waitStart + waitMs);
      }
   }

   var callbackSpy,
       fullResponse,
       aborted;

   function abortCallback() {
      this.abort();
      aborted = true;
   }

   function theRequestToBeAborted() {
      return aborted
   }

   function whenDoneFn(obj) {
      fullResponse = obj;
   }

   beforeEach(function () {
      aborted = false;
      fullResponse = null;
      callbackSpy = jasmine.createSpy('callbackSpy');
   });

});

<|endoftext|>


<commit_before>import assert from 'assert';
import ESParser from '../../../src/Parser/ESParser.js';

/** @test {ESParser} */
describe('ESParser', ()=>{
  it('can parse "do expressions"', ()=>{
    const ast = ESParser.parse({experimentalProposal: {doExpressions: true}}, './test/fixture/syntax/DoExpressions.js');
    assert(ast.program.sourceType === 'module');
  });

  it('can parse "function bind"', ()=>{
    const ast = ESParser.parse({experimentalProposal: {functionBind: true}}, './test/fixture/syntax/FunctionBind.js');
    assert(ast.program.sourceType === 'module');
  });

  it('can parse "function sent"', ()=>{
    const ast = ESParser.parse({experimentalProposal: {functionSent: true}}, './test/fixture/syntax/FunctionSent.js');
    assert(ast.program.sourceType === 'module');
  });

  it('can parse "async generators"', ()=>{
    const ast = ESParser.parse({experimentalProposal: {asyncGenerators: false}}, './test/fixture/syntax/AsyncGenerators.js');
    assert(ast.program.sourceType === 'module');
  });
});
<commit_msg>fix(experimental): typo<commit_after>import assert from 'assert';
import ESParser from '../../../src/Parser/ESParser.js';

/** @test {ESParser} */
describe('ESParser', ()=>{
  it('can parse "do expressions"', ()=>{
    const ast = ESParser.parse({experimentalProposal: {doExpressions: true}}, './test/fixture/syntax/DoExpressions.js');
    assert(ast.program.sourceType === 'module');
  });

  it('can parse "function bind"', ()=>{
    const ast = ESParser.parse({experimentalProposal: {functionBind: true}}, './test/fixture/syntax/FunctionBind.js');
    assert(ast.program.sourceType === 'module');
  });

  it('can parse "function sent"', ()=>{
    const ast = ESParser.parse({experimentalProposal: {functionSent: true}}, './test/fixture/syntax/FunctionSent.js');
    assert(ast.program.sourceType === 'module');
  });

  it('can parse "async generators"', ()=>{
    const ast = ESParser.parse({experimentalProposal: {asyncGenerators: true}}, './test/fixture/syntax/AsyncGenerators.js');
    assert(ast.program.sourceType === 'module');
  });
});
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*eslint no-console: 0*/
var parseArgs = require('minimist');
var process = require('process');
var util = require('util');
var path = require('path');
var FakeKafkaServer = require('./kafka-server');
var FakeSentryServer = require('sentry-logger/test/lib/sentry-server');

var BenchmarkRunner = require('tchannel/benchmarks/');

var bahn = path.join(__dirname, 'hyperbahn-worker.js');

function HyperbahnBenchmarkRunner(opts) {
    if (!(this instanceof HyperbahnBenchmarkRunner)) {
        return new HyperbahnBenchmarkRunner(opts);
    }

    var self = this;
    BenchmarkRunner.call(self, opts);
}
util.inherits(HyperbahnBenchmarkRunner, BenchmarkRunner);

HyperbahnBenchmarkRunner.prototype.startFakeSentry =
function startFakeSentry() {
    var self = this;
    self.sentry = FakeSentryServer(onSentry);

    function onSentry(msg) {
    }
};

HyperbahnBenchmarkRunner.prototype.startFakeKafka =
function startFakeKafka() {
    var self = this;
    self.kafka = FakeKafkaServer(onKafkaMessage);

    function onKafkaMessage(msg) {
    }
};

HyperbahnBenchmarkRunner.prototype.spawnRelayServer =
function spawnRelayServer() {
    var self = this;

    self.startFakeKafka();
    self.startFakeSentry();

    var hyperbahnProc = self.run(bahn, [
        '--serverPort', String(self.ports.serverPort),
        '--serverServiceName', String(self.serviceName),
        '--instances', String(self.instanceCount),
        '--workerPort', String(self.ports.relayServerPort),
        '--statsdPort', String(self.ports.statsdPort),
        '--kafkaPort', String(self.kafka.port),
        '--sentryPort', String(self.sentry.address().port)
    ]);
    self.relayProcs.push(hyperbahnProc);
    hyperbahnProc.stdout.pipe(process.stderr);
    hyperbahnProc.stderr.pipe(process.stderr);
};

if (require.main === module) {
    var argv = parseArgs(process.argv.slice(2), {
        '--': true,
        alias: {
            o: 'output'
        },
        boolean: ['relay', 'trace', 'debug', 'noEndpointOverhead']
    });
    var runner = HyperbahnBenchmarkRunner(argv);
    runner.start();
}

function noop () {}
<commit_msg>benchmarks: lint<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*eslint no-console: 0*/
var parseArgs = require('minimist');
var process = require('process');
var util = require('util');
var path = require('path');
var FakeKafkaServer = require('./kafka-server');
var FakeSentryServer = require('sentry-logger/test/lib/sentry-server');

var BenchmarkRunner = require('tchannel/benchmarks/');

var bahn = path.join(__dirname, 'hyperbahn-worker.js');

function HyperbahnBenchmarkRunner(opts) {
    if (!(this instanceof HyperbahnBenchmarkRunner)) {
        return new HyperbahnBenchmarkRunner(opts);
    }

    var self = this;
    BenchmarkRunner.call(self, opts);
}
util.inherits(HyperbahnBenchmarkRunner, BenchmarkRunner);

HyperbahnBenchmarkRunner.prototype.startFakeSentry =
function startFakeSentry() {
    var self = this;
    self.sentry = FakeSentryServer(onSentry);

    function onSentry(msg) {
    }
};

HyperbahnBenchmarkRunner.prototype.startFakeKafka =
function startFakeKafka() {
    var self = this;
    self.kafka = FakeKafkaServer(onKafkaMessage);

    function onKafkaMessage(msg) {
    }
};

HyperbahnBenchmarkRunner.prototype.spawnRelayServer =
function spawnRelayServer() {
    var self = this;

    self.startFakeKafka();
    self.startFakeSentry();

    var hyperbahnProc = self.run(bahn, [
        '--serverPort', String(self.ports.serverPort),
        '--serverServiceName', String(self.serviceName),
        '--instances', String(self.instanceCount),
        '--workerPort', String(self.ports.relayServerPort),
        '--statsdPort', String(self.ports.statsdPort),
        '--kafkaPort', String(self.kafka.port),
        '--sentryPort', String(self.sentry.address().port)
    ]);
    self.relayProcs.push(hyperbahnProc);
    hyperbahnProc.stdout.pipe(process.stderr);
    hyperbahnProc.stderr.pipe(process.stderr);
};

if (require.main === module) {
    var argv = parseArgs(process.argv.slice(2), {
        '--': true,
        alias: {
            o: 'output'
        },
        boolean: ['relay', 'trace', 'debug', 'noEndpointOverhead']
    });
    var runner = HyperbahnBenchmarkRunner(argv);
    runner.start();
}
<|endoftext|>


<commit_before>var _ = require('lodash'),
    dynamicVariables = require('../../lib/superstring/dynamic-variables'),
    expect = require('chai').expect;

describe('Dynamic variable', function () {
    it('should have all attributes', function () {
        expect(dynamicVariables).to.be.an('object');
        _.forOwn(dynamicVariables, function (dynamicVariable) {
            expect(dynamicVariable).to.be.an('object');
            expect(dynamicVariable.description).to.be.a('string');
            expect(dynamicVariable.generator).to.be.a('function');
        });
    });

    describe('generator', function () {
        it('should return random data', function () {
            _.forOwn(dynamicVariables, function (variable) {
                expect(variable.generator()).to.not.be.undefined;
            });
        });

        it('should start with $', function () {
            _.forOwn(dynamicVariables, function (variable, name) {
                expect(name[0]).to.equal('$');
            });
        });

        it('$randomInt should return a random number', function () {
            expect(dynamicVariables.$randomInt.generator()).to.be.within(0, 1000);
        });

        it('$timeStamp should return a valid timestamp', function () {
            expect(dynamicVariables.$timestamp.generator()).to.be.a('number');
        });

        it('$guid should return a valid uuid', function () {
            expect(dynamicVariables.$guid.generator())
                .to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
        });

        it('$randomPhoneNumber returns a random phone number without extension', function () {
            var phone1 = dynamicVariables.$randomPhoneNumber.generator(),
                phone2 = dynamicVariables.$randomPhoneNumber.generator();

            expect(phone1.length).to.equal(12);
            expect(phone2.length).to.equal(12);
            expect(phone1).to.not.equal(phone2);
        });

        it('$randomLocale returns a random locale', function () {
            var locale1 = dynamicVariables.$randomLocale.generator(),
                locale2 = dynamicVariables.$randomLocale.generator();

            expect(locale1.length).to.be.at.least(2).and.at.most(3);
            expect(locale2.length).to.be.at.least(2).and.at.most(3);
            expect(locale1).to.not.equal(locale2);
        });

        it('$randomPhoneNumberExt returns a random phone number with extension', function () {
            var phone1 = dynamicVariables.$randomPhoneNumberExt.generator(),
                phone2 = dynamicVariables.$randomPhoneNumberExt.generator();

            expect(phone1.length).to.be.at.least(14);
            expect(phone2.length).to.be.at.least(14);
            expect(phone1).to.not.equal(phone2);
        });

        it('$randomWords returns some random numbers', function () {
            var words = dynamicVariables.$randomWords.generator(),
                wordsArray = words.split(' ');

            expect(words).to.not.be.null;
            expect(wordsArray.length).to.be.at.least(2);
        });

        it('$randomFilePath returns a file path', function () {
            var filePath = dynamicVariables.$randomFilePath.generator();

            expect(filePath).to.not.be.undefined;
            expect(filePath).to.not.be.null;
        });

        it('$randomDirectoryPath returns a directory path', function () {
            var directoryPath = dynamicVariables.$randomDirectoryPath.generator();

            expect(directoryPath).to.not.be.undefined;
            expect(directoryPath).to.not.be.null;
        });
    });
});
<commit_msg>Add test to verify timestamp generator returns valid result<commit_after>var _ = require('lodash'),
    dynamicVariables = require('../../lib/superstring/dynamic-variables'),
    expect = require('chai').expect;

describe('Dynamic variable', function () {
    it('should have all attributes', function () {
        expect(dynamicVariables).to.be.an('object');
        _.forOwn(dynamicVariables, function (dynamicVariable) {
            expect(dynamicVariable).to.be.an('object');
            expect(dynamicVariable.description).to.be.a('string');
            expect(dynamicVariable.generator).to.be.a('function');
        });
    });

    describe('generator', function () {
        it('should return random data', function () {
            _.forOwn(dynamicVariables, function (variable) {
                expect(variable.generator()).to.not.be.undefined;
            });
        });

        it('should start with $', function () {
            _.forOwn(dynamicVariables, function (variable, name) {
                expect(name[0]).to.equal('$');
            });
        });

        it('$randomInt should return a random number', function () {
            expect(dynamicVariables.$randomInt.generator()).to.be.within(0, 1000);
        });

        it('$timeStamp should return a valid timestamp', function () {
            expect(dynamicVariables.$timestamp.generator()).to.be.a('number');
        });

        it('$isoTimestamp returns a timestamp in ISO format', function () {
            var isoTimestamp = dynamicVariables.$isoTimestamp.generator(),
                // eslint-disable-next-line security/detect-non-literal-regexp
                regex = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})' + // match year
                    '-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])' + // match month and day
                    'T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.[0-9]+)?(Z)?$'); // match time

            expect(isoTimestamp).to.be.a('string');
            expect(isoTimestamp).to.match(regex);
        });

        it('$guid should return a valid uuid', function () {
            expect(dynamicVariables.$guid.generator())
                .to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
        });

        it('$randomPhoneNumber returns a random phone number without extension', function () {
            var phone1 = dynamicVariables.$randomPhoneNumber.generator(),
                phone2 = dynamicVariables.$randomPhoneNumber.generator();

            expect(phone1.length).to.equal(12);
            expect(phone2.length).to.equal(12);
            expect(phone1).to.not.equal(phone2);
        });

        it('$randomLocale returns a random locale', function () {
            var locale1 = dynamicVariables.$randomLocale.generator(),
                locale2 = dynamicVariables.$randomLocale.generator();

            expect(locale1.length).to.be.at.least(2).and.at.most(3);
            expect(locale2.length).to.be.at.least(2).and.at.most(3);
            expect(locale1).to.not.equal(locale2);
        });

        it('$randomPhoneNumberExt returns a random phone number with extension', function () {
            var phone1 = dynamicVariables.$randomPhoneNumberExt.generator(),
                phone2 = dynamicVariables.$randomPhoneNumberExt.generator();

            expect(phone1.length).to.be.at.least(14);
            expect(phone2.length).to.be.at.least(14);
            expect(phone1).to.not.equal(phone2);
        });

        it('$randomWords returns some random numbers', function () {
            var words = dynamicVariables.$randomWords.generator(),
                wordsArray = words.split(' ');

            expect(words).to.not.be.null;
            expect(wordsArray.length).to.be.at.least(2);
        });

        it('$randomFilePath returns a file path', function () {
            var filePath = dynamicVariables.$randomFilePath.generator();

            expect(filePath).to.not.be.undefined;
            expect(filePath).to.not.be.null;
        });

        it('$randomDirectoryPath returns a directory path', function () {
            var directoryPath = dynamicVariables.$randomDirectoryPath.generator();

            expect(directoryPath).to.not.be.undefined;
            expect(directoryPath).to.not.be.null;
        });
    });
});
<|endoftext|>


<commit_before>/**
 * @fileOverview Testing the Entity Middleware and "before", "after" methods.
 */

var sinon  = require('sinon');
var chai = require('chai');
// var sinon = require('sinon');
var assert = chai.assert;

var Entity = require('../../');

var noop = function(){};

setup(function() {});
teardown(function() {});

// The numbering (e.g. 1.1.1) has nothing to do with order
// The purpose is to provide a unique string so specific tests are
// run by using the mocha --grep "1.1.1" option.

suite('4.11 Entity Middleware and "before", "after" methods', function() {
  test('4.11.1 surface tests', function() {
    var EntityOne = Entity.extend(function() {
      this.method('create', this._create.bind(this));
    });

    EntityOne.prototype._create = noop;

    var entityOne = new EntityOne();

    assert.isFunction(entityOne.create, 'a "create" method should exist');
    assert.isFunction(entityOne.create.use, 'a "create.use" method should exist');
    assert.isFunction(entityOne.create.before, 'a "create.before" method should exist');
    assert.isFunction(entityOne.create.after, 'a "create.after" method should exist');
  });

  test('4.11.1 Proper sequence of execution', function() {
    var stubBeforeOne = sinon.stub();
    var stubBeforeTwo = sinon.stub();
    var stubAfterOne = sinon.stub();
    var stubAfterTwo = sinon.stub();
    var stubActual = sinon.stub();

    var EntityOne = Entity.extend(function() {
      this.method('create', this._create.bind(this));

      this.create.before(stubBeforeOne);
      this.create.before(stubBeforeTwo);
      this.create.after(stubAfterOne);
      this.create.after(stubAfterTwo);
    });

    EntityOne.prototype._create = stubActual;

    var entityOne = new EntityOne();

    entityOne.create();

    assert(stubBeforeOne.calledBefore(stubBeforeTwo), 'stubABeforeOne() before stubBeforeTwo()');
    assert(stubBeforeTwo.calledBefore(stubActual), 'stubBeforeTwo() before stubActual()');
    assert(stubActual.calledBefore(stubAfterOne), 'stubActual() before stubAfterOne()');
    assert(stubAfterOne.calledBefore(stubAfterTwo), 'stubAfterOne() before stubAfterTwo()');
  });
});
<commit_msg>styling edits<commit_after>/**
 * @fileOverview Testing the Entity Middleware and "before", "after" methods.
 */

var sinon  = require('sinon');
var chai = require('chai');
// var sinon = require('sinon');
var assert = chai.assert;

var Entity = require('../../');

var noop = function(){};

setup(function() {});
teardown(function() {});

// The numbering (e.g. 1.1.1) has nothing to do with order
// The purpose is to provide a unique string so specific tests are
// run by using the mocha --grep "1.1.1" option.

suite('4.11 Entity Middleware and "before", "after" methods', function() {
  test('4.11.1 surface tests', function() {
    var entityOne = Entity.extend(function() {
      this.method('create', this._create.bind(this));
    });

    entityOne.prototype._create = noop;

    var ent = entityOne();

    assert.isFunction(ent.create, 'a "create" method should exist');
    assert.isFunction(ent.create.use, 'a "create.use" method should exist');
    assert.isFunction(ent.create.before, 'a "create.before" method should exist');
    assert.isFunction(ent.create.after, 'a "create.after" method should exist');
  });

  test('4.11.1 Proper sequence of execution', function() {
    var stubBeforeOne = sinon.stub();
    var stubBeforeTwo = sinon.stub();
    var stubAfterOne = sinon.stub();
    var stubAfterTwo = sinon.stub();
    var stubActual = sinon.stub();

    var entityOne = Entity.extend(function() {
      this.method('create', this._create.bind(this));

      this.create.before(stubBeforeOne);
      this.create.before(stubBeforeTwo);
      this.create.after(stubAfterOne);
      this.create.after(stubAfterTwo);
    });

    entityOne.prototype._create = stubActual;

    entityOne().create();

    assert(stubBeforeOne.calledBefore(stubBeforeTwo), 'stubABeforeOne() before stubBeforeTwo()');
    assert(stubBeforeTwo.calledBefore(stubActual), 'stubBeforeTwo() before stubActual()');
    assert(stubActual.calledBefore(stubAfterOne), 'stubActual() before stubAfterOne()');
    assert(stubAfterOne.calledBefore(stubAfterTwo), 'stubAfterOne() before stubAfterTwo()');
  });
});
<|endoftext|>


<commit_before>var GeoPackageAPI = window.geopackage;
var geopackageMap = L.map('geopackage-map').setView([38.625800, -90.189933], 14);
L.tileLayer('http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.png', {
  attribution: 'Source: Esri, DigitalGlobe, GeoEye, Earthstar Geographics, CNES/Airbus DS, USDA, USGS, AeroGRID, IGN, and the GIS User Community. OpenStreetMap.'
}).addTo(geopackageMap);

window.onload = function () {
  window.loadUrl(./StLouis.gpkg");
}

window.loadUrl = function(url) {
  fileName = url.split('/').pop();
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'arraybuffer';

  xhr.onload = function(e) {
    var uInt8Array = new Uint8Array(this.response);
    loadByteArray(uInt8Array);
  };
  xhr.send();
}

function loadByteArray(array, callback) {
  GeoPackageAPI.openGeoPackageByteArray(array, function(err, geoPackage) { // Now you can operate on the GeoPackage
    // Get the tile table names
    geoPackage.getTileTables(function(err, tileTableNames) {
      geoPackage.getTileDaoWithTableName(tileTableNames[0], function(err, tileDao) { // We know we have one tile layer, loop if you have more.
      var maxZoom = tileDao.maxWebMapZoom;
      var minZoom = tileDao.minWebMapZoom;
      var tableLayer = new L.GridLayer({noWrap: true, minZoom: minZoom, maxZoom: maxZoom});
      tableLayer.createTile = function(tilePoint, done) {
        var canvas = L.DomUtil.create('canvas', 'leaflet-tile');
        var size = this.getTileSize();
        canvas.width = size.x;
        canvas.height = size.y;
        setTimeout(function() {
          console.time('Draw tile ' + tilePoint.x + ', ' + tilePoint.y + ' zoom: ' + tilePoint.z);
          GeoPackageAPI.drawXYZTileInCanvas(geoPackage, tileTableNames[0], tilePoint.x, tilePoint.y, tilePoint.z, size.x, size.y, canvas, function(err) {
            console.timeEnd('Draw tile ' + tilePoint.x + ', ' + tilePoint.y + ' zoom: ' + tilePoint.z);
            done(err, canvas);
          });
        }, 0);
        return canvas;
      }
      geopackageMap.addLayer(tableLayer);
      tableLayer.bringToFront();
      });
    });

    // Get the feature table names
    geoPackage.getFeatureTables(function(err, featureTableNames) {
      for (var i = 0; i < featureTableNames.length; i++) {
        geoPackage.getFeatureDaoWithTableName(featureTableNames[i], function(err, featureDao) {
          geoPackage.getInfoForTable(featureDao, function(err, info) {

            // query for all features
            featureDao.queryForEach(function(err, row, rowDone) {
              var feature = featureDao.getFeatureRow(row);
              var geometry = feature.getGeometry();
              if (geometry) {
                // Make the information into something we can display on the map with leaflet
                var geom = geometry.geometry;
                var geoJson = geometry.geometry.toGeoJSON();
                geoJson.properties = {};
                geoJson.properties["table_name"] = feature.featureTable.table_name;

                // map the values from the feature table into GeoJSON properties we can use to style the map and show a popup
                for (var key in feature.values) {
                  if(feature.values.hasOwnProperty(key) && key != feature.getGeometryColumn().name) {
                    var column = info.columnMap[key];
                    geoJson.properties[column.displayName] = feature.values[key];
                  }
                }
                geojsonLayer.addData(geoJson);
              }
              rowDone();
            });
          });
        });
      }
    });
  });

  var geojsonLayer = L.geoJson([], {
      style: function (feature) { // Style the polygons
          return {
            color: "#000",
            weight: 2,
            opacity: 1,
            fillColor: "#093"
          };
      },
      onEachFeature: function (feature, layer) {
        layer.bindPopup("
" + feature.properties.name + "
");

        if (feature.properties.table_name == "Pizza") {
          layer.setIcon(pizzaIcon);
        } else if (feature.properties.table_name == "PointsOfInterest") {
          layer.setIcon(poiIcon);
        }
      }
  }).addTo(geopackageMap);

  // Configure the icons that we want to use to style our data
  var pizzaIcon = L.icon({
    iconUrl: 'pizza.png',
    shadowUrl: 'shadow.png',
    iconSize: [32, 40],
    shadowSize: [32, 38],
    iconAnchor: [16, 40],
    shadowAnchor: [12, 32],
    popupAnchor: [0, -64]
  });

  var poiIcon = L.icon({
    iconUrl: 'poi.png',
    shadowUrl: 'shadow.png',
    iconSize: [32, 40],
    shadowSize: [32, 38],
    iconAnchor: [16, 40],
    shadowAnchor: [12, 32],
    popupAnchor: [0, -64]
  });
}
<commit_msg>adding quotes<commit_after>var GeoPackageAPI = window.geopackage;
var geopackageMap = L.map('geopackage-map').setView([38.625800, -90.189933], 14);
L.tileLayer('http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.png', {
  attribution: 'Source: Esri, DigitalGlobe, GeoEye, Earthstar Geographics, CNES/Airbus DS, USDA, USGS, AeroGRID, IGN, and the GIS User Community. OpenStreetMap.'
}).addTo(geopackageMap);

window.onload = function () {
  window.loadUrl("./StLouis.gpkg");
}

window.loadUrl = function(url) {
  fileName = url.split('/').pop();
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'arraybuffer';

  xhr.onload = function(e) {
    var uInt8Array = new Uint8Array(this.response);
    loadByteArray(uInt8Array);
  };
  xhr.send();
}

function loadByteArray(array, callback) {
  GeoPackageAPI.openGeoPackageByteArray(array, function(err, geoPackage) { // Now you can operate on the GeoPackage
    // Get the tile table names
    geoPackage.getTileTables(function(err, tileTableNames) {
      geoPackage.getTileDaoWithTableName(tileTableNames[0], function(err, tileDao) { // We know we have one tile layer, loop if you have more.
      var maxZoom = tileDao.maxWebMapZoom;
      var minZoom = tileDao.minWebMapZoom;
      var tableLayer = new L.GridLayer({noWrap: true, minZoom: minZoom, maxZoom: maxZoom});
      tableLayer.createTile = function(tilePoint, done) {
        var canvas = L.DomUtil.create('canvas', 'leaflet-tile');
        var size = this.getTileSize();
        canvas.width = size.x;
        canvas.height = size.y;
        setTimeout(function() {
          console.time('Draw tile ' + tilePoint.x + ', ' + tilePoint.y + ' zoom: ' + tilePoint.z);
          GeoPackageAPI.drawXYZTileInCanvas(geoPackage, tileTableNames[0], tilePoint.x, tilePoint.y, tilePoint.z, size.x, size.y, canvas, function(err) {
            console.timeEnd('Draw tile ' + tilePoint.x + ', ' + tilePoint.y + ' zoom: ' + tilePoint.z);
            done(err, canvas);
          });
        }, 0);
        return canvas;
      }
      geopackageMap.addLayer(tableLayer);
      tableLayer.bringToFront();
      });
    });

    // Get the feature table names
    geoPackage.getFeatureTables(function(err, featureTableNames) {
      for (var i = 0; i < featureTableNames.length; i++) {
        geoPackage.getFeatureDaoWithTableName(featureTableNames[i], function(err, featureDao) {
          geoPackage.getInfoForTable(featureDao, function(err, info) {

            // query for all features
            featureDao.queryForEach(function(err, row, rowDone) {
              var feature = featureDao.getFeatureRow(row);
              var geometry = feature.getGeometry();
              if (geometry) {
                // Make the information into something we can display on the map with leaflet
                var geom = geometry.geometry;
                var geoJson = geometry.geometry.toGeoJSON();
                geoJson.properties = {};
                geoJson.properties["table_name"] = feature.featureTable.table_name;

                // map the values from the feature table into GeoJSON properties we can use to style the map and show a popup
                for (var key in feature.values) {
                  if(feature.values.hasOwnProperty(key) && key != feature.getGeometryColumn().name) {
                    var column = info.columnMap[key];
                    geoJson.properties[column.displayName] = feature.values[key];
                  }
                }
                geojsonLayer.addData(geoJson);
              }
              rowDone();
            });
          });
        });
      }
    });
  });

  var geojsonLayer = L.geoJson([], {
      style: function (feature) { // Style the polygons
          return {
            color: "#000",
            weight: 2,
            opacity: 1,
            fillColor: "#093"
          };
      },
      onEachFeature: function (feature, layer) {
        layer.bindPopup("
" + feature.properties.name + "
");

        if (feature.properties.table_name == "Pizza") {
          layer.setIcon(pizzaIcon);
        } else if (feature.properties.table_name == "PointsOfInterest") {
          layer.setIcon(poiIcon);
        }
      }
  }).addTo(geopackageMap);

  // Configure the icons that we want to use to style our data
  var pizzaIcon = L.icon({
    iconUrl: 'pizza.png',
    shadowUrl: 'shadow.png',
    iconSize: [32, 40],
    shadowSize: [32, 38],
    iconAnchor: [16, 40],
    shadowAnchor: [12, 32],
    popupAnchor: [0, -64]
  });

  var poiIcon = L.icon({
    iconUrl: 'poi.png',
    shadowUrl: 'shadow.png',
    iconSize: [32, 40],
    shadowSize: [32, 38],
    iconAnchor: [16, 40],
    shadowAnchor: [12, 32],
    popupAnchor: [0, -64]
  });
}
<|endoftext|>