<commit_before>// Karma configuration
// Generated on Fri Feb 17 2017 15:57:25 GMT+0800 (中国标准时间)

module.exports = function (config) {
    // 设置测试的超时时间

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'browserify'],

        browserify: {
            debug: true,
            transform: [
                [require('babelify'), {
                    presets: ["env"],
                    ignore: ["**/libs/**"],
                    plugins: ['istanbul']
                }],
                [require('browserify-css'), {global: true}],
                require('browserify-imgify')
            ]
        },

        // list of files  patterns to load in the browser
        // false 表示初始化的时候不会使用 script 标签直接将相关 js 引入到浏览器，需要自己写代码加载, 注意添加顺序
        files: [
            /***测试文件***/
            './tool/**.js',
            './resources/**.js',
            /***classic的源码***/
            /*由于除了classic其他都不依赖于8c,所以classic 的引入放在最后，以免被common覆盖*/
            {pattern: '../src/classic/libs/SuperMap_Basic-8.1.1-16520.js', include: false},
            {pattern: '../src/classic/libs/Lang/*.js', include: false},
            {pattern: '../src/classic/theme/default/*.css', include: false},
            /**测试文件**/
            // './test-main-classic.js',

            /***common的源码***/
            '../src/common/**/*.js',
            /**测试文件**/

            './test-main-common.js',

            /***leaflet的源码***/
            {pattern: '../node_modules/leaflet/dist/leaflet.css', include: false},
            {pattern: '../src/leaflet/**/**/*.css', include: false},
            '../src/leaflet/**/!(ClientComputationView|index).js',
            /**测试文件**/
            './test-main-leaflet.js',

            /***openlayers的源码***/
            {pattern: '../node_modules/openlayers/dist/ol-debug.css', include: false},
            {pattern: '../src/openlayers/**/**/*.css', include: false},
            '../src/openlayers/**/!(index).js',
            /**测试文件**/
            './test-main-openlayers.js',

            /***mapboxgl***/
            {pattern: '../node_modules/mapbox-gl/dist/mapbox-gl.css', include: false},
            '../src/mapboxgl/**/!(index).js',
            /**测试文件**/
            './test-main-mapboxgl.js'
        ],

        // list of files to exclude 测试时排除的文件
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '../node_modules/whatwg-fetch-importable/whatwgFetch.js': ['browserify'],
            '../node_modules/fetch-jsonp/build/fetch-jsonp.js': ['browserify'],
            '../src/classic/libs/SuperMap_Basic-8.1.1-16520.js': ['browserify'],
            '../src/classic/libs/Lang/*.js': ['browserify'],
            '../src/classic/**/!(index).js': ['browserify'],
            './classic/**/*Spec.js': ['browserify'],
            './test-main-classic.js': ['browserify'],

            '../src/common/**/*.js': ['browserify'],
            './common/**/*Spec.js': ['browserify'],
            './test-main-common.js': ['browserify'],

            '../node_modules/leaflet/dist/leaflet-src.js': ['browserify'],
            '../src/leaflet/**/!(ClientComputationView|index).js': ['browserify'],
            './leaflet/**/*Spec.js': ['browserify'],
            './test-main-leaflet.js': ['browserify'],

            '../node_modules/openlayers/dist/ol-debug.js': ['browserify'],
            '../src/openlayers/**/!(index).js': ['browserify'],
            './openlayers/**/*Spec.js': ['browserify'],
            './test-main-openlayers.js': ['browserify'],

            '../node_modules/mapbox-gl/dist/mapbox-gl-dev.js': ['browserify'],
            '../src/mapboxgl/**/!(index).js': ['browserify'],
            './mapboxgl/**/*Spec.js': ['browserify'],
            './test-main-mapboxgl.js': ['browserify']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage', 'teamcity'],

        //最大超时时间
        captureTimeout: 120000,
        browserNoActivityTimeout: 120000,
        browserDisconnectTimeout: 20000,

        coverageReporter: {
            dir: 'testcoverage/',
            reporters: [
                {type: 'lcov', subdir: '.'}
            ]
        }
        ,

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity

    })
};
<commit_msg>还原误提交的文件 karma<commit_after>// Karma configuration
// Generated on Fri Feb 17 2017 15:57:25 GMT+0800 (中国标准时间)

module.exports = function (config) {
    // 设置测试的超时时间

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'browserify'],

        browserify: {
            debug: true,
            transform: [
                [require('babelify'), {
                    presets: ["env"],
                    ignore: ["**/libs/**"],
                    plugins: ['istanbul']
                }],
                [require('browserify-css'), {global: true}],
                require('browserify-imgify')
            ]
        },

        // list of files  patterns to load in the browser
        // false 表示初始化的时候不会使用 script 标签直接将相关 js 引入到浏览器，需要自己写代码加载, 注意添加顺序
        files: [
            /***测试文件***/
            './tool/**.js',
            './resources/**.js',
            /***classic的源码***/
            /*由于除了classic其他都不依赖于8c,所以classic 的引入放在最后，以免被common覆盖*/
            {pattern: '../src/classic/libs/SuperMap_Basic-8.1.1-16520.js', include: false},
            {pattern: '../src/classic/libs/Lang/*.js', include: false},
            {pattern: '../src/classic/theme/default/*.css', include: false},
            /**测试文件**/
             './test-main-classic.js',

            /***common的源码***/
            '../src/common/**/*.js',
            /**测试文件**/

            './test-main-common.js',

            /***leaflet的源码***/
            {pattern: '../node_modules/leaflet/dist/leaflet.css', include: false},
            {pattern: '../src/leaflet/**/**/*.css', include: false},
            '../src/leaflet/**/!(ClientComputationView|index).js',
            /**测试文件**/
            './test-main-leaflet.js',

            /***openlayers的源码***/
            {pattern: '../node_modules/openlayers/dist/ol-debug.css', include: false},
            {pattern: '../src/openlayers/**/**/*.css', include: false},
            '../src/openlayers/**/!(index).js',
            /**测试文件**/
            './test-main-openlayers.js',

            /***mapboxgl***/
            {pattern: '../node_modules/mapbox-gl/dist/mapbox-gl.css', include: false},
            '../src/mapboxgl/**/!(index).js',
            /**测试文件**/
            './test-main-mapboxgl.js'
        ],

        // list of files to exclude 测试时排除的文件
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '../node_modules/whatwg-fetch-importable/whatwgFetch.js': ['browserify'],
            '../node_modules/fetch-jsonp/build/fetch-jsonp.js': ['browserify'],
            '../src/classic/libs/SuperMap_Basic-8.1.1-16520.js': ['browserify'],
            '../src/classic/libs/Lang/*.js': ['browserify'],
            '../src/classic/**/!(index).js': ['browserify'],
            './classic/**/*Spec.js': ['browserify'],
            './test-main-classic.js': ['browserify'],

            '../src/common/**/*.js': ['browserify'],
            './common/**/*Spec.js': ['browserify'],
            './test-main-common.js': ['browserify'],

            '../node_modules/leaflet/dist/leaflet-src.js': ['browserify'],
            '../src/leaflet/**/!(ClientComputationView|index).js': ['browserify'],
            './leaflet/**/*Spec.js': ['browserify'],
            './test-main-leaflet.js': ['browserify'],

            '../node_modules/openlayers/dist/ol-debug.js': ['browserify'],
            '../src/openlayers/**/!(index).js': ['browserify'],
            './openlayers/**/*Spec.js': ['browserify'],
            './test-main-openlayers.js': ['browserify'],

            '../node_modules/mapbox-gl/dist/mapbox-gl-dev.js': ['browserify'],
            '../src/mapboxgl/**/!(index).js': ['browserify'],
            './mapboxgl/**/*Spec.js': ['browserify'],
            './test-main-mapboxgl.js': ['browserify']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage', 'teamcity'],

        //最大超时时间
        captureTimeout: 120000,
        browserNoActivityTimeout: 120000,
        browserDisconnectTimeout: 20000,

        coverageReporter: {
            dir: 'testcoverage/',
            reporters: [
                {type: 'lcov', subdir: '.'}
            ]
        }
        ,

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity

    })
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on 2016-03-07

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    // as well as any additional frameworks (requirejs/chai/sinon/...)
    frameworks: [
      'jasmine'
    ],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/angular/angular.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-cookies/angular-cookies.js',
      'bower_components/angular-resource/angular-resource.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/angular-sanitize/angular-sanitize.js',
      'bower_components/angular-touch/angular-touch.js',
      'bower_components/angular-translate/angular-translate.js',
      'bower_components/angular-messages/angular-messages.js',
      'bower_components/angular-aria/angular-aria.js',
      'bower_components/angular-material/angular-material.js',
      'bower_components/angular-material-icons/angular-material-icons.min.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 8080,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'Firefox'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-firefox-launcher'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<commit_msg>Apricot-0000 Updated test browser<commit_after>// Karma configuration
// Generated on 2016-03-07

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    // as well as any additional frameworks (requirejs/chai/sinon/...)
    frameworks: [
      'jasmine'
    ],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/angular/angular.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-cookies/angular-cookies.js',
      'bower_components/angular-resource/angular-resource.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/angular-sanitize/angular-sanitize.js',
      'bower_components/angular-touch/angular-touch.js',
      'bower_components/angular-translate/angular-translate.js',
      'bower_components/angular-messages/angular-messages.js',
      'bower_components/angular-aria/angular-aria.js',
      'bower_components/angular-material/angular-material.js',
      'bower_components/angular-material-icons/angular-material-icons.min.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 8080,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'Chrome'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-firefox-launcher'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<|endoftext|>


<commit_before>var
	chai = require('chai'),
	should = chai.should();

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

	var
		filterLib = null,
		mongoose = require('mongoose'),
		orClauseItems = [],
		whereClause = {};

	var Kitteh = mongoose.model('kittehs-filter', new mongoose.Schema({
		birthday : { type : Date, default : Date.now },
		features : {
			color : String,
			isFurreh : Boolean
		},
		isDead: Boolean,
		home : String,
		name : String,
		peePatches : [String]
	}));

	before(function () {
		filterLib = require('../../lib/filter')(mongoose);

		mongoose.Query.prototype.or = function (clause) {
			if (clause) {
				orClauseItems.push(clause);
			}
		};

		mongoose.Query.prototype.where = function (key, val) {
			whereClause[key] = val;
		};
	});

	beforeEach(function () {
		orClauseItems = [];
		whereClause = {};
	});

	it ('should return a query when created', function () {
		var query = Kitteh
			.find()
			.filter(null);

		(query instanceof mongoose.Query).should.equals(true);
	});

	it ('should apply both mandatory and optional filters when both are supplied', function () {
		var options = {
			filters : {
				mandatory : {
					contains : {
						name : 'cat'
					}
				},
				optional : {
					exact : {
						'features.color' : 'brindle'
					}
				}
			}
		};

		var query = Kitteh
			.find()
			.filter(options);

		should.exist(query);
		should.exist(whereClause.name);
		orClauseItems.should.have.length(1);
	});

	describe('mandatory filters', function () {
		it ('should look for occurrences of a term within a string using contains', function () {
			var options = {
				filters : {
					mandatory : {
						contains : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.name);
			whereClause.name.test('cat').should.equals(true);
			whereClause.name.test('a cat exists').should.equals(true);
			whereClause.name.test('dog').should.equals(false);
		});

		it ('should look for occurrences of a term at the start of a string using endsWith', function () {
			var options = {
				filters : {
					mandatory : {
						endsWith : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.name);
			whereClause.name.test('cat').should.equals(true);
			whereClause.name.test('cool cat').should.equals(true);
			whereClause.name.test('this cat is sick').should.equals(false);
		});

		it ('should look for occurrences of a term at the start of a string using startsWith', function () {
			var options = {
				filters : {
					mandatory : {
						startsWith : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.name);
			whereClause.name.test('cat').should.equals(true);
			whereClause.name.test('cat exists').should.equals(true);
			whereClause.name.test('this cat is sick').should.equals(false);
		});

		it ('should look for occurrences of an exact match of the term when using exact', function () {
			var options = {
				filters : {
					mandatory : {
						exact : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.name);
			whereClause.name.test('cat').should.equals(true);
			whereClause.name.test('cat litter').should.equals(false);
			whereClause.name.test('the cat').should.equals(false);
		});

	it ('should look for occurrences of an exact match of the object when using exact', function () {
		var options = {
			filters : {
				mandatory : {
					exact : {
						isDead : false
					}
				}
			}
		};

		var query = Kitteh
			.find()
			.filter(options);

			should.exist(query);
			should.exist(whereClause.isDead);
			whereClause.isDead.should.equals(false);
		});
	});

	describe('optional filters', function () {
		it ('should look for occurrences of a term within a string using contains', function () {
			var options = {
				filters : {
					optional : {
						contains : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][0].name.test('a cat exists').should.equals(true);
			orClauseItems[0][0].name.test('dog').should.equals(false);
		});

		it ('should look for occurrences of a term at the start of a string using endsWith', function () {
			var options = {
				filters : {
					optional : {
						endsWith : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][0].name.test('cool cat').should.equals(true);
			orClauseItems[0][0].name.test('this cat is sick').should.equals(false);
		});

		it ('should look for occurrences of a term at the start of a string using startsWith', function () {
			var options = {
				filters : {
					optional : {
						startsWith : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][0].name.test('cat exists').should.equals(true);
			orClauseItems[0][0].name.test('this cat is sick').should.equals(false);
		});

		it ('should look for occurrences of an exact match of the term when using exact', function () {
			var options = {
				filters : {
					optional : {
						exact : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][0].name.test('cat litter').should.equals(false);
			orClauseItems[0][0].name.test('the cat').should.equals(false);
		});

        it ('should look for occurrences of an exact match of the object when using exact', function () {
            var options = {
                filters : {
                    optional : {
                        exact : {
                            isDead : true
                        }
                    }
                }
            };

            var query = Kitteh
                .find()
                .filter(options);

            should.exist(query);
            orClauseItems.should.have.length(1);
            orClauseItems[0][0].isDead.should.equals(true);
            //orClauseItems[0][0].name.test('cat litter').should.equals(false);
            //orClauseItems[0][0].name.test('the cat').should.equals(false);
        });

		it ('should look for multiple occurrences of a match when supplying an array', function () {
			var options = {
				filters : {
					optional : {
						exact : {
							name : ['cat', 'Kitteh']
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][1].name.test('Kitteh').should.equals(true);
		});
	});
});
<commit_msg>adding test for number exact match test<commit_after>var
	chai = require('chai'),
	should = chai.should();

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

	var
		filterLib = null,
		mongoose = require('mongoose'),
		orClauseItems = [],
		whereClause = {};

	var Kitteh = mongoose.model('kittehs-filter', new mongoose.Schema({
		birthday : { type : Date, default : Date.now },
		features : {
			color : String,
			isFurreh : Boolean
		},
		id : Number,
		isDead: Boolean,
		home : String,
		name : String,
		peePatches : [String]
	}));

	before(function () {
		filterLib = require('../../lib/filter')(mongoose);

		mongoose.Query.prototype.or = function (clause) {
			if (clause) {
				orClauseItems.push(clause);
			}
		};

		mongoose.Query.prototype.where = function (key, val) {
			whereClause[key] = val;
		};
	});

	beforeEach(function () {
		orClauseItems = [];
		whereClause = {};
	});

	it ('should return a query when created', function () {
		var query = Kitteh
			.find()
			.filter(null);

		(query instanceof mongoose.Query).should.equals(true);
	});

	it ('should apply both mandatory and optional filters when both are supplied', function () {
		var options = {
			filters : {
				mandatory : {
					contains : {
						name : 'cat'
					}
				},
				optional : {
					exact : {
						'features.color' : 'brindle'
					}
				}
			}
		};

		var query = Kitteh
			.find()
			.filter(options);

		should.exist(query);
		should.exist(whereClause.name);
		orClauseItems.should.have.length(1);
	});

	describe('mandatory filters', function () {
		it ('should look for occurrences of a term within a string using contains', function () {
			var options = {
				filters : {
					mandatory : {
						contains : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.name);
			whereClause.name.test('cat').should.equals(true);
			whereClause.name.test('a cat exists').should.equals(true);
			whereClause.name.test('dog').should.equals(false);
		});

		it ('should look for occurrences of a term at the start of a string using endsWith', function () {
			var options = {
				filters : {
					mandatory : {
						endsWith : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.name);
			whereClause.name.test('cat').should.equals(true);
			whereClause.name.test('cool cat').should.equals(true);
			whereClause.name.test('this cat is sick').should.equals(false);
		});

		it ('should look for occurrences of a term at the start of a string using startsWith', function () {
			var options = {
				filters : {
					mandatory : {
						startsWith : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.name);
			whereClause.name.test('cat').should.equals(true);
			whereClause.name.test('cat exists').should.equals(true);
			whereClause.name.test('this cat is sick').should.equals(false);
		});

		it ('should look for occurrences of an exact match of the term when using exact', function () {
			var options = {
				filters : {
					mandatory : {
						exact : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.name);
			whereClause.name.test('cat').should.equals(true);
			whereClause.name.test('cat litter').should.equals(false);
			whereClause.name.test('the cat').should.equals(false);
		});

		it ('should look for occurrences of an exact match of the object when using exact', function () {
			var options = {
				filters : {
					mandatory : {
						exact : {
							isDead : false
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.isDead);
			whereClause.isDead.should.equals(false);
		});

		it ('should look for occurrences of an exact match of a number when using exact', function () {
			var options = {
				filters : {
					mandatory : {
						exact : {
							id : 12345
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			should.exist(whereClause.id);
			whereClause.id.should.equals(12345);
		});
	});

	describe('optional filters', function () {
		it ('should look for occurrences of a term within a string using contains', function () {
			var options = {
				filters : {
					optional : {
						contains : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][0].name.test('a cat exists').should.equals(true);
			orClauseItems[0][0].name.test('dog').should.equals(false);
		});

		it ('should look for occurrences of a term at the start of a string using endsWith', function () {
			var options = {
				filters : {
					optional : {
						endsWith : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][0].name.test('cool cat').should.equals(true);
			orClauseItems[0][0].name.test('this cat is sick').should.equals(false);
		});

		it ('should look for occurrences of a term at the start of a string using startsWith', function () {
			var options = {
				filters : {
					optional : {
						startsWith : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][0].name.test('cat exists').should.equals(true);
			orClauseItems[0][0].name.test('this cat is sick').should.equals(false);
		});

		it ('should look for occurrences of an exact match of the term when using exact', function () {
			var options = {
				filters : {
					optional : {
						exact : {
							name : 'cat'
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][0].name.test('cat litter').should.equals(false);
			orClauseItems[0][0].name.test('the cat').should.equals(false);
		});

        it ('should look for occurrences of an exact match of the object when using exact', function () {
            var options = {
                filters : {
                    optional : {
                        exact : {
                            isDead : true
                        }
                    }
                }
            };

            var query = Kitteh
                .find()
                .filter(options);

            should.exist(query);
            orClauseItems.should.have.length(1);
            orClauseItems[0][0].isDead.should.equals(true);
            //orClauseItems[0][0].name.test('cat litter').should.equals(false);
            //orClauseItems[0][0].name.test('the cat').should.equals(false);
        });

		it ('should look for multiple occurrences of a match when supplying an array', function () {
			var options = {
				filters : {
					optional : {
						exact : {
							name : ['cat', 'Kitteh']
						}
					}
				}
			};

			var query = Kitteh
				.find()
				.filter(options);

			should.exist(query);
			orClauseItems.should.have.length(1);
			orClauseItems[0][0].name.test('cat').should.equals(true);
			orClauseItems[0][1].name.test('Kitteh').should.equals(true);
		});
	});
});
<|endoftext|>


<commit_before>
var assert = require('assert');
var fs = require('fs');
var grunt = require('grunt');

suite('grunt-metascript', function() {
  suite('generating', function() {
    test('program mode', function() {
      assert.ok(fs.existsSync('out/somemeta-program.js'));
      assert.equal(fs.readFileSync('out/somemeta-program.js', 'utf8'), fs.readFileSync('test/fixtures/somemeta-program.js', 'utf8'));
    });

    test('transform mode', function() {
      assert.ok(fs.existsSync('out/somemeta-transform.js'));
      assert.equal(fs.readFileSync('out/somemeta-transform.js', 'utf8'), fs.readFileSync('test/fixtures/somemeta-transform.js', 'utf8'));
    });

    test('multiple files: exclude program', function() {
      assert.ok(!fs.existsSync('out/multi/somemeta-program.js'));
    });

    test('multiple files transformation', function() {
      grunt.file.recurse('out/multi/', function(abspath, rootdir, subdir, filename) {
        assert.equal(fs.readFileSync(abspath, 'utf8'), fs.readFileSync('test/fixtures/multi/' + (subdir?subdir+'/':'') + filename, 'utf8'));
      });
    });
  });
});
<commit_msg>Hopefully fixed test by trimming output<commit_after>/* global suite, test */
var assert = require('assert');
var fs = require('fs');
var grunt = require('grunt');

suite('grunt-metascript', function() {
  'use strict';

  suite('generating', function() {
    test('program mode', function() {
      assert.ok(fs.existsSync('out/somemeta-program.js'));
      assert.equal(fs.readFileSync('out/somemeta-program.js', 'utf8').trim(), fs.readFileSync('test/fixtures/somemeta-program.js', 'utf8').trim());
    });

    test('transform mode', function() {
      assert.ok(fs.existsSync('out/somemeta-transform.js'));
      assert.equal(fs.readFileSync('out/somemeta-transform.js', 'utf8').trim(), fs.readFileSync('test/fixtures/somemeta-transform.js', 'utf8').trim());
    });

    test('multiple files: exclude program', function() {
      assert.ok(!fs.existsSync('out/multi/somemeta-program.js'));
    });

    test('multiple files transformation', function() {
      grunt.file.recurse('out/multi/', function(abspath, rootdir, subdir, filename) {
        assert.ok(fs.existsSync(abspath));
        assert.equal(fs.readFileSync(abspath, 'utf8').trim(), fs.readFileSync('test/fixtures/multi/' + (subdir?subdir+'/':'') + filename, 'utf8').trim());
      });
    });
  });
});
<|endoftext|>


<commit_before>const { assert, expect } = require('chai');
const nxtpm = require('../index.js');
const config = require('../lib/util/config.js');
const nxt = require('../lib/util/nxt.js');
let cli;

describe('Validation', () => {

  it('Accepts valid manifests', done => {
    const data = require('./data/manifests_valid.js');
    for (manifest of data) {
      assert.ok(nxtpm.manifest.validate(manifest));
    }
    done();
  });

  it('Rejects invalid manifests', done => {
    const data = require('./data/manifests_invalid.js');
    for (manifest of data) {
      expect(() => nxtpm.manifest.validate(manifest)).to.throw(Error);
    }
    done();
  });

});

describe('Nxt', () => {
  it('does an API request', done => {
    nxt.request({ requestType: 'getAlias', aliasName: 'test' })
    .then(data => {
      assert.equal(data.data.aliasName, 'test');
      done();
    }, err => {
      console.log(err.stack || err);
    });
  });
});

describe('Config', () => {
  it('Can set custom config', done => {
    nxtpm.setConfig('nxt:numSources', 1);
    const numSources = config.get('nxt:numSources');
    assert.equal(numSources, 1);
    nxt.request({ requestType: 'getConstants' })
    .then(data => {
      assert.equal(data.frequency, 1);
      assert.equal(data.score, 1);
      done();
    }, err => {
      console.log(err.stack || err);
    });
  });
});
<commit_msg>More unit tests<commit_after>const { assert, expect } = require('chai');
const path = require('path');
const tmp = require('tmp');
const jetpack = require('fs-jetpack');
const nxtpm = require('../index.js');
const config = require('../lib/util/config.js');
const nxt = require('../lib/util/nxt.js');
let cli;

describe('Validation', () => {

  it('Accepts valid manifests', done => {
    const data = require('./data/manifests_valid.js');
    for (manifest of data) {
      assert.ok(nxtpm.manifest.validate(manifest));
    }
    done();
  });

  it('Rejects invalid manifests', done => {
    const data = require('./data/manifests_invalid.js');
    for (manifest of data) {
      expect(() => nxtpm.manifest.validate(manifest)).to.throw(Error);
    }
    done();
  });

});

describe('Nxt', () => {

  it('Does an API request', done => {
    nxt.request({ requestType: 'getAlias', aliasName: 'test' })
    .then(data => {
      assert.equal(data.data.aliasName, 'test');
      done();
    }, err => {
      console.log(err.stack || err);
    });
  });

});

describe('Config', () => {

  it('Can set custom config', done => {
    nxtpm.setConfig('nxt:numSources', 1);
    const numSources = config.get('nxt:numSources');
    assert.equal(numSources, 1);
    nxt.request({ requestType: 'getConstants' })
    .then(data => {
      assert.equal(data.frequency, 1);
      assert.equal(data.score, 1);
      done();
    }, err => {
      console.log(err.stack || err);
    });
  });

});

describe('Info', () => {

  it('Retrieve package info', done => {
    nxtpm.info('test6').then(data => {
      expect(data.manifest).not.empty;
      expect(data.transaction).not.empty;
      done();
    }, err => {
      console.log(err.stack || err);
    })
  });

});

describe('Install', () => {

  it('Installs package to current working dir', done => {
    nxtpm.install('test6').then(() => {
      assert.equal(jetpack.exists('test6'), 'dir');
      jetpack.remove('test6');
      done();
    }, err => {
      console.log(err.stack || err);
    })
  });

  it('Installs package to specified dir', done => {
    const dir = tmp.dirSync().name;
    nxtpm.install('test6', dir).then(() => {
      assert.equal(
        jetpack.exists(path.join(dir, 'test6')),
        'dir'
      );
      done();
    });
  });

  it('Refuses to install to non-empty directory', done => {
    const dir = tmp.dirSync().name;
    const file = path.join(dir, 'test6', 'file.txt');
    jetpack.file(file);
    expect(() => nxtpm.install('test6', dir)).to.throw(Error);
    done();
  });

});

describe('Archive', () => {

  it('Create tar.gz archive', done => {
    const file = tmp.fileSync().name;
    nxtpm.archive.create(
      path.join(__dirname, 'package'),
      file
    )
    .then(checksum => {
      assert.equal(checksum.length, 64);
      done();
    }, err => {
      console.log(err.stack || err);
    });
  });

});

describe('Publish', () => {

  it('Creates publish transactions', () => {
    const file = path.join(__dirname, 'package', 'nxtpm.json');
    const mft = jetpack.read(file, 'json');
    expect(() => nxtpm.publish(mft, 'test', true)).to.not.throw;
  });

});

describe('Extend', () => {

  it('Creates extend transaction', () => {
    expect(() => nxtpm.extend('test6', 'test', true)).to.not.throw;
  });

});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Alasdair Mercer, Skelp
 *
 * 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'

var EventEmitter = require('events').EventEmitter
var expect = require('chai').expect

var Oopsy = require('../lib/oopsy')

describe('Oopsy', function() {
  it('should be a constructor', function() {
    expect(Oopsy).to.be.a('function')
    expect(new Oopsy()).to.be.an('object')
  })

  describe('.extend', function() {
    var Base = Oopsy.extend(function(name) {
      this.name = name
    }, {
      greet: function(name) {
        return 'Hello ' + name + ', my name is ' + this.name
      }
    }, {
      foo: function() {
        return 'bar'
      }
    })

    it('should extend the prototype and static properties', function() {
      function ChildConstructor() {
        ChildConstructor.super_.apply(this, arguments)

        this.id = 123
      }

      var Child = Base.extend(ChildConstructor, {
        farewell: function(name) {
          return 'Goodbye ' + name
        }
      }, {
        fizz: function() {
          return 'buzz'
        }
      })
      var child = new Child('Foo')

      expect(Child).to.equal(ChildConstructor)
      expect(child.hasOwnProperty('name')).to.be.true
      expect(child.name).to.equal('Foo')
      expect(child.id).to.equal(123)
      expect(child.greet('Bar')).to.equal('Hello Bar, my name is Foo')
      expect(child.farewell('Bar')).to.equal('Goodbye Bar')
      expect(Child.foo()).to.equal('bar')
      expect(Child.fizz()).to.equal('buzz')
    })

    it('should return constructor with correct inheritance', function() {
      var SubBase = Base.extend(function() {
        SubBase.super_.apply(this, arguments)
      })
      var Child = SubBase.extend(function() {
        Child.super_.apply(this, arguments)
      })
      var child = new Child('Foo')

      expect(child).to.be.an.instanceof(Oopsy)
      expect(child).to.be.an.instanceof(Base)
      expect(child).to.be.an.instanceof(SubBase)
      expect(child).to.be.an.instanceof(Child)
    })

    it('should give constructor reference to super constructor', function() {
      var SubBase = Base.extend(function() {
        SubBase.super_.apply(this, arguments)
      })
      var Child = SubBase.extend(function() {
        Child.super_.apply(this, arguments)
      })

      expect(Child.super_).to.equal(SubBase)
      expect(SubBase.super_).to.equal(Base)
      expect(Base.super_).to.equal(Oopsy)
    })

    it('should allow semi-inheritance of existing classes', function() {
      var Child = Base.extend(function() {
        Child.super_.apply(this, arguments)

        EventEmitter.call(this)
      }, EventEmitter.prototype, EventEmitter)
      var child = new Child('Foo')

      expect(Child.super_).to.equal(Base)
      expect(child).to.be.an.instanceof(Oopsy)
      expect(child).to.be.an.instanceof(Base)
      expect(child).to.be.an.instanceof(Child)
      expect(child).not.to.be.an.instanceof(EventEmitter)
      expect(child.name).to.equal('Foo')
      expect(child.listenerCount()).to.equal(0)
    })

    context('when no constructor is passed', function() {
      it('should extend the prototype and static properties', function() {
        var Child = Base.extend({
          farewell: function(name) {
            return 'Goodbye ' + name
          }
        }, {
          fizz: function() {
            return 'buzz'
          }
        })
        var child = new Child('Foo')

        expect(child.name).to.equal('Foo')
        expect(child.greet('Bar')).to.equal('Hello Bar, my name is Foo')
        expect(child.farewell('Bar')).to.equal('Goodbye Bar')
        expect(Child.foo()).to.equal('bar')
        expect(Child.fizz()).to.equal('buzz')
      })

      it('should return a constructor with correct inheritance', function() {
        var SubBase = Base.extend()
        var Child = SubBase.extend()
        var child = new Child('Foo')

        expect(child).to.be.an.instanceof(Oopsy)
        expect(child).to.be.an.instanceof(Base)
        expect(child).to.be.an.instanceof(SubBase)
        expect(child).to.be.an.instanceof(Child)
      })

      it('should return a constructor with reference to super constructor', function() {
        var SubBase = Base.extend()
        var Child = SubBase.extend()

        expect(Child.super_).to.equal(SubBase)
        expect(SubBase.super_).to.equal(Base)
        expect(Base.super_).to.equal(Oopsy)
      })
    })
  })
})
<commit_msg>fixed test failing on Node.js <0.12<commit_after>/*
 * Copyright (C) 2016 Alasdair Mercer, Skelp
 *
 * 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'

var EventEmitter = require('events').EventEmitter
var expect = require('chai').expect

var Oopsy = require('../lib/oopsy')

describe('Oopsy', function() {
  it('should be a constructor', function() {
    expect(Oopsy).to.be.a('function')
    expect(new Oopsy()).to.be.an('object')
  })

  describe('.extend', function() {
    var Base = Oopsy.extend(function(name) {
      this.name = name
    }, {
      greet: function(name) {
        return 'Hello ' + name + ', my name is ' + this.name
      }
    }, {
      foo: function() {
        return 'bar'
      }
    })

    it('should extend the prototype and static properties', function() {
      function ChildConstructor() {
        ChildConstructor.super_.apply(this, arguments)

        this.id = 123
      }

      var Child = Base.extend(ChildConstructor, {
        farewell: function(name) {
          return 'Goodbye ' + name
        }
      }, {
        fizz: function() {
          return 'buzz'
        }
      })
      var child = new Child('Foo')

      expect(Child).to.equal(ChildConstructor)
      expect(child.hasOwnProperty('name')).to.be.true
      expect(child.name).to.equal('Foo')
      expect(child.id).to.equal(123)
      expect(child.greet('Bar')).to.equal('Hello Bar, my name is Foo')
      expect(child.farewell('Bar')).to.equal('Goodbye Bar')
      expect(Child.foo()).to.equal('bar')
      expect(Child.fizz()).to.equal('buzz')
    })

    it('should return constructor with correct inheritance', function() {
      var SubBase = Base.extend(function() {
        SubBase.super_.apply(this, arguments)
      })
      var Child = SubBase.extend(function() {
        Child.super_.apply(this, arguments)
      })
      var child = new Child('Foo')

      expect(child).to.be.an.instanceof(Oopsy)
      expect(child).to.be.an.instanceof(Base)
      expect(child).to.be.an.instanceof(SubBase)
      expect(child).to.be.an.instanceof(Child)
    })

    it('should give constructor reference to super constructor', function() {
      var SubBase = Base.extend(function() {
        SubBase.super_.apply(this, arguments)
      })
      var Child = SubBase.extend(function() {
        Child.super_.apply(this, arguments)
      })

      expect(Child.super_).to.equal(SubBase)
      expect(SubBase.super_).to.equal(Base)
      expect(Base.super_).to.equal(Oopsy)
    })

    it('should allow semi-inheritance of existing classes', function() {
      var Child = Base.extend(function() {
        Child.super_.apply(this, arguments)

        EventEmitter.call(this)
      }, EventEmitter.prototype, EventEmitter)
      var child = new Child('Foo')

      expect(Child.super_).to.equal(Base)
      expect(child).to.be.an.instanceof(Oopsy)
      expect(child).to.be.an.instanceof(Base)
      expect(child).to.be.an.instanceof(Child)
      expect(child).not.to.be.an.instanceof(EventEmitter)
      expect(child.name).to.equal('Foo')
      expect(child.listeners()).to.eql([])
    })

    context('when no constructor is passed', function() {
      it('should extend the prototype and static properties', function() {
        var Child = Base.extend({
          farewell: function(name) {
            return 'Goodbye ' + name
          }
        }, {
          fizz: function() {
            return 'buzz'
          }
        })
        var child = new Child('Foo')

        expect(child.name).to.equal('Foo')
        expect(child.greet('Bar')).to.equal('Hello Bar, my name is Foo')
        expect(child.farewell('Bar')).to.equal('Goodbye Bar')
        expect(Child.foo()).to.equal('bar')
        expect(Child.fizz()).to.equal('buzz')
      })

      it('should return a constructor with correct inheritance', function() {
        var SubBase = Base.extend()
        var Child = SubBase.extend()
        var child = new Child('Foo')

        expect(child).to.be.an.instanceof(Oopsy)
        expect(child).to.be.an.instanceof(Base)
        expect(child).to.be.an.instanceof(SubBase)
        expect(child).to.be.an.instanceof(Child)
      })

      it('should return a constructor with reference to super constructor', function() {
        var SubBase = Base.extend()
        var Child = SubBase.extend()

        expect(Child.super_).to.equal(SubBase)
        expect(SubBase.super_).to.equal(Base)
        expect(Base.super_).to.equal(Oopsy)
      })
    })
  })
})
<|endoftext|>


<commit_before>var pdiff = require('../lib/main');

var assert = require('assert');
var chai = require("chai");
chai.should();

describe("pdiff", function() {
  describe('#diff', function() {
    it("should diff on word boundaries.", function() {
      var result = pdiff.diff("var x = 10;", "var x = 20;");

      result.should.deep.equal([
        {
          value: "var x = "
        },
        {
          added: undefined,
          removed: true,
          value: "10"
        },
        {
          added: true,
          removed: undefined,
          value: "20"
        },
        {
          value: ";"
        }
      ])
    })
    it("should diff lines when a delta is large.", function() {
      var result = pdiff.diff(
        [
          "function fib(n)",
          "  if (n <= 1) return 1;",
          "  else return fib(n-1) + fib(n-2);",
          "}",
          "",
          "function initialize() {",
          "  alert('foo');",
          "}"
        ].join("\n"),
        [
          "function initialize() {",
          "  alert('foo');",
          "}"
        ].join("\n")
      );

      result.should.deep.equal([
        {
          added: undefined,
          removed: true,
          value: [
            "function fib(n)",
            "  if (n <= 1) return 1;",
            "  else return fib(n-1) + fib(n-2);",
            "}",
            "",
            ""
          ].join("\n")
        },
        {
          value: [
            "function initialize() {",
            "  alert('foo');",
            "}"
          ].join("\n")
        }
      ])
    })
  })
  describe("#addLineNumbers", () => {
    it("should return a diff data with line numbers when words are replaced.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "test: 10\n",
        "test: 20\n"
      ));
      diff.should.deep.equal([
        {
          lineNumberOfLhs: 0,
          lineNumberOfRhs: 0,
          values: [{
            value: "test: "
          },
          {
            removed: true,
            value: "10"
          },
          {
            added: true,
            value: "20"
          }]
        }
      ])
    })
    it("should return a diff data with line numbers when lines are inserted.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "test: 10\n",
        "test: 10\ntest: 20\n"
      ));
      diff.should.deep.equal([
        {
          lineNumberOfLhs: 0,
          lineNumberOfRhs: 0,
          values: [{
            value: "test: 10"
          }]
        },
        {
          lineNumberOfRhs: 1,
          values: [
            {
              added: true,
              value: "test: 20"
            }
          ]
        }
      ])
    })
    it("should return a diff data with line numbers when lines are removed.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "test: 10\ntest: 20\n",
        "test: 10\n"
      ));
      diff.should.deep.equal([
        {
          lineNumberOfLhs: 0,
          lineNumberOfRhs: 0,
          values: [{
            value: "test: 10"
          }]
        },
        {
          lineNumberOfLhs: 1,
          values: [{
            removed: true,
            value: "test: 20"
          }]
        }
      ])
    })
    it("should return a diff data with line numbers when lines are replaced.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "foo\n",
        "bar\ntest: 10\n"
      ));
      diff.should.deep.equal([
        {
          lineNumberOfLhs: 0,
          values: [{
            removed: true,
            value: "foo"
          }]
        },
        {
          lineNumberOfRhs: 0,
          values: [{
            added: true,
            value: "bar"
          }]
        },
        {
          lineNumberOfRhs: 1,
          values: [
            {
              added: true,
              value: "test: 10"
            }
          ]
        }
      ])
    })
    it("should deal with the buggy case(https://github.com/HiroakiMikami/pdiff/issues/12)", () => {
      pdiff.addLineNumbers(pdiff.diff(
        "{\nprivate: true\n}\n",
        "{\n}\n"
      )).should.deep.equal([
        {
          lineNumberOfLhs: 0,
          lineNumberOfRhs: 0,
          values: [{value: "{"}]
        },
        {
          lineNumberOfLhs: 1,
          values: [{
            removed: true,
            value: "private: true"
          }]
        },
        {
          lineNumberOfLhs: 2,
          lineNumberOfRhs: 1,
          values: [{value: "}"}]
        }
      ])
    })
  })
  describe("#extractDiff", () => {
    it("should return a grouped diff.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "foo\nbar\n",
        "test\nbar\ntest: 10\n"
      ));
      var extractedDiff = pdiff.extractDiff(diff, 0);
      extractedDiff.should.deep.equal([
        [
          {
            lineNumberOfLhs: 0,
            lineNumberOfRhs: 0,
            values: [
              {
                removed: true,
                value: "foo"
              },
              {
                added: true,
                value: "test"
              }
            ]
          }
        ],
        [
          {
            lineNumberOfRhs: 2,
            values: [{
              added: true,
              value: "test: 10"
            }]
          }
        ]
      ]);
    })
  })
})
<commit_msg>Reformat a code<commit_after>var pdiff = require('../lib/main');

var assert = require('assert');
var chai = require("chai");
chai.should();

describe("pdiff", () => {
  describe('#diff', () => {
    it("should diff on word boundaries.", () => {
      var result = pdiff.diff("var x = 10;", "var x = 20;");

      result.should.deep.equal([
        {
          value: "var x = "
        },
        {
          added: undefined,
          removed: true,
          value: "10"
        },
        {
          added: true,
          removed: undefined,
          value: "20"
        },
        {
          value: ";"
        }
      ])
    })
    it("should diff lines when a delta is large.", () => {
      var result = pdiff.diff(
        [
          "function fib(n)",
          "  if (n <= 1) return 1;",
          "  else return fib(n-1) + fib(n-2);",
          "}",
          "",
          "function initialize() {",
          "  alert('foo');",
          "}"
        ].join("\n"),
        [
          "function initialize() {",
          "  alert('foo');",
          "}"
        ].join("\n")
      );

      result.should.deep.equal([
        {
          added: undefined,
          removed: true,
          value: [
            "function fib(n)",
            "  if (n <= 1) return 1;",
            "  else return fib(n-1) + fib(n-2);",
            "}",
            "",
            ""
          ].join("\n")
        },
        {
          value: [
            "function initialize() {",
            "  alert('foo');",
            "}"
          ].join("\n")
        }
      ])
    })
  })
  describe("#addLineNumbers", () => {
    it("should return a diff data with line numbers when words are replaced.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "test: 10\n",
        "test: 20\n"
      ));
      diff.should.deep.equal([
        {
          lineNumberOfLhs: 0,
          lineNumberOfRhs: 0,
          values: [{
            value: "test: "
          },
          {
            removed: true,
            value: "10"
          },
          {
            added: true,
            value: "20"
          }]
        }
      ])
    })
    it("should return a diff data with line numbers when lines are inserted.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "test: 10\n",
        "test: 10\ntest: 20\n"
      ));
      diff.should.deep.equal([
        {
          lineNumberOfLhs: 0,
          lineNumberOfRhs: 0,
          values: [{
            value: "test: 10"
          }]
        },
        {
          lineNumberOfRhs: 1,
          values: [
            {
              added: true,
              value: "test: 20"
            }
          ]
        }
      ])
    })
    it("should return a diff data with line numbers when lines are removed.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "test: 10\ntest: 20\n",
        "test: 10\n"
      ));
      diff.should.deep.equal([
        {
          lineNumberOfLhs: 0,
          lineNumberOfRhs: 0,
          values: [{
            value: "test: 10"
          }]
        },
        {
          lineNumberOfLhs: 1,
          values: [{
            removed: true,
            value: "test: 20"
          }]
        }
      ])
    })
    it("should return a diff data with line numbers when lines are replaced.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "foo\n",
        "bar\ntest: 10\n"
      ));
      diff.should.deep.equal([
        {
          lineNumberOfLhs: 0,
          values: [{
            removed: true,
            value: "foo"
          }]
        },
        {
          lineNumberOfRhs: 0,
          values: [{
            added: true,
            value: "bar"
          }]
        },
        {
          lineNumberOfRhs: 1,
          values: [
            {
              added: true,
              value: "test: 10"
            }
          ]
        }
      ])
    })
    it("should deal with the buggy case(https://github.com/HiroakiMikami/pdiff/issues/12)", () => {
      pdiff.addLineNumbers(pdiff.diff(
        "{\nprivate: true\n}\n",
        "{\n}\n"
      )).should.deep.equal([
        {
          lineNumberOfLhs: 0,
          lineNumberOfRhs: 0,
          values: [{value: "{"}]
        },
        {
          lineNumberOfLhs: 1,
          values: [{
            removed: true,
            value: "private: true"
          }]
        },
        {
          lineNumberOfLhs: 2,
          lineNumberOfRhs: 1,
          values: [{value: "}"}]
        }
      ])
    })
  })
  describe("#extractDiff", () => {
    it("should return a grouped diff.", () => {
      var diff = pdiff.addLineNumbers(pdiff.diff(
        "foo\nbar\n",
        "test\nbar\ntest: 10\n"
      ));
      var extractedDiff = pdiff.extractDiff(diff, 0);
      extractedDiff.should.deep.equal([
        [
          {
            lineNumberOfLhs: 0,
            lineNumberOfRhs: 0,
            values: [
              {
                removed: true,
                value: "foo"
              },
              {
                added: true,
                value: "test"
              }
            ]
          }
        ],
        [
          {
            lineNumberOfRhs: 2,
            values: [{
              added: true,
              value: "test: 10"
            }]
          }
        ]
      ]);
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

const test = require('tape');
const moment = require('moment');

const server = require('../lib/index.js');
const redis = require('../lib/db/redis.js');
const client = require('../lib/db/client.js');

let hash, payload;

server.init(1, (err, server) => {

    client.select(2, function() {}); // select different one to other test files

    test('test can write list to db', (t) => {
        const array = ['1', '2', '3', '4', '5'];
        const listName = 'testList';
        client.RPUSH(listName, array);
        client.LRANGE(listName, 0, -1, (error, reply) => {
            t.ok(!error, 'assert error is empty');
            t.deepEqual(reply, array, 'assert arrays match!');
            t.end();
        });
        client.DEL(listName, (err, reply) => {
            console.log('cleaned DB', reply);
        });
    });

    test('getHashKeyValue gets a hash\'s key value', (t) => {
        hash = 'test1';

        client.hset(hash, 'type', 'client');
        redis.getHashKeyValue(hash, 'type', (type) => {
            t.equal(type, 'client', 'types match');
            t.end();
        });
    });

    test('addRemoveFromSets adds to a set and removes from another', (t) => {
        hash = 'test2';

        client.sadd('awaitingApproval', hash);
        redis.addRemoveFromSets('approvedUsers', 'awaitingApproval', hash, () => {
            client.sismember('approvedUsers', hash, (err, res) => {
                t.equal(res, 1, 'hash added to approvedUsers');
            });
            client.sismember('awaitingApproval', hash, (err, res) => {
                t.equal(res, 0, 'hash add to awaitingApproval');
                t.end();
            });
        });
    });

    test('isAMemberOfSet correctly checks for a set member', (t) => {
        hash = 'test4';

        client.sadd('approvedUsers', hash);
        redis.isAMemberOfSet(hash, 'approvedUsers', (res) => {
            t.equal(res, 1, 'correctly identifies hash!');
            t.end();
        });
    });

    test('isExistingUser identifies user in DB', (t) => {
        hash = 'test5';

        client.del(hash);
        client.hset(hash, 'id', hash, (err, res) => {
            if (res) {
                redis.isExistingUser(hash, (res) => {
                    t.equal(res, 1, 'identifies hash exists!');
                    t.end();
                });
            }
        });
    });

    test('addClientSignUpDetails adds payload to hash and adds to awaitingApproval', (t) => {
        hash = 'test6';
        payload = {
            firstName: 'Joe',
            surname: 'Bloggs'
        };
        redis.addClientSignUpDetails(payload, hash, () => {
            client.sismember('awaitingApproval', hash, (err, res) => {
                t.equal(res, 1, 'client is added to awaitingApproval');
                client.hgetall(hash, (err, reply) => {
                    payload.id = hash;
                    payload.type = 'client';
                    let expected = payload;
                    let actual = reply;
                    t.deepEqual(actual, expected, 'correctly adds client payload');
                    t.end();
                });
            });
        });
    });

    test('addAgencySignUpDetails saves correct payload', (t) => {
        hash = 'test7';
        payload = {
            firstName: 'Joe',
            surname: 'Bloggs'
        };
        redis.addAgencySignUpDetails(payload, hash, () => {
            client.hgetall(hash, (err, reply) => {
                payload.id = hash;
                payload.type = 'agency';
                let expected = payload;
                let actual = reply;
                t.deepEqual(actual, expected, 'correctly saves agency payload');
                t.end();
            });
        });
    });

    test('getSetMembersInfo does exactly what it says on the tin', (t) => {
        let hash2 = 'test9';
        let hashObj = {
            id: 'user123',
            type: 'client',
            email: 'google@gmail.com',
            company: 'facebook'
        };
        hash = 'test8';
        client.hmset(hash, hashObj);
        client.sadd('testSet', hash);
        client.hmset(hash2, hashObj);
        client.sadd('testSet', hash2);

        redis.getSetMembersInfo('testSet', (res) => {
            let actual = res;
            let expected = [{ company: 'facebook', email: 'google@gmail.com', id: 'user123', type: 'client' }, { company: 'facebook', email: 'google@gmail.com', id: 'user123', type: 'client' }];

            t.deepEqual(actual, expected, 'The correct data was returned!');
            redis.getSetMembersInfo('testSet2', (res) => {
                t.equal(res, false, 'empty set should return false');
                t.end();
            });
        });

        // test('addJob saves a job with the company name, adds to liveJobs and adds appropriate dates', (t) => {
        //   let id  = 'test11';
        //   let vid = 'testVid1';
        //   payload = {
        //     jobTitle: 'developer',
        //     salary: '£30,000',
        //     searchDate: 'Tue Aug 25 2009'
        //   };
        //   let expected = {
        //     clientEmail: 'zuckerberg@fb.com',
        //     clientId: 'test11',
        //     companyName: 'fac',
        //     dateSubmitted: moment().format('MMMM Do YYYY'),
        //     jobTitle: 'developer',
        //     salary: '£30,000',
        //     searchDate: 'August 25th 2009',
        //     vid: 'testVid1'
        //   };
        //   client.del(id + 'jobs');
        //   client.srem('liveJobs', vid);
        //   client.hset(id, 'companyName', 'fac');
        //   client.hset(id, 'email', 'zuckerberg@fb.com');
        //   redis.addJob(payload, id, vid, () => {
        //     client.hgetall(vid, (err, reply) => {
        //       t.deepEqual(reply, expected, 'correctly formats job object!');
        //     });
        //     client.sismember(id + 'jobs', vid, (err, reply) => {
        //       t.equal(reply, 1, 'correctly added to idjobs set!');
        //     });
        //     client.sismember('liveJobs', vid, (err, reply) => {
        //       t.equal(reply, 1, 'correctly save to liveJobs set');
        //       t.end();
        //     });
        //   });
        // });

        test('getSetMembers correctly retrieves set members', (t) => {
            hash = 'test12';
            let hash2 = 'test13',
                hash3 = 'test14',
                set = 'testSet4';

            client.sadd(set, hash, hash2, hash3);
            redis.getSetMembers(set, (res) => {
                t.deepEqual(res.length, 3, 'correct set has been returned!');
                t.end();
            });
        });

        test('getVacancydetails ', (t) => {
            let vid = 'testVid2';
            payload = {
                jobTitle: 'UX designer',
                salary: '£40,000'
            };
            client.hmset(vid, payload);
            redis.getVacancyDetails(vid, (res) => {
                t.deepEqual(res, payload, 'correct object is returned!');
                t.end();
            });
        });

        test('addIdToSet does what it says', (t) => {
            let set = 'testSet3';
            hash = 'test10';
            client.DEL(set);
            redis.addIdToSet(hash, set, (res) => {
                t.equal(res, 1, 'should callback 1');
                client.sismember(set, hash, (err, reply) => {
                    t.equal(reply, 1, 'hash is now in set!');
                    t.end();

                });
            });
        });
        test('addcvagainstvacancy, does what it says', (t) => {
                let vid = 'testvid';
                let cvid = 'testcvid';
                let payload = {
                    file_url: 'https://harnesscvbucket.s3.amazonaws.com/' + cvid
                };
                redis.addCVagainstVacancy(payload, vid, (res) => {
                    console.log('RES', res);
                    client.exists(cvid, (err, reply) => {
                        t.equal(reply, 1, 'cv exists in database');
                    });
                    client.sismember('testvidadminShortlist', 'testcvid', (err, reply) => {
                        t.equal(reply, 1, 'cv is in vacancy set');
                        t.end();

                    });
                });
        });

          const jobPayload = { jobTitle: 'Tester', jobDescription: 'testing everything', jobCategory: 'test', teamCulture: 'persistant', typesOfProjects: 'tests', teamSize: 5, skillOne: 'test', skillTwo: 'test again', skillThree: 'test more', personality: 'persistant', salary: 100000, searchProgress: 'slow', searchDeadline: '12\/12\/2016' };

            test('addjob adds vacancy to db , livejobs & user id set also adds companyName and email', (t) => {
                   let id = 'testid';
                   let vid = 'testvid';
                redis.addJob(jobPayload, id, vid, (res) => {
                    console.log('RES', res);
                    client.exists(vid, (err, reply) => {
                        t.equal(reply, 1, 'cv exists in database');
                    });
                    client.hget(vid, 'dateSubmitted', (err, reply) => {
                        t.equal(reply, moment().format('Do MMMM YYYY'), 'dateSubmitted key is in database');
                    });
                    client.hget(vid, 'searchDeadline', (err, reply) => {
                        t.equal(reply, '12th December 2016', 'searchDeadl key is in database');
                    });
                    client.sismember(id + 'jobs', vid, (err, reply) => {
                        t.equal(reply, 1, 'cv is in vacancy set');
                    });
                    client.sismember('liveJobs', vid, (err, reply) => {
                        t.equal(reply, 1, 'cv is in livejobs set');
                        t.end();
                    });
                });
            });
            test('removeVacancy removes from livejobs and idjobs', (t) => {
                let id = 'testid';
                let vid = 'testvid';
                redis.removeVacancy(vid, id, (res) => {
                    console.log('RES', res);
                    client.exists(vid, (err, reply) => {
                        t.equal(reply, 0, 'cv exists in database');
                    });
                    client.sismember(id + 'jobs', vid, (err, reply) => {
                        t.equal(reply, 0, 'cv is not in vacancy set');
                    });
                    client.sismember('liveJobs', vid, (err, reply) => {
                        t.equal(reply, 0, 'cv is not in livejobs set');
                        t.end();
                    });
                });

            });
            test('test hset', (t) => {
                let id = 'testhashid';
                let key = 'fieldname';
                let value ='value';
                redis.setHashKeyValue(id, key, value, (res) => {
                    console.log('RES', res);
                    client.exists(id, key,(err,reply) => {
                        t.equal(reply,1, 'hash key exists in db');
                        t.end();
                        //client.flushdb();
                        client.quit();
                    });

                });
           });

    });

    server.stop();
});

// last test call client.quit();
<commit_msg>resolving test<commit_after>'use strict';

const test = require('tape');
const moment = require('moment');

const server = require('../lib/index.js');
const redis = require('../lib/db/redis.js');
const client = require('../lib/db/client.js');

let hash, payload;

server.init(1, (err, server) => {

    client.select(2, function() {}); // select different one to other test files

    test('test can write list to db', (t) => {
        const array = ['1', '2', '3', '4', '5'];
        const listName = 'testList';
        client.RPUSH(listName, array);
        client.LRANGE(listName, 0, -1, (error, reply) => {
            t.ok(!error, 'assert error is empty');
            t.deepEqual(reply, array, 'assert arrays match!');
            t.end();
        });
        client.DEL(listName, (err, reply) => {
            console.log('cleaned DB', reply);
        });
    });

    test('getHashKeyValue gets a hash\'s key value', (t) => {
        hash = 'test1';

        client.hset(hash, 'type', 'client');
        redis.getHashKeyValue(hash, 'type', (type) => {
            t.equal(type, 'client', 'types match');
            t.end();
        });
    });

    test('addRemoveFromSets adds to a set and removes from another', (t) => {
        hash = 'test2';

        client.sadd('awaitingApproval', hash);
        redis.addRemoveFromSets('approvedUsers', 'awaitingApproval', hash, () => {
            client.sismember('approvedUsers', hash, (err, res) => {
                t.equal(res, 1, 'hash added to approvedUsers');
            });
            client.sismember('awaitingApproval', hash, (err, res) => {
                t.equal(res, 0, 'hash add to awaitingApproval');
                t.end();
            });
        });
    });

    test('isAMemberOfSet correctly checks for a set member', (t) => {
        hash = 'test4';

        client.sadd('approvedUsers', hash);
        redis.isAMemberOfSet(hash, 'approvedUsers', (res) => {
            t.equal(res, 1, 'correctly identifies hash!');
            t.end();
        });
    });

    test('isExistingUser identifies user in DB', (t) => {
        hash = 'test5';

        client.del(hash);
        client.hset(hash, 'id', hash, (err, res) => {
            if (res) {
                redis.isExistingUser(hash, (res) => {
                    t.equal(res, 1, 'identifies hash exists!');
                    t.end();
                });
            }
        });
    });

    test('addClientSignUpDetails adds payload to hash and adds to awaitingApproval', (t) => {
        hash = 'test6';
        payload = {
            firstName: 'Joe',
            surname: 'Bloggs'
        };
        redis.addClientSignUpDetails(payload, hash, () => {
            client.sismember('awaitingApproval', hash, (err, res) => {
                t.equal(res, 1, 'client is added to awaitingApproval');
                client.hgetall(hash, (err, reply) => {
                    payload.id = hash;
                    payload.type = 'client';
                    let expected = payload;
                    let actual = reply;
                    t.deepEqual(actual, expected, 'correctly adds client payload');
                    t.end();
                });
            });
        });
    });

    test('addAgencySignUpDetails saves correct payload', (t) => {
        hash = 'test7';
        payload = {
            firstName: 'Joe',
            surname: 'Bloggs'
        };
        redis.addAgencySignUpDetails(payload, hash, () => {
            client.hgetall(hash, (err, reply) => {
                payload.id = hash;
                payload.type = 'agency';
                let expected = payload;
                let actual = reply;
                t.deepEqual(actual, expected, 'correctly saves agency payload');
                t.end();
            });
        });
    });

    test('getSetMembersInfo does exactly what it says on the tin', (t) => {
        let hash2 = 'test9';
        let hashObj = {
            id: 'user123',
            type: 'client',
            email: 'google@gmail.com',
            company: 'facebook'
        };
        hash = 'test8';
        client.hmset(hash, hashObj);
        client.sadd('testSet', hash);
        client.hmset(hash2, hashObj);
        client.sadd('testSet', hash2);

        redis.getSetMembersInfo('testSet', (res) => {
            let actual = res;
            let expected = [{ company: 'facebook', email: 'google@gmail.com', id: 'user123', type: 'client' }, { company: 'facebook', email: 'google@gmail.com', id: 'user123', type: 'client' }];

            t.deepEqual(actual, expected, 'The correct data was returned!');
            redis.getSetMembersInfo('testSet2', (res) => {
                t.equal(res, false, 'empty set should return false');
                t.end();
            });
        });

        // test('addJob saves a job with the company name, adds to liveJobs and adds appropriate dates', (t) => {
        //   let id  = 'test11';
        //   let vid = 'testVid1';
        //   payload = {
        //     jobTitle: 'developer',
        //     salary: '£30,000',
        //     searchDate: 'Tue Aug 25 2009'
        //   };
        //   let expected = {
        //     clientEmail: 'zuckerberg@fb.com',
        //     clientId: 'test11',
        //     companyName: 'fac',
        //     dateSubmitted: moment().format('MMMM Do YYYY'),
        //     jobTitle: 'developer',
        //     salary: '£30,000',
        //     searchDate: 'August 25th 2009',
        //     vid: 'testVid1'
        //   };
        //   client.del(id + 'jobs');
        //   client.srem('liveJobs', vid);
        //   client.hset(id, 'companyName', 'fac');
        //   client.hset(id, 'email', 'zuckerberg@fb.com');
        //   redis.addJob(payload, id, vid, () => {
        //     client.hgetall(vid, (err, reply) => {
        //       t.deepEqual(reply, expected, 'correctly formats job object!');
        //     });
        //     client.sismember(id + 'jobs', vid, (err, reply) => {
        //       t.equal(reply, 1, 'correctly added to idjobs set!');
        //     });
        //     client.sismember('liveJobs', vid, (err, reply) => {
        //       t.equal(reply, 1, 'correctly save to liveJobs set');
        //       t.end();
        //     });
        //   });
        // });

        test('getSetMembers correctly retrieves set members', (t) => {
            hash = 'test12';
            let hash2 = 'test13',
                hash3 = 'test14',
                set = 'testSet4';

            client.sadd(set, hash, hash2, hash3);
            redis.getSetMembers(set, (res) => {
                t.deepEqual(res.length, 3, 'correct set has been returned!');
                t.end();
            });
        });

        test('getVacancydetails ', (t) => {
            let vid = 'testVid2';
            payload = {
                jobTitle: 'UX designer',
                salary: '£40,000'
            };
            client.hmset(vid, payload);
            redis.getVacancyDetails(vid, (res) => {
                t.deepEqual(res, payload, 'correct object is returned!');
                t.end();
            });
        });

        test('addIdToSet does what it says', (t) => {
            let set = 'testSet3';
            hash = 'test10';
            client.DEL(set);
            redis.addIdToSet(hash, set, (res) => {
                t.equal(res, 1, 'should callback 1');
                client.sismember(set, hash, (err, reply) => {
                    t.equal(reply, 1, 'hash is now in set!');
                    t.end();

                });
            });
        });
        test('addcvagainstvacancy, does what it says', (t) => {
                let vid = 'testvid';
                let cvid = 'testcvid';
                let payload = {
                    file_url: 'https://harnesscvbucket.s3.amazonaws.com/' + cvid
                };
                redis.addCVagainstVacancy(payload, vid, (res) => {
                    console.log('RES', res);
                    client.exists(cvid, (err, reply) => {
                        t.equal(reply, 1, 'cv exists in database');
                    });
                    client.sismember('testvidadminShortlist', 'testcvid', (err, reply) => {
                        t.equal(reply, 1, 'cv is in vacancy set');
                        t.end();

                    });
                });
        });

          const jobPayload = { jobTitle: 'Tester', jobDescription: 'testing everything', jobCategory: 'test', teamCulture: 'persistant', typesOfProjects: 'tests', teamSize: 5, skillOne: 'test', skillTwo: 'test again', skillThree: 'test more', personality: 'persistant', salary: 100000, searchProgress: 'slow', searchDeadline: '12\/12\/2016' };

            test('addjob adds vacancy to db , livejobs & user id set also adds companyName and email', (t) => {
                   let id = 'testid';
                   let vid = 'testvid';
                redis.addJob(jobPayload, id, vid, (res) => {
                    console.log('RES', res);
                    client.exists(vid, (err, reply) => {
                        t.equal(reply, 1, 'cv exists in database');
                    });
                    client.hget(vid, 'dateSubmitted', (err, reply) => {
                        t.equal(reply, moment().format('Do MMMM YYYY'), 'dateSubmitted key is in database');
                    });
                    client.hget(vid, 'searchDeadline', (err, reply) => {
                        t.equal(reply, '12th December 2016', 'searchDeadl key is in database');
                    });
                    client.sismember(id + 'jobs', vid, (err, reply) => {
                        t.equal(reply, 1, 'cv is in vacancy set');
                    });
                    client.sismember('liveJobs', vid, (err, reply) => {
                        t.equal(reply, 1, 'cv is in livejobs set');
                        t.end();
                    });
                });
            });
            test('removeVacancy removes from livejobs and idjobs', (t) => {
                let id = 'testid';
                let vid = 'testvid';
                redis.removeVacancy(vid, id, (res) => {
                    console.log('RES', res);
                    client.exists(vid, (err, reply) => {
                        t.equal(reply, 0, 'cv exists in database');
                    });
                    client.sismember(id + 'jobs', vid, (err, reply) => {
                        t.equal(reply, 0, 'cv is not in vacancy set');
                    });
                    client.sismember('liveJobs', vid, (err, reply) => {
                        t.equal(reply, 0, 'cv is not in livejobs set');
                        t.end();
                    });
                });

            });
           /* test('test hset', (t) => {
                let id = 'testhashid';
                let key = 'fieldname';
                let value ='value';
                redis.setHashKeyValue(id, key, value, (res) => {
                    console.log('RES', res);
                    client.exists(id, key,(err,reply) => {
                        t.equal(reply,1, 'hash key exists in db');
                        t.end();
                        //client.flushdb();
                        client.quit();
                    });

                });
           });
*/

    });

    server.stop();
});

// last test call client.quit();
<|endoftext|>


<commit_before>import chance from "chance";
import { expect } from "chai";
import Bitloader from "src/bit-loader";

describe("Fetch Test Suite", function() {
  var loader, fetchStub, resolveStub, transformStub, dependencyStub, precompileStub, resolveData, fetchData, transformData;

  beforeEach(function() {
    resolveData = {path: "this is the real path"};
    fetchData = {source: "source content"};
    transformData = {source: "transformed source"};

    resolveStub = sinon.stub().returns(resolveData);
    fetchStub = sinon.stub().returns(fetchData);
    transformStub = sinon.stub().returns(transformData);
    dependencyStub = sinon.stub();
    precompileStub = sinon.stub();

    loader = new Bitloader({
      resolve: resolveStub,
      fetch: fetchStub,
      transform: transformStub,
      dependency: dependencyStub,
      precompile: precompileStub
    });
  });

  describe("When fetching a module called `like`", function() {
    beforeEach(function() {
      return loader.controllers.fetcher.fetch("like");
    });

    it("then `resolve` is called with `like`", function() {
      sinon.assert.calledWith(resolveStub, sinon.match({name: "like"}));
    });

    it("then `fetch` is called with `like`", function() {
      sinon.assert.calledWith(fetchStub, sinon.match(resolveData));
    });

    it("then `transform` is called with source `source content`", function() {
      sinon.assert.calledWith(transformStub, sinon.match(fetchData));
    });

    it("then `dependency` is called with source `transformed content`", function() {
      sinon.assert.calledWith(dependencyStub, sinon.match(transformData));
    });

    it("then `precompile` is called with source `transformed content`", function() {
      sinon.assert.calledWith(precompileStub, sinon.match(transformData));
    });
  });

  describe("When fetching a module that is excluded", function() {
    var excludeName, result;

    beforeEach(function() {
      excludeName = chance().string();
      return loader
        .exclude(excludeName).controllers.fetcher
        .fetch(excludeName)
        .then(function(r) {
          result = r;
        });
    });

    it("then resolve provider is not called", function() {
      sinon.assert.notCalled(resolveStub);
    });

    it("then fetch provider is not called", function() {
      sinon.assert.notCalled(fetchStub);
    });

    it("then module meta path is `null`", function() {
      expect(result.path).to.equal(null);
    });

    it("then module meta name is properly set", function() {
      expect(result.name).to.equal(excludeName);
    });

    it("then module meta id is properly set", function() {
      expect(result.id).to.equal(excludeName);
    });

    it("then module meta source is properly set", function() {
      expect(result.source).to.equal("");
    });
  });
});
<commit_msg>Adding some unit/integration tests for the fetcher controller through the loader fetch interface<commit_after>import chance from "chance";
import { expect } from "chai";
import Bitloader from "src/bit-loader";
import Module from "src/module";

describe("Fetch Test Suite", function() {
  var loader, fetchStub, resolveStub, transformStub, dependencyStub, precompileStub;
  var nameLikeData, resolveLikeData, fetchLikeData, transformLikeData, dependencyLikeData;
  var nameDep1Data, resolveDep1Data, fetchDep1Data, transformDep1Data, dependencyDep1Data;
  var nameCommonData, resolveCommonData, fetchCommonData, transformCommonData, dependencyCommonData;

  beforeEach(function() {
    nameLikeData = {name: "like"};
    resolveLikeData = {path: "this is the real path"};
    fetchLikeData = {source: "source content"};
    transformLikeData = {source: "transformed source"};
    dependencyLikeData = {deps: ["dep1", "common-dep"]};

    nameDep1Data = {name: "dep1"};
    resolveDep1Data = {path: "real path to dep1"};
    fetchDep1Data = {source: "dep1 source"};
    transformDep1Data = {source: "changed dep1 source"};
    dependencyDep1Data = {deps: ["common-dep"]};

    nameCommonData = {name: "common-dep"};
    resolveCommonData = {path: "path to common-dep dependency"};
    fetchCommonData = {source: "source for common-dep"};
    transformCommonData = {source: "transformed source for common-data"};
    dependencyCommonData = {deps: []};

    resolveStub = sinon.stub();
    resolveStub
      .withArgs(sinon.match(nameLikeData))
      .returns(resolveLikeData);
    resolveStub
      .withArgs(sinon.match(nameDep1Data))
      .returns(resolveDep1Data);
    resolveStub
      .withArgs(sinon.match(nameCommonData))
      .returns(resolveCommonData);

    fetchStub = sinon.stub()
    fetchStub
      .withArgs(sinon.match(nameLikeData))
      .returns(fetchLikeData);
    fetchStub
      .withArgs(sinon.match(nameDep1Data))
      .returns(fetchDep1Data);
    fetchStub
      .withArgs(sinon.match(nameCommonData))
      .returns(fetchCommonData);

    transformStub = sinon.stub();
    transformStub
      .withArgs(sinon.match(nameLikeData))
      .returns(transformLikeData);
    transformStub
      .withArgs(sinon.match(nameDep1Data))
      .returns(transformDep1Data);
    transformStub
      .withArgs(sinon.match(nameCommonData))
      .returns(transformCommonData);

    dependencyStub = sinon.stub();
    dependencyStub
      .withArgs(sinon.match(nameLikeData))
      .returns(dependencyLikeData);
    dependencyStub
      .withArgs(sinon.match(nameDep1Data))
      .returns(dependencyDep1Data);
    dependencyStub
      .withArgs(sinon.match(nameCommonData))
      .returns(dependencyCommonData);

    precompileStub = sinon.stub();

    loader = new Bitloader({
      resolve: resolveStub,
      fetch: fetchStub,
      transform: transformStub,
      dependency: dependencyStub,
      precompile: precompileStub
    });
  });

  describe("When fetching a module called `like`", function() {
    var result;

    beforeEach(function() {
      return loader.controllers.fetcher.fetch("like").then(function(r) {
        result = r;
      });
    });

    it("then `resolve` is called with `like` name data", function() {
      sinon.assert.calledWith(resolveStub, sinon.match(nameLikeData));
    });

    it("then `resolve` is called with `dep1` name data", function() {
      sinon.assert.calledWith(resolveStub, sinon.match(nameDep1Data));
    });

    it("then `resolve` is called with `common-dep` name data", function() {
      sinon.assert.calledWith(resolveStub, sinon.match(nameCommonData));
    });

    it("then `fetch` is called with `like` resolve data", function() {
      sinon.assert.calledWith(fetchStub, sinon.match(resolveLikeData));
    });

    it("then `fetch` is called with `dep1` resolve data", function() {
      sinon.assert.calledWith(fetchStub, sinon.match(resolveDep1Data));
    });

    it("then `fetch` is called with `common-dep` resolve data", function() {
      sinon.assert.calledWith(fetchStub, sinon.match(resolveCommonData));
    });

    it("then `transform` is called with `like` fetch data", function() {
      sinon.assert.calledWith(transformStub, sinon.match(fetchLikeData));
    });

    it("then `transform` is called with `dep1` fetch data", function() {
      sinon.assert.calledWith(transformStub, sinon.match(fetchDep1Data));
    });

    it("then `transform` is called with `common-dep` fetch data", function() {
      sinon.assert.calledWith(transformStub, sinon.match(fetchCommonData));
    });

    it("then `dependency` is called with `like` tranfom data", function() {
      sinon.assert.calledWith(dependencyStub, sinon.match(transformLikeData));
    });

    it("then `dependency` is called with `dep1` tranfom data", function() {
      sinon.assert.calledWith(dependencyStub, sinon.match(transformDep1Data));
    });

    it("then `dependency` is called with `common-dep` tranfom data", function() {
      sinon.assert.calledWith(dependencyStub, sinon.match(transformCommonData));
    });

    it("then `precompile` is called with `like` transform data", function() {
      sinon.assert.calledWith(precompileStub, sinon.match(transformLikeData));
    });

    it("then `precompile` is called with `dep1` transform data", function() {
      sinon.assert.calledWith(precompileStub, sinon.match(transformDep1Data));
    });

    it("then `precompile` is called with `common-dep` transform data", function() {
      sinon.assert.calledWith(precompileStub, sinon.match(transformCommonData));
    });

    it("then the result will have all the aggregated data", function() {
      expect(result).to.eql(new Module({
        deps: [],
        directory: "",
        fileName: "this is the real path",
        id: "this is the real path",
        name: "like",
        path: "this is the real path",
        referrer: {
          id: undefined,
          name: undefined,
          path: undefined
        },
        state: "resolve",
        type: "UNKNOWN"
      }));
    });
  });

  describe("When fetching a module that is excluded", function() {
    var excludeName, result;

    beforeEach(function() {
      excludeName = chance().string();
      return loader
        .exclude(excludeName).controllers.fetcher
        .fetch(excludeName)
        .then(function(r) {
          result = r;
        });
    });

    it("then resolve provider is not called", function() {
      sinon.assert.notCalled(resolveStub);
    });

    it("then fetch provider is not called", function() {
      sinon.assert.notCalled(fetchStub);
    });

    it("then module meta path is `null`", function() {
      expect(result.path).to.equal(null);
    });

    it("then module meta name is properly set", function() {
      expect(result.name).to.equal(excludeName);
    });

    it("then module meta id is properly set", function() {
      expect(result.id).to.equal(excludeName);
    });

    it("then module meta source is properly set", function() {
      expect(result.source).to.equal("");
    });
  });
});
<|endoftext|>