<commit_before>'use strict';

const portfinder = require('portfinder');
const express = require('express');
const bodyParser = require('body-parser');
const _ = require('lodash');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const formidable = require('formidable');
const form = new formidable.IncomingForm();
const formParse = Promise.promisify(form.parse, {context: form, multiArgs: true});
//const log = require('hw-logger').log;

const apiServer = {
  baseUrl: null,
  init(appKey) {
    this.appKey = appKey || 'mysecretkey';
    this.app = express();
    this.app.use((req, res, next) => {
      if (req.headers['x-okapi-key'] !== this.appKey) {
        res.status(401);
        res.json({code: 'UNAUTHORIZED', message: 'BAD_APP_KEY'});
        return;
      }
      next();
    });
    this.app.get('/myapi/v1/myresource', (req, res) => {
      res.json({foo: 'bar'});
    });
    this.contacts = [];
    this.app.post('/myapi/v1/contacts', bodyParser.json(), (req, res) => {
      const data = Object.assign(_.pick(req.body, ['firstName', 'lastName']), {id: this.contacts.length + 1});
      this.contacts.push(data);
      res.status(201);
      res.json(data);
    });
    this.app.patch('/myapi/v1/contacts/:id', bodyParser.json(), (req, res) => {
      const data = this.contacts[parseInt(req.params.id) - 1];
      if (!data) {
        res.status(404);
        res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'});
        return;
      }
      this.contacts[req.params.id] = Object.assign(data, _.pick(req.body, ['firstName', 'lastName']));
      this.contacts.push(this.contacts[req.params.id]);
      res.status(200);
      res.json(data);
    });
    this.app.get('/myapi/v1/contacts/:id', (req, res) => {
      const data = this.contacts[parseInt(req.params.id) - 1];
      if (!data) {
        res.status(404);
        res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'});
        return;
      }
      res.json(data);
    });
    this.app.delete('/myapi/v1/contacts/:id', bodyParser.json(), (req, res) => {
      const index = parseInt(req.params.id) - 1;
      const data = this.contacts[index];
      if (!data) {
        res.status(404);
        res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'});
        return;
      }
      this.contacts.splice(index, 1);
      res.status(204);
      res.end();
    });
    this.app.post('/myapi/v1/upload', (req, res) => {
      /**
       * $ curl -i -X POST http://localhost:8000/myapi/v1/upload \
       *    -H "Content-Type: multipart/form-data" \
       *    -F "toto=@package.json"
       */
      formParse(req)
        .spread((fields, files) => files[_.first(Object.keys(files))])
        .then(file => fs.readFileAsync(file.path)
          .then(content => {
            res.status(201);
            res.type(file.type);
            res.end(content);
          })
          .finally(() => fs.unlinkAsync(file.path))
        );
    });
    this.app.use((req, res, next) => {
      res.status(404);
      res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'});
    });
    return this;
  },
  start() {
    return Promise
      .fromCallback(cb => {
        portfinder.getPort(cb);
      })
      .then(freePort => {
        this.port = freePort;
        this.baseUrl = `http://localhost:${apiServer.port}`;
      })
      .then(() => Promise
        .fromCallback(cb => {
          this.server = this.app.listen(this.port, cb);
        })
      );
  },
  stop() {
    if (this.server) {
      return Promise
        .fromCallback(cb => {
          this.server.close(cb);
        });
    }
  }
};

if (!module.parent) {
  apiServer.init()
    .start()
    .then(() => {
      console.log(`Test api server listening to ${apiServer.baseUrl} with app key "${apiServer.appKey}"`);
    });
}

module.exports = apiServer;
<commit_msg>test server<commit_after>'use strict';

const portfinder = require('portfinder');
const express = require('express');
const bodyParser = require('body-parser');
const _ = require('lodash');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const formidable = require('formidable');
const form = new formidable.IncomingForm();
const formParse = Promise.promisify(form.parse, {context: form, multiArgs: true});
//const log = require('hw-logger').log;

const apiServer = {
  baseUrl: null,
  init(appKey) {
    this.appKey = appKey || 'mysecretkey';
    this.app = express();
    this.app.use((req, res, next) => {
      if (req.headers['x-okapi-key'] !== this.appKey) {
        res.status(401);
        res.json({code: 'UNAUTHORIZED', message: 'BAD_APP_KEY'});
        return;
      }
      next();
    });
    this.app.get('/myapi/v1/myresource', (req, res) => {
      res.json({foo: req.query.foo || 'bar'});
    });
    this.contacts = [];
    this.app.post('/myapi/v1/contact-forms', bodyParser.urlencoded(), (req, res) => {
      const data = Object.assign(_.pick(req.body, ['firstName', 'lastName']), {id: this.contacts.length + 1});
      this.contacts.push(data);
      res.status(201);
      res.json(data);
    });
    this.app.post('/myapi/v1/contacts', bodyParser.json(), (req, res) => {
      const data = Object.assign(_.pick(req.body, ['firstName', 'lastName']), {id: this.contacts.length + 1});
      this.contacts.push(data);
      res.status(201);
      res.json(data);
    });
    this.app.patch('/myapi/v1/contacts/:id', bodyParser.json(), (req, res) => {
      const data = this.contacts[parseInt(req.params.id) - 1];
      if (!data) {
        res.status(404);
        res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'});
        return;
      }
      this.contacts[req.params.id] = Object.assign(data, _.pick(req.body, ['firstName', 'lastName']));
      this.contacts.push(this.contacts[req.params.id]);
      res.status(200);
      res.json(data);
    });
    this.app.get('/myapi/v1/contacts/:id', (req, res) => {
      const data = this.contacts[parseInt(req.params.id) - 1];
      if (!data) {
        res.status(404);
        res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'});
        return;
      }
      res.json(data);
    });
    this.app.delete('/myapi/v1/contacts/:id', bodyParser.json(), (req, res) => {
      const index = parseInt(req.params.id) - 1;
      const data = this.contacts[index];
      if (!data) {
        res.status(404);
        res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'});
        return;
      }
      this.contacts.splice(index, 1);
      res.status(204);
      res.end();
    });
    this.app.post('/myapi/v1/upload', (req, res) => {
      /**
       * $ curl -i -X POST http://localhost:8000/myapi/v1/upload \
       *    -H "Content-Type: multipart/form-data" \
       *    -F "toto=@package.json"
       */
      formParse(req)
        .spread((fields, files) => files[_.first(Object.keys(files))])
        .then(file => fs.readFileAsync(file.path)
          .then(content => {
            res.status(201);
            res.type(file.type);
            res.end(content);
          })
          .finally(() => fs.unlinkAsync(file.path))
        );
    });
    this.app.use((req, res, next) => {
      res.status(404);
      res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'});
    });
    return this;
  },
  start() {
    return Promise
      .fromCallback(cb => {
        portfinder.getPort(cb);
      })
      .then(freePort => {
        this.port = freePort;
        this.baseUrl = `http://localhost:${apiServer.port}`;
      })
      .then(() => Promise
        .fromCallback(cb => {
          this.server = this.app.listen(this.port, cb);
        })
      );
  },
  stop() {
    if (this.server) {
      return Promise
        .fromCallback(cb => {
          this.server.close(cb);
        });
    }
  }
};

if (!module.parent) {
  apiServer.init()
    .start()
    .then(() => {
      console.log(`Test api server listening to ${apiServer.baseUrl} with app key "${apiServer.appKey}"`);
    });
}

module.exports = apiServer;
<|endoftext|>


<commit_before>var gulp = require('gulp');
var stylus = require('gulp-stylus');
var plumber = require('gulp-plumber');
var jade = require('gulp-jade');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var browserSync = require('browser-sync').create();

//HTML
gulp.task('templates', function() {
  return gulp.src(['./src/jade/*.jade','!./src/jade/_*.jade'])
    .pipe(plumber())
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('./dist/'))
});

gulp.task('template-watch',['templates'], function(){
  browserSync.reload();
  return;
});

//STYLE-MINIFY
gulp.task('styleCompress', function () {
  return gulp.src(['./src/styl/*.styl','!./src/styl/_*.styl'])
    .pipe(plumber())
    .pipe(stylus({
      compress: true
    }))
    .pipe(gulp.dest('./dist/css/'))
    .pipe(browserSync.stream());
});

//SCRIPTS-MINIFY
gulp.task('scriptMinify', function () {
  return gulp.src('src/js/*.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(gulp.dest('./dist/js/'))
});

gulp.task('script-watch',['scriptMinify'], browserSync.reload);

//COMPRESS IMAGE
gulp.task('compressImage',function(){
  return gulp.src('./src/images/*')
    .pipe(plumber())
		.pipe(imagemin())
		.pipe(gulp.dest('./dist/images'))
});

//COPY ANIMATE.CSS
gulp.task('copyAnimateCSS', function() {
    gulp.src('./vendor/animate.css/*.min.css')
    .pipe(gulp.dest('./dist/vendor/css/'));
});

//COPY BOOTSTRAP
gulp.task('copyBootstrapCSS', function() {
    gulp.src('./vendor/bootstrap/dist/css/*.min.css')
    .pipe(gulp.dest('./dist/vendor/css/'));
});

gulp.task('copyBootstrapJS', function() {
    gulp.src('./vendor/bootstrap/dist/js/*.min.js')
    .pipe(gulp.dest('./dist/vendor/js/'));
});

gulp.task('copyBootstrapFont', function() {
    gulp.src('./vendor/bootstrap/dist/fonts/*.{eot,svg,ttf,woff,woff2}')
    .pipe(gulp.dest('./dist/vendor/fonts/'));
});

//COPY FONTAWESOME
gulp.task('copyFontawesomeCSS', function() {
    gulp.src('./vendor/font-awesome/css/*.min.css')
    .pipe(gulp.dest('./dist/vendor/css/'));
});

gulp.task('copyFontawesomeFont', function() {
    gulp.src('./vendor/font-awesome/fonts/*.{eot,svg,ttf,otf,woff,woff2}')
    .pipe(gulp.dest('./dist/vendor/fonts/'));
});

gulp.task('copyJqueryJS', function() {
    gulp.src('./vendor/jquery/dist/jquery.min.js')
    .pipe(gulp.dest('./dist/vendor/js/'));
});

gulp.task('copyLibs',['copyAnimateCSS','copyBootstrapCSS','copyBootstrapJS','copyBootstrapFont','copyFontawesomeCSS','copyFontawesomeFont','copyJqueryJS']);

gulp.task('browser-sync', function() {
    browserSync.init({
        server: {
            baseDir: "./dist/"
        }
    });
});

gulp.task('watch', function() {
  gulp.watch([ 'src/jade/**/*.jade', 'src/jade/*.jade' ], ['template-watch']);
  gulp.watch(['src/styl/*.styl', './src/styl/**/*.styl'], ['styleCompress']);
  gulp.watch('src/js/*.js', ['script-watch']);
  gulp.watch('src/images/**', ['compressImage']);
});

gulp.task('default',['copyLibs','templates','styleCompress','scriptMinify','compressImage','browser-sync','watch']);
<commit_msg>fix partial style not updated on save<commit_after>var gulp = require('gulp');
var stylus = require('gulp-stylus');
var plumber = require('gulp-plumber');
var jade = require('gulp-jade');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var browserSync = require('browser-sync').create();

//HTML
gulp.task('templates', function() {
  return gulp.src(['./src/jade/*.jade','!./src/jade/_*.jade'])
    .pipe(plumber())
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('./dist/'))
});

gulp.task('template-watch',['templates'], function(){
  browserSync.reload();
  return;
});

//STYLE-MINIFY
gulp.task('styleCompress', function () {
  return gulp.src(['./src/styl/*.styl','!./src/styl/_*.styl'])
    .pipe(plumber())
    .pipe(stylus({
      compress: true
    }))
    .pipe(gulp.dest('./dist/css/'))
    .pipe(browserSync.stream());
});

//SCRIPTS-MINIFY
gulp.task('scriptMinify', function () {
  return gulp.src('src/js/*.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(gulp.dest('./dist/js/'))
});

gulp.task('script-watch',['scriptMinify'], browserSync.reload);

//COMPRESS IMAGE
gulp.task('compressImage',function(){
  return gulp.src('./src/images/*')
    .pipe(plumber())
		.pipe(imagemin())
		.pipe(gulp.dest('./dist/images'))
});

//COPY ANIMATE.CSS
gulp.task('copyAnimateCSS', function() {
    gulp.src('./vendor/animate.css/*.min.css')
    .pipe(gulp.dest('./dist/vendor/css/'));
});

//COPY BOOTSTRAP
gulp.task('copyBootstrapCSS', function() {
    gulp.src('./vendor/bootstrap/dist/css/*.min.css')
    .pipe(gulp.dest('./dist/vendor/css/'));
});

gulp.task('copyBootstrapJS', function() {
    gulp.src('./vendor/bootstrap/dist/js/*.min.js')
    .pipe(gulp.dest('./dist/vendor/js/'));
});

gulp.task('copyBootstrapFont', function() {
    gulp.src('./vendor/bootstrap/dist/fonts/*.{eot,svg,ttf,woff,woff2}')
    .pipe(gulp.dest('./dist/vendor/fonts/'));
});

//COPY FONTAWESOME
gulp.task('copyFontawesomeCSS', function() {
    gulp.src('./vendor/font-awesome/css/*.min.css')
    .pipe(gulp.dest('./dist/vendor/css/'));
});

gulp.task('copyFontawesomeFont', function() {
    gulp.src('./vendor/font-awesome/fonts/*.{eot,svg,ttf,otf,woff,woff2}')
    .pipe(gulp.dest('./dist/vendor/fonts/'));
});

gulp.task('copyJqueryJS', function() {
    gulp.src('./vendor/jquery/dist/jquery.min.js')
    .pipe(gulp.dest('./dist/vendor/js/'));
});

gulp.task('copyLibs',['copyAnimateCSS','copyBootstrapCSS','copyBootstrapJS','copyBootstrapFont','copyFontawesomeCSS','copyFontawesomeFont','copyJqueryJS']);

gulp.task('browser-sync', function() {
    browserSync.init({
        server: {
            baseDir: "./dist/"
        }
    });
});

gulp.task('watch', function() {
  gulp.watch([ 'src/jade/**/*.jade', 'src/jade/*.jade' ], ['template-watch']);
  gulp.watch(['src/styl/*.styl', 'src/styl/**/*.styl'], ['styleCompress']);
  gulp.watch('src/js/*.js', ['script-watch']);
  gulp.watch('src/images/**', ['compressImage']);
});

gulp.task('default',['copyLibs','templates','styleCompress','scriptMinify','compressImage','browser-sync','watch']);
<|endoftext|>


<commit_before>var index = require('../index');
var sinon = require('sinon');

var options = {};
var req = {};
var testFunction1 = function () { return true; };
var testFunction2 = function () { return false; };
var myIgnoredTextKey = 'myIgnoredTestKey';
var myTestRequest = { route: { name: myIgnoredTextKey }};

describe('Validation', function () {
    describe('getValidatorChain', function () {
        before(function () {
            index.validation._validators.myTestValidator = testFunction1;
            index.validation._validators.myTestValidator2 = testFunction2;
            index.validation._ignoredValidationKeys.push(myIgnoredTextKey);
        });

        after(function () {
            delete index.validation._validators.myTestValidator;
            delete index.validation._validators.myTestValidator2;
            index.validation._ignoredValidationKeys.splice(index.validation._ignoredValidationKeys.indexOf(myIgnoredTextKey), 1);
            index.validation._ignoredValidationKeys.indexOf(myIgnoredTextKey).should.equal(-1);
        });

        it('ignore validator key', function () {
            index.validation._ignoredValidationKeys.indexOf(myIgnoredTextKey).should.not.equal(-1);
            var validatorChainAsObject = index.validation.getValidatorChain(null, { myIgnoredTextKey: testFunction1 }, null, null, null);
            validatorChainAsObject.length.should.equal(0);
        });

        it('single validator', function (done) {
            var validatorChainAsObject = index.validation.getValidatorChain(null, { myTestValidator: true, msg: testFunction1 }, null, null, null);
            validatorChainAsObject.length.should.equal(1);
            validatorChainAsObject[0].fn.should.equal(testFunction1);
            validatorChainAsObject[0].msg.should.equal(testFunction1);

            var validatorChainAsArray = index.validation.getValidatorChain(null, [
                { myTestValidator: true, msg: testFunction1 }
            ], null, null, null);
            validatorChainAsArray.length.should.equal(1);
            validatorChainAsArray[0].fn.should.equal(testFunction1);
            validatorChainAsArray[0].msg.should.equal(testFunction1);

            done();
        });

        it('multiple validators', function (done) {
            var validatorChainAsObject = index.validation.getValidatorChain(null, { myTestValidator: true, myTestValidator2: true, msg: myIgnoredTextKey }, null, null, null);
            validatorChainAsObject.length.should.equal(2);

            validatorChainAsObject[0].fn.should.equal(testFunction1);
            validatorChainAsObject[0].msg.should.equal(myIgnoredTextKey);
            validatorChainAsObject[1].fn.should.equal(testFunction2);
            validatorChainAsObject[1].msg.should.equal(myIgnoredTextKey);

            var validatorChainAsArray = index.validation.getValidatorChain(null, [
                { myTestValidator: true, msg: testFunction1 },
                { myTestValidator2: true, msg: false }
            ], null, null, null);
            validatorChainAsArray.length.should.equal(2);
            validatorChainAsArray[0].fn.should.equal(testFunction1);
            validatorChainAsArray[0].msg.should.equal(testFunction1);
            validatorChainAsArray[1].fn.should.equal(testFunction2);
            validatorChainAsArray[1].msg.should.equal(false);

            var validatorChainAsArray2 = index.validation.getValidatorChain(null, [
                { myTestValidator: true, msg: testFunction1 },
                { myTestValidator2: true, myTestValidator: true, msg: false }
            ], null, null, null);
            validatorChainAsArray2.length.should.equal(3);
            validatorChainAsArray2[0].fn.should.equal(testFunction1);
            validatorChainAsArray2[0].msg.should.equal(testFunction1);
            validatorChainAsArray2[1].fn.should.equal(testFunction2);
            validatorChainAsArray2[1].msg.should.equal(false);
            validatorChainAsArray2[2].fn.should.equal(testFunction1);
            validatorChainAsArray2[2].msg.should.equal(false);

            done();
        });

        it('validationChainStore by routeName', function (done) {
            var generationSpy = sinon.spy(index.validation, '_generateValidationChain');

            var validatorChainAsObject = index.validation.getValidatorChain(null, { myTestValidator: true, msg: testFunction1 }, null, null, myTestRequest, null);
            validatorChainAsObject.length.should.equal(1);
            validatorChainAsObject[0].fn.should.equal(testFunction1);
            validatorChainAsObject[0].msg.should.equal(testFunction1);

            var validatorChainAsObject2 = index.validation.getValidatorChain(null, { myTestValidator: true, msg: testFunction1 }, null, null, myTestRequest, null);
            validatorChainAsObject2.length.should.equal(1);
            validatorChainAsObject2[0].fn.should.equal(testFunction1);
            validatorChainAsObject2[0].msg.should.equal(testFunction1);

            generationSpy.calledTwice.should.not.be.ok;
            generationSpy.calledOnce.should.be.ok;
            generationSpy.restore();

            done();
        });
    });

    describe('validate', function () {
        it('min', function (done) {
            var validationModel = { name: { isRequired: true, min: 10 } },
                validationReq = { params: { name: 9 } },
                validationOptions = {};

            var errors = index.validation.process(validationModel, validationReq, validationOptions);
            errors.length.should.equal(1);

            validationReq = { params: { name: 10 } };

            var errors2 = index.validation.process(validationModel, validationReq, validationOptions);
            errors2.length.should.equal(0);

            done();
        });

        it('isIPv4', function (done) {
            var validationModel = { name: { isRequired: true, isIPv4: false } },
                validationReq = { params: { name: 9 } },
                validationOptions = {};

            var errors0 = index.validation.process(validationModel, validationReq, validationOptions);
            errors0.length.should.equal(0);

            validationModel.name.isIPv4 = true;
            var errors1 = index.validation.process(validationModel, validationReq, validationOptions);
            errors1.length.should.equal(1);

            validationReq = { params: { name: '127.0.0.1' } };
            var errors2 = index.validation.process(validationModel, validationReq, validationOptions);
            errors2.length.should.equal(0);

            done();
        });

        it('example #1', function (done) {
            var validationModel = {
                status: { isRequired: true, isIn: ['foo', 'bar'], scope: 'query' },
                email: { isRequired: false, isEmail: true, scope: 'query' },
                age: { isRequired: true, isInt: true, scope: 'query' }
            };

            var validationReq = { params: {
                'name': 'Timo',
                'status': 'bar',
                'email': 'my.email@gmail.com',
                'age': '10',
                'street': 'abcdefghij'
            } };

            var validationOptions = {};

            var errors0 = index.validation.process(validationModel, validationReq, validationOptions);
            errors0.length.should.equal(0);

            delete validationReq.params.email;
            var errors1 = index.validation.process(validationModel, validationReq, validationOptions);
            errors1.length.should.equal(0);

            delete validationReq.params.status;
            var errors2 = index.validation.process(validationModel, validationReq, validationOptions);
            errors2.length.should.equal(1);

            done();
        });

        it('errorsAsArray / errorsAsObject', function (done) {
            var validationReq = { params: { } };
            var validationModel = {
                status: { isRequired: true, isIn: ['foo', 'bar'], scope: 'query' }
            };

            var errors0 = index.validation.process(validationModel, validationReq, { errorsAsArray: false });
            errors0.should.be.a('object');
            errors0.status.should.exist;
            errors0.status.field.should.equal('status');
            errors0.status.code.should.equal('MISSING');

            var errors1 = index.validation.process(validationModel, validationReq, { errorsAsArray: true });
            errors1.should.be.an.instanceof(Array);
            errors1.length.should.equal(1);
            errors1[0].field.should.equal('status');
            errors1[0].code.should.equal('MISSING');

            done();
        });

        it('function as validation parameter', function (done) {
            var isRequiredTrue, validationReq = { params: { } };
            var options = { errorsAsArray: true };
            var validationModelTrue = { status: { } };

            isRequiredTrue = function () {
                this.req.should.exist;
                this.req.should.equal(validationReq);

                this.validationModel.should.exist;
                this.validationModel.should.equal(validationModelTrue);

                this.validationRules.should.exist;
                this.validationRules.should.equal(validationModelTrue.status);

                this.options.should.exist;
                this.options.should.equal(options);

                return true;
            };

            validationModelTrue.status.isRequired = isRequiredTrue;
            validationModelTrue.status.isIn = ['foo', 'bar'];
            validationModelTrue.status.scope = 'query';

            var errors1 = index.validation.process(validationModelTrue, validationReq, options);
            errors1.should.be.an.instanceof(Array);
            errors1.length.should.equal(1);
            errors1[0].field.should.equal('status');
            errors1[0].code.should.equal('MISSING');

            done();
        });

        it('validation order', function (done) {
            var validationReq = { params: { } };
            var validationModel = {
                status: { isIn: ['foo', 'bar'], scope: 'query' }
            };

            validationModel.status.isRequired = false;
            console.log(validationModel);

            var errors0 = index.validation.process(validationModel, validationReq, { errorsAsArray: true });
            errors0.should.be.an.instanceof(Array);
            errors0.length.should.equal(0);

            done();
        });
    });
});
<commit_msg>Remove log<commit_after>var index = require('../index');
var sinon = require('sinon');

var options = {};
var req = {};
var testFunction1 = function () { return true; };
var testFunction2 = function () { return false; };
var myIgnoredTextKey = 'myIgnoredTestKey';
var myTestRequest = { route: { name: myIgnoredTextKey }};

describe('Validation', function () {
    describe('getValidatorChain', function () {
        before(function () {
            index.validation._validators.myTestValidator = testFunction1;
            index.validation._validators.myTestValidator2 = testFunction2;
            index.validation._ignoredValidationKeys.push(myIgnoredTextKey);
        });

        after(function () {
            delete index.validation._validators.myTestValidator;
            delete index.validation._validators.myTestValidator2;
            index.validation._ignoredValidationKeys.splice(index.validation._ignoredValidationKeys.indexOf(myIgnoredTextKey), 1);
            index.validation._ignoredValidationKeys.indexOf(myIgnoredTextKey).should.equal(-1);
        });

        it('ignore validator key', function () {
            index.validation._ignoredValidationKeys.indexOf(myIgnoredTextKey).should.not.equal(-1);
            var validatorChainAsObject = index.validation.getValidatorChain(null, { myIgnoredTextKey: testFunction1 }, null, null, null);
            validatorChainAsObject.length.should.equal(0);
        });

        it('single validator', function (done) {
            var validatorChainAsObject = index.validation.getValidatorChain(null, { myTestValidator: true, msg: testFunction1 }, null, null, null);
            validatorChainAsObject.length.should.equal(1);
            validatorChainAsObject[0].fn.should.equal(testFunction1);
            validatorChainAsObject[0].msg.should.equal(testFunction1);

            var validatorChainAsArray = index.validation.getValidatorChain(null, [
                { myTestValidator: true, msg: testFunction1 }
            ], null, null, null);
            validatorChainAsArray.length.should.equal(1);
            validatorChainAsArray[0].fn.should.equal(testFunction1);
            validatorChainAsArray[0].msg.should.equal(testFunction1);

            done();
        });

        it('multiple validators', function (done) {
            var validatorChainAsObject = index.validation.getValidatorChain(null, { myTestValidator: true, myTestValidator2: true, msg: myIgnoredTextKey }, null, null, null);
            validatorChainAsObject.length.should.equal(2);

            validatorChainAsObject[0].fn.should.equal(testFunction1);
            validatorChainAsObject[0].msg.should.equal(myIgnoredTextKey);
            validatorChainAsObject[1].fn.should.equal(testFunction2);
            validatorChainAsObject[1].msg.should.equal(myIgnoredTextKey);

            var validatorChainAsArray = index.validation.getValidatorChain(null, [
                { myTestValidator: true, msg: testFunction1 },
                { myTestValidator2: true, msg: false }
            ], null, null, null);
            validatorChainAsArray.length.should.equal(2);
            validatorChainAsArray[0].fn.should.equal(testFunction1);
            validatorChainAsArray[0].msg.should.equal(testFunction1);
            validatorChainAsArray[1].fn.should.equal(testFunction2);
            validatorChainAsArray[1].msg.should.equal(false);

            var validatorChainAsArray2 = index.validation.getValidatorChain(null, [
                { myTestValidator: true, msg: testFunction1 },
                { myTestValidator2: true, myTestValidator: true, msg: false }
            ], null, null, null);
            validatorChainAsArray2.length.should.equal(3);
            validatorChainAsArray2[0].fn.should.equal(testFunction1);
            validatorChainAsArray2[0].msg.should.equal(testFunction1);
            validatorChainAsArray2[1].fn.should.equal(testFunction2);
            validatorChainAsArray2[1].msg.should.equal(false);
            validatorChainAsArray2[2].fn.should.equal(testFunction1);
            validatorChainAsArray2[2].msg.should.equal(false);

            done();
        });

        it('validationChainStore by routeName', function (done) {
            var generationSpy = sinon.spy(index.validation, '_generateValidationChain');

            var validatorChainAsObject = index.validation.getValidatorChain(null, { myTestValidator: true, msg: testFunction1 }, null, null, myTestRequest, null);
            validatorChainAsObject.length.should.equal(1);
            validatorChainAsObject[0].fn.should.equal(testFunction1);
            validatorChainAsObject[0].msg.should.equal(testFunction1);

            var validatorChainAsObject2 = index.validation.getValidatorChain(null, { myTestValidator: true, msg: testFunction1 }, null, null, myTestRequest, null);
            validatorChainAsObject2.length.should.equal(1);
            validatorChainAsObject2[0].fn.should.equal(testFunction1);
            validatorChainAsObject2[0].msg.should.equal(testFunction1);

            generationSpy.calledTwice.should.not.be.ok;
            generationSpy.calledOnce.should.be.ok;
            generationSpy.restore();

            done();
        });
    });

    describe('validate', function () {
        it('min', function (done) {
            var validationModel = { name: { isRequired: true, min: 10 } },
                validationReq = { params: { name: 9 } },
                validationOptions = {};

            var errors = index.validation.process(validationModel, validationReq, validationOptions);
            errors.length.should.equal(1);

            validationReq = { params: { name: 10 } };

            var errors2 = index.validation.process(validationModel, validationReq, validationOptions);
            errors2.length.should.equal(0);

            done();
        });

        it('isIPv4', function (done) {
            var validationModel = { name: { isRequired: true, isIPv4: false } },
                validationReq = { params: { name: 9 } },
                validationOptions = {};

            var errors0 = index.validation.process(validationModel, validationReq, validationOptions);
            errors0.length.should.equal(0);

            validationModel.name.isIPv4 = true;
            var errors1 = index.validation.process(validationModel, validationReq, validationOptions);
            errors1.length.should.equal(1);

            validationReq = { params: { name: '127.0.0.1' } };
            var errors2 = index.validation.process(validationModel, validationReq, validationOptions);
            errors2.length.should.equal(0);

            done();
        });

        it('example #1', function (done) {
            var validationModel = {
                status: { isRequired: true, isIn: ['foo', 'bar'], scope: 'query' },
                email: { isRequired: false, isEmail: true, scope: 'query' },
                age: { isRequired: true, isInt: true, scope: 'query' }
            };

            var validationReq = { params: {
                'name': 'Timo',
                'status': 'bar',
                'email': 'my.email@gmail.com',
                'age': '10',
                'street': 'abcdefghij'
            } };

            var validationOptions = {};

            var errors0 = index.validation.process(validationModel, validationReq, validationOptions);
            errors0.length.should.equal(0);

            delete validationReq.params.email;
            var errors1 = index.validation.process(validationModel, validationReq, validationOptions);
            errors1.length.should.equal(0);

            delete validationReq.params.status;
            var errors2 = index.validation.process(validationModel, validationReq, validationOptions);
            errors2.length.should.equal(1);

            done();
        });

        it('errorsAsArray / errorsAsObject', function (done) {
            var validationReq = { params: { } };
            var validationModel = {
                status: { isRequired: true, isIn: ['foo', 'bar'], scope: 'query' }
            };

            var errors0 = index.validation.process(validationModel, validationReq, { errorsAsArray: false });
            errors0.should.be.a('object');
            errors0.status.should.exist;
            errors0.status.field.should.equal('status');
            errors0.status.code.should.equal('MISSING');

            var errors1 = index.validation.process(validationModel, validationReq, { errorsAsArray: true });
            errors1.should.be.an.instanceof(Array);
            errors1.length.should.equal(1);
            errors1[0].field.should.equal('status');
            errors1[0].code.should.equal('MISSING');

            done();
        });

        it('function as validation parameter', function (done) {
            var isRequiredTrue, validationReq = { params: { } };
            var options = { errorsAsArray: true };
            var validationModelTrue = { status: { } };

            isRequiredTrue = function () {
                this.req.should.exist;
                this.req.should.equal(validationReq);

                this.validationModel.should.exist;
                this.validationModel.should.equal(validationModelTrue);

                this.validationRules.should.exist;
                this.validationRules.should.equal(validationModelTrue.status);

                this.options.should.exist;
                this.options.should.equal(options);

                return true;
            };

            validationModelTrue.status.isRequired = isRequiredTrue;
            validationModelTrue.status.isIn = ['foo', 'bar'];
            validationModelTrue.status.scope = 'query';

            var errors1 = index.validation.process(validationModelTrue, validationReq, options);
            errors1.should.be.an.instanceof(Array);
            errors1.length.should.equal(1);
            errors1[0].field.should.equal('status');
            errors1[0].code.should.equal('MISSING');

            done();
        });

        it('validation order', function (done) {
            var validationReq = { params: { } };
            var validationModel = {
                status: { isIn: ['foo', 'bar'], scope: 'query' }
            };

            validationModel.status.isRequired = false;
            var errors0 = index.validation.process(validationModel, validationReq, { errorsAsArray: true });
            errors0.should.be.an.instanceof(Array);
            errors0.length.should.equal(0);

            done();
        });
    });
});
<|endoftext|>


<commit_before>/*
    Licenced Under MIT
    @file gulpfile.js
    @desc Buildfile for angular-multiselect
*/

var gulp = require('gulp'),
    clean = require('gulp-clean'),
    watch = require('gulp-watch'),
    sequence = require('run-sequence'),
    minify = require('gulp-ngmin');
    order = require('gulp-order'),
    jshint = require('gulp-jshint'),
    lintspaces = require("gulp-lintspaces"),
    jshintsummary = require('jshint-summary'),
    lintspacesConfig = {
        indentation: 'spaces',
        spaces: 4,
        trailingspaces: true,
        ignores: [
            'js-comments'
        ]
    };

/*
 Gulp monitors the src tree and rebuilds it detects a modification. Used of dev purpose
*/
gulp.task('watch', function() {
    watch("src/**/*.*", function() {
        gulp.start("build-clean");
    });
});

gulp.task('default', ['build-clean'], function() {
});

/*
 Check for lintspaces errors in source code
*/
gulp.task('whitespace', function() {
    return gulp.src([
            'src/*.js',
            'src/*.html',
            'src/*.css'])
        .pipe(lintspaces(lintspacesConfig))
        .pipe(lintspaces.reporter());
});

/* For Future Use -- Currently not used */
gulp.task('scripts', function() {
    return gulp.src('src/*.js')
        .pipe(order([
            "app.js",
            "multiselect.js",
            "multiselect-tpls.js"]))
        .pipe(jshint.reporter('jshint-summary', {
            verbose: true,
            reasonCol: 'cyan,bold',
            codeCol: 'green'
        }))
        .pipe(gulp.dest('dist'));
});

/* For future use to compress */
gulp.task('compress', function() {
    return gulp.src('src/*.js')
        .pipe(minify({dynamic: true}))
        .pipe(gulp.dest('dist'));
});

gulp.task('js', function () {
    return gulp.src('src/*.js')
        .pipe(gulp.dest('dist'));
});

gulp.task('css', function () {
    return gulp.src('src/*.css')
        .pipe(gulp.dest('dist'));
});

gulp.task('html', function () {
    return gulp.src('src/*.html')
        .pipe(gulp.dest('dist'));
});

gulp.task('clean', function() {
    return gulp.src(['dist'], {read: false})
        .pipe(clean());
});

/*
 Need to finish clean before building all the other stuff, and all other stuff
 needs to complete before injecting build artifacts into index.html.
*/
gulp.task('build-clean', function () {
    console.log("----------------------");
    sequence('clean',
            'whitespace',
            ['js','css'],
            'html'
            );
});
<commit_msg>Added author information to gulpfile.js<commit_after>/*
    Licenced Under MIT
    @file gulpfile.js
    @author Nagaraja.T (github/naga2raja)
    @desc Buildfile for angular-multiselect
*/

var gulp = require('gulp'),
    clean = require('gulp-clean'),
    watch = require('gulp-watch'),
    sequence = require('run-sequence'),
    minify = require('gulp-ngmin');
    order = require('gulp-order'),
    jshint = require('gulp-jshint'),
    lintspaces = require("gulp-lintspaces"),
    jshintsummary = require('jshint-summary'),
    lintspacesConfig = {
        indentation: 'spaces',
        spaces: 4,
        trailingspaces: true,
        ignores: [
            'js-comments'
        ]
    };

/*
 Gulp monitors the src tree and rebuilds it detects a modification. Used of dev purpose
*/
gulp.task('watch', function() {
    watch("src/**/*.*", function() {
        gulp.start("build-clean");
    });
});

gulp.task('default', ['build-clean'], function() {
});

/*
 Check for lintspaces errors in source code
*/
gulp.task('whitespace', function() {
    return gulp.src([
            'src/*.js',
            'src/*.html',
            'src/*.css'])
        .pipe(lintspaces(lintspacesConfig))
        .pipe(lintspaces.reporter());
});

/* For Future Use -- Currently not used */
gulp.task('scripts', function() {
    return gulp.src('src/*.js')
        .pipe(order([
            "app.js",
            "multiselect.js",
            "multiselect-tpls.js"]))
        .pipe(jshint.reporter('jshint-summary', {
            verbose: true,
            reasonCol: 'cyan,bold',
            codeCol: 'green'
        }))
        .pipe(gulp.dest('dist'));
});

/* For future use to compress */
gulp.task('compress', function() {
    return gulp.src('src/*.js')
        .pipe(minify({dynamic: true}))
        .pipe(gulp.dest('dist'));
});

gulp.task('js', function () {
    return gulp.src('src/*.js')
        .pipe(gulp.dest('dist'));
});

gulp.task('css', function () {
    return gulp.src('src/*.css')
        .pipe(gulp.dest('dist'));
});

gulp.task('html', function () {
    return gulp.src('src/*.html')
        .pipe(gulp.dest('dist'));
});

gulp.task('clean', function() {
    return gulp.src(['dist'], {read: false})
        .pipe(clean());
});

/*
 Need to finish clean before building all the other stuff, and all other stuff
 needs to complete before injecting build artifacts into index.html.
*/
gulp.task('build-clean', function () {
    console.log("----------------------");
    sequence('clean',
            'whitespace',
            ['js','css'],
            'html'
            );
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
const fs = require('fs');
const del = require('del');
const glob = require('glob');
const path = require('path');
const mkdirp = require('mkdirp');
const babelify = require('babelify');
const isparta = require('isparta');
const esperanto = require('esperanto');
const browserify = require('browserify');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');
const manifest = require('./package.json');
const config = manifest.seniOptions;
const mainFile = manifest.main;
const destinationFolder = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));

// Remove the built files
gulp.task('clean', function(cb) {
  del([destinationFolder], cb);
});

// Remove our temporary files
gulp.task('clean-tmp', function(cb) {
  del(['tmp'], cb);
});

// Send a notification when JSHint fails,
// so that you know your changes didn't build
function jshintNotify(file) {
  if (!file.jshint) { return; }
  return file.jshint.success ? false : 'JSHint failed';
}

function jscsNotify(file) {
  if (!file.jscs) { return; }
  return file.jscs.success ? false : 'JSRC failed';
}

// Lint our source code
gulp.task('lint-src', function() {
  return gulp.src(['src/**/*.js'])
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.notify(jshintNotify))
    .pipe($.jscs())
    .pipe($.notify(jscsNotify))
    .pipe($.jshint.reporter('fail'));
});

// Lint our test code
gulp.task('lint-test', function() {
  return gulp.src(['test/**/*.js'])
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.notify(jshintNotify))
    .pipe($.jscs())
    .pipe($.notify(jscsNotify))
    .pipe($.jshint.reporter('fail'));
});

// Build two versions of the library
gulp.task('build', ['lint-src', 'clean'], function(done) {
  esperanto.bundle({
    base: 'src',
    entry: config.entryFileName
  }).then(function(bundle) {
    var res = bundle.toUmd({
      sourceMap: true,
      sourceMapSource: config.entryFileName + '.js',
      sourceMapFile: exportFileName + '.js',
      name: config.exportVarName
    });
    // Write the generated sourcemap
    mkdirp.sync(destinationFolder);
    fs.writeFileSync(path.join(destinationFolder, exportFileName + '.js'), res.map.toString());

    $.file(exportFileName + '.js', res.code, { src: true })
      .pipe($.plumber())
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.babel({ blacklist: ['useStrict'] }))
      .pipe($.sourcemaps.write('./', {addComment: false}))
      .pipe(gulp.dest(destinationFolder))
      .pipe($.filter(['*', '!**/*.js.map']))
      .pipe($.rename(exportFileName + '.min.js'))
      .pipe($.uglifyjs({
        outSourceMap: true,
        inSourceMap: destinationFolder + '/' + exportFileName + '.js.map'
      }))
      .pipe(gulp.dest(destinationFolder))
      .on('end', done);
  });
});

// Bundle our app for our unit tests
gulp.task('browserify', function() {
  var testFiles = glob.sync('./test/unit/**/*');
  var allFiles = ['./test/setup/browserify.js'].concat(testFiles);
  var bundler = browserify(allFiles);
  bundler.transform(babelify.configure({
    sourceMapRelative: __dirname + '/src',
    blacklist: ['useStrict']
  }));
  var bundleStream = bundler.bundle();
  return bundleStream
    .on('error', function(err){
      console.log(err.message);
      this.emit('end');
    })
    .pipe($.plumber())
    .pipe(source('./tmp/__spec-build.js'))
    .pipe(gulp.dest(''))
    .pipe($.livereload());
});

gulp.task('coverage', function(done) {
  require('babel/register')({ modules: 'common' });
  gulp.src(['src/**/*.js'])
    .pipe($.plumber())
    .pipe($.istanbul({ instrumenter: isparta.Instrumenter }))
    .pipe($.istanbul.hookRequire())
    .on('finish', function() {
      return test()
      .pipe($.istanbul.writeReports())
      .on('end', done);
    });
});

function test() {

  return gulp.src(['test/setup/node.js', 'test/unit/**/*.js'], {read: false})
    .pipe($.plumber())
    .pipe($.mocha({reporter: 'dot', globals: config.mochaGlobals}));
};

// Lint and run our tests
gulp.task('test', ['lint-src', 'lint-test'], function() {
  require('babel/register')({ modules: 'common' });
  return test();
});

// Ensure that linting occurs before browserify runs. This prevents
// the build from breaking due to poorly formatted code.
gulp.task('build-in-sequence', function(callback) {
  runSequence(['lint-src', 'lint-test'], 'browserify', callback);
});

// Run the headless unit tests as you make changes.
gulp.task('watch', function() {
  gulp.watch(['src/**/*', 'test/**/*', '.jshintrc', 'test/.jshintrc'], ['test']);
});

// Set up a livereload environment for our spec runner
gulp.task('test-browser', ['build-in-sequence'], function() {
  $.livereload.listen({port: 35729, host: 'localhost', start: true});
  return gulp.watch(['src/**/*.js', 'test/**/*', '.jshintrc', 'test/.jshintrc'], ['build-in-sequence']);
});

// An alias of test
gulp.task('default', ['test']);
<commit_msg>gulp build-watch<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
const fs = require('fs');
const del = require('del');
const glob = require('glob');
const path = require('path');
const mkdirp = require('mkdirp');
const babelify = require('babelify');
const isparta = require('isparta');
const esperanto = require('esperanto');
const browserify = require('browserify');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');
const manifest = require('./package.json');
const config = manifest.seniOptions;
const mainFile = manifest.main;
const destinationFolder = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));

// Remove the built files
gulp.task('clean', function(cb) {
  del([destinationFolder], cb);
});

// Remove our temporary files
gulp.task('clean-tmp', function(cb) {
  del(['tmp'], cb);
});

// Send a notification when JSHint fails,
// so that you know your changes didn't build
function jshintNotify(file) {
  if (!file.jshint) { return; }
  return file.jshint.success ? false : 'JSHint failed';
}

function jscsNotify(file) {
  if (!file.jscs) { return; }
  return file.jscs.success ? false : 'JSRC failed';
}

// Lint our source code
gulp.task('lint-src', function() {
  return gulp.src(['src/**/*.js'])
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.notify(jshintNotify))
    .pipe($.jscs())
    .pipe($.notify(jscsNotify))
    .pipe($.jshint.reporter('fail'));
});

// Lint our test code
gulp.task('lint-test', function() {
  return gulp.src(['test/**/*.js'])
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.notify(jshintNotify))
    .pipe($.jscs())
    .pipe($.notify(jscsNotify))
    .pipe($.jshint.reporter('fail'));
});

// Build two versions of the library
gulp.task('build', ['lint-src', 'clean'], function(done) {
  esperanto.bundle({
    base: 'src',
    entry: config.entryFileName
  }).then(function(bundle) {
    var res = bundle.toUmd({
      sourceMap: true,
      sourceMapSource: config.entryFileName + '.js',
      sourceMapFile: exportFileName + '.js',
      name: config.exportVarName
    });
    // Write the generated sourcemap
    mkdirp.sync(destinationFolder);
    fs.writeFileSync(path.join(destinationFolder, exportFileName + '.js'), res.map.toString());

    $.file(exportFileName + '.js', res.code, { src: true })
      .pipe($.plumber())
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.babel({ blacklist: ['useStrict'] }))
      .pipe($.sourcemaps.write('./', {addComment: false}))
      .pipe(gulp.dest(destinationFolder))
      .pipe($.filter(['*', '!**/*.js.map']))
      .pipe($.rename(exportFileName + '.min.js'))
      .pipe($.uglifyjs({
        outSourceMap: true,
        inSourceMap: destinationFolder + '/' + exportFileName + '.js.map'
      }))
      .pipe(gulp.dest(destinationFolder))
      .on('end', done);
  });
});

// Bundle our app for our unit tests
gulp.task('browserify', function() {
  var testFiles = glob.sync('./test/unit/**/*');
  var allFiles = ['./test/setup/browserify.js'].concat(testFiles);
  var bundler = browserify(allFiles);
  bundler.transform(babelify.configure({
    sourceMapRelative: __dirname + '/src',
    blacklist: ['useStrict']
  }));
  var bundleStream = bundler.bundle();
  return bundleStream
    .on('error', function(err){
      console.log(err.message);
      this.emit('end');
    })
    .pipe($.plumber())
    .pipe(source('./tmp/__spec-build.js'))
    .pipe(gulp.dest(''))
    .pipe($.livereload());
});

gulp.task('coverage', function(done) {
  require('babel/register')({ modules: 'common' });
  gulp.src(['src/**/*.js'])
    .pipe($.plumber())
    .pipe($.istanbul({ instrumenter: isparta.Instrumenter }))
    .pipe($.istanbul.hookRequire())
    .on('finish', function() {
      return test()
      .pipe($.istanbul.writeReports())
      .on('end', done);
    });
});

function test() {

  return gulp.src(['test/setup/node.js', 'test/unit/**/*.js'], {read: false})
    .pipe($.plumber())
    .pipe($.mocha({reporter: 'dot', globals: config.mochaGlobals}));
};

// Lint and run our tests
gulp.task('test', ['lint-src', 'lint-test'], function() {
  require('babel/register')({ modules: 'common' });
  return test();
});

// Ensure that linting occurs before browserify runs. This prevents
// the build from breaking due to poorly formatted code.
gulp.task('build-in-sequence', function(callback) {
  runSequence(['lint-src', 'lint-test'], 'browserify', callback);
});

// Run the headless unit tests as you make changes.
gulp.task('watch', function() {
  gulp.watch(['src/**/*', 'test/**/*', '.jshintrc', 'test/.jshintrc'], ['test']);
});

// Build as you make changes.
gulp.task('build-watch', function() {
  gulp.watch(['src/**/*'], ['build']);
});

// Set up a livereload environment for our spec runner
gulp.task('test-browser', ['build-in-sequence'], function() {
  $.livereload.listen({port: 35729, host: 'localhost', start: true});
  return gulp.watch(['src/**/*.js', 'test/**/*', '.jshintrc', 'test/.jshintrc'], ['build-in-sequence']);
});

// An alias of test
gulp.task('default', ['test']);
<|endoftext|>


<commit_before>var test = require('tap').test,
    shremlin = require('..'),
    createGraph = require('ngraph.graph');

test('visit all edges', function (t) {
  // this is our test graph:
  // 1 -> 2 <- 3
  //      v
  // 6 <- 4 -> 5
  var graph = createGraph();
  graph.addLink(1, 2); graph.addLink(3, 2);
  graph.addLink(2, 4); graph.addLink(4, 5); graph.addLink(4, 6);
  g = shremlin(graph);

  t.test('4 | outE', function (t) {
    t.plan(2);
    g.V(4)
      .outE()
      .forEach(function (edge) {
        t.ok(edge.fromId === 4 && ([6, 5].indexOf(edge.toId) > -1), "Outgoing edges from vertex 4 connect to correct neighbors");
      });
  });

  t.test('2 | inE', function (t) {
    t.plan(2);
    g.V(2)
      .inE()
      .forEach(function (edge) {
        t.ok(edge.toId === 2 && ([1, 3].indexOf(edge.fromId) > -1), "Incoming edges to vertex 2 connect from correct neighbors");
      });
  });
  t.test('2 | bothE', function (t) {
    t.plan(6); // six because we have 3 edges times two asserts
    g.V(2)
      .bothE()
      .forEach(function (edge) {
        t.ok(edge.toId === 2 || edge.toId === 4, "To ids are only 2 and 4");
        t.ok([1, 2, 3].indexOf(edge.fromId) >= -1, "From ids are 1 2 and 3");
      });
  });
});

test('Visit filtered edges', function (t) {
  var graph = createGraph();
  graph.addLink(1, 3, 'mother');
  graph.addLink(1, 4, 'father'); graph.addLink(5, 1, 'father');

  g = shremlin(graph);
  t.plan(2);
  g.V(5)
   .outE('father')
   .forEach(function (edge) {
     t.equal(edge.toId, 1, 'Father of 5 is 1');
   });

  g.V(5)
   .outE('father')
   .inV()
   .outE('father')
   .forEach(function(edge) {
     t.equal(edge.toId, 4, 'Father of 1 is 4');
   });
   // todo: more tests for bothE, inE
});
<commit_msg>More tests for edge iterators<commit_after>var test = require('tap').test,
    shremlin = require('..'),
    createGraph = require('ngraph.graph');

test('visit all edges', function (t) {
  // this is our test graph:
  // 1 -> 2 <- 3
  //      v
  // 6 <- 4 -> 5
  var graph = createGraph();
  graph.addLink(1, 2); graph.addLink(3, 2);
  graph.addLink(2, 4); graph.addLink(4, 5); graph.addLink(4, 6);
  g = shremlin(graph);

  t.test('4 | outE', function (t) {
    t.plan(2);
    g.V(4)
      .outE()
      .forEach(function (edge) {
        t.ok(edge.fromId === 4 && ([6, 5].indexOf(edge.toId) > -1), "Outgoing edges from vertex 4 connect to correct neighbors");
      });
  });

  t.test('2 | inE', function (t) {
    t.plan(2);
    g.V(2)
      .inE()
      .forEach(function (edge) {
        t.ok(edge.toId === 2 && ([1, 3].indexOf(edge.fromId) > -1), "Incoming edges to vertex 2 connect from correct neighbors");
      });
  });
  t.test('2 | bothE', function (t) {
    t.plan(6); // six because we have 3 edges times two asserts
    g.V(2)
      .bothE()
      .forEach(function (edge) {
        t.ok(edge.toId === 2 || edge.toId === 4, "To ids are only 2 and 4");
        t.ok([1, 2, 3].indexOf(edge.fromId) >= -1, "From ids are 1 2 and 3");
      });
  });
});

test('Visit filtered edges', function (t) {
  var graph = createGraph();
  graph.addLink(1, 3, 'mother');
  graph.addLink(1, 4, 'father'); graph.addLink(5, 1, 'father');

  g = shremlin(graph);
  t.plan(5);
  g.V(5)
   .outE('father')
   .forEach(function (edge) {
     t.equal(edge.toId, 1, 'Father of 5 is 1');
   });

  g.V(5)
   .outE('father')
   .inV()
   .outE('father')
   .forEach(function(edge) {
     t.equal(edge.toId, 4, 'Father of 1 is 4');
   });

  g.V(5)
   .outE('father')
   .bothV()
   .forEach(function(vertex) {
     t.ok([5, 1].indexOf(vertex.id) > -1, 'Both 1 and 5 should be returned');
   });

  g.V(5)
   .outE('father')
   .outV()
   .forEach(function(vertex) {
     t.equal(vertex.id, 5, 'Should come back to where it started');
   });
});
<|endoftext|>


<commit_before>/**
 * Created by fuhuixiang on 16-8-15.
 */
"use strict";

var gulp = require('gulp'),
    sass = require('gulp-sass');

gulp.task('test', ()=> {
    gulp.src('./test/*.scss')
        .pipe(sass({
            includePaths: require('./index').includePaths,
            // outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(gulp.dest('./test/'));
});

gulp.task('test:watch', ()=> {
    gulp.watch('./test/*.scss', ['test']);
});
<commit_msg>修改测试脚本<commit_after>/**
 * Created by fuhuixiang on 16-8-15.
 */
"use strict";

const gulp = require('gulp'),
      sass = require('gulp-sass');

gulp.task('test', () => {
    gulp.src('./test/*.scss')
        .pipe(sass({
            includePaths: require('./index').includePaths,
            // outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(gulp.dest('./test/'));
});

gulp.task('test:watch', () => {
    gulp.watch('./test/*.scss', ['test']);
});
<|endoftext|>


<commit_before>describe('Unit: mediaCenterWidget: Services', function () {
    var COLLECTIONS;
    beforeEach(module('mediaCenterWidget'));

    beforeEach(inject(function ($injector) {
        COLLECTIONS = $injector.get('COLLECTIONS');
    }));

    describe('Unit : Buildfire service', function () {
        var Buildfire;
        beforeEach(inject(
            function (_Buildfire_) {
                Buildfire = _Buildfire_;
            }));
        it('Buildfire should exists', function () {
            expect(Buildfire).toBeDefined();
        });
    });

    describe('Unit : MediaCenter service', function () {
        var DB, MediaCenter;
        beforeEach(inject(
            function (_DB_) {
                DB = _DB_;
                MediaCenter = new DB(COLLECTIONS.MediaCenter);
            }));
        it('MediaCenter should exists', function () {
            expect(MediaCenter).toBeDefined();
            expect(MediaCenter._tagName).toEqual(COLLECTIONS.MediaCenter);
        });
        it('MediaCenter methods should exists', function () {
            expect(MediaCenter.get).toBeDefined();
            expect(MediaCenter.find).toBeDefined();
            expect(MediaCenter.save).toBeDefined();
            expect(MediaCenter.update).toBeDefined();
            expect(MediaCenter.delete).toBeDefined();
            expect(MediaCenter.insert).toBeDefined();
        });
    });

    describe('Unit : MediaContent service', function () {
        var DB, MediaContent;
        beforeEach(inject(
            function (_DB_) {
                DB = _DB_;
                MediaContent = new DB(COLLECTIONS.MediaContent);
            }));
        it('MediaContent should exists', function () {
            expect(MediaContent).toBeDefined();
            expect(MediaContent._tagName).toEqual(COLLECTIONS.MediaContent);
        });
        it('MediaCenter methods should exists', function () {
            expect(MediaContent.get).toBeDefined();
            expect(MediaContent.find).toBeDefined();
            expect(MediaContent.save).toBeDefined();
            expect(MediaContent.update).toBeDefined();
            expect(MediaContent.delete).toBeDefined();
            expect(MediaContent.insert).toBeDefined();
        });
    });

});

describe('Unit : ImageLib Factory', function () {
    //var ImageLibrary, Buildfire, STATUS_MESSAGES, STATUS_CODE, q;
    beforeEach(module('mediaCenterWidgetServices'));
    beforeEach(inject(function () {
        Buildfire = {
            imageLib: {}
        };
        Buildfire.imageLib = jasmine.createSpyObj('Buildfire.imageLib', ['showDialog']);
    }));

    it('Buildfire should exist and be an object', function () {
        expect(typeof Buildfire).toEqual('object');
    });
    it('Buildfire.imageLib should exist and be an object', function () {
        expect(typeof Buildfire.imageLib).toEqual('object');
    });

});<commit_msg>Added test cases for services in widget section<commit_after>describe('Unit: mediaCenterWidget: Services', function () {
    var COLLECTIONS;
    beforeEach(module('mediaCenterWidget'));

    beforeEach(inject(function ($injector) {
        COLLECTIONS = $injector.get('COLLECTIONS');
    }));

    describe('Unit : Buildfire service', function () {
        var Buildfire;
        beforeEach(inject(
            function (_Buildfire_) {
                Buildfire = _Buildfire_;
            }));
        it('Buildfire should exists', function () {
            expect(Buildfire).toBeDefined();
        });
    });

    describe('Unit : MediaCenter service', function () {
        var DB, MediaCenter;
        beforeEach(inject(
            function (_DB_) {
                DB = _DB_;
                MediaCenter = new DB(COLLECTIONS.MediaCenter);
            }));
        it('MediaCenter should exists', function () {
            expect(MediaCenter).toBeDefined();
            expect(MediaCenter._tagName).toEqual(COLLECTIONS.MediaCenter);
        });
        it('MediaCenter methods should exists', function () {
            expect(MediaCenter.get).toBeDefined();
            expect(MediaCenter.find).toBeDefined();
            expect(MediaCenter.save).toBeDefined();
            expect(MediaCenter.update).toBeDefined();
            expect(MediaCenter.delete).toBeDefined();
            expect(MediaCenter.insert).toBeDefined();
        });
    });

    describe('Unit : MediaContent service', function () {
        var DB, MediaContent;
        beforeEach(inject(
            function (_DB_) {
                DB = _DB_;
                MediaContent = new DB(COLLECTIONS.MediaContent);
            }));
        it('MediaContent should exists', function () {
            expect(MediaContent).toBeDefined();
            expect(MediaContent._tagName).toEqual(COLLECTIONS.MediaContent);
        });
        it('MediaCenter methods should exists', function () {
            expect(MediaContent.get).toBeDefined();
            expect(MediaContent.find).toBeDefined();
            expect(MediaContent.save).toBeDefined();
            expect(MediaContent.update).toBeDefined();
            expect(MediaContent.delete).toBeDefined();
            expect(MediaContent.insert).toBeDefined();
        });
        it('MediaCenter methods should exists', function () {
            Buildfire={datastore:{get:function(tagName,cb){
                cb(null,{});
            }}};
            MediaContent.insert([]);
            MediaContent.insert('asads');
            MediaContent.getById('id1');
            MediaContent.insert();
            MediaContent.find();
            MediaContent.find({});
            MediaContent.update('id',{});
            MediaContent.update();
            MediaContent.update('id');
            MediaContent.save({});
            MediaContent.save();
            MediaContent.delete();
            MediaContent.delete('id');
        });
    });

});

describe('Unit : ImageLib Factory', function () {
    //var ImageLibrary, Buildfire, STATUS_MESSAGES, STATUS_CODE, q;
    beforeEach(module('mediaCenterWidgetServices'));
    beforeEach(inject(function () {
        Buildfire = {
            imageLib: {}
        };
        Buildfire.imageLib = jasmine.createSpyObj('Buildfire.imageLib', ['showDialog']);
    }));

    it('Buildfire should exist and be an object', function () {
        expect(typeof Buildfire).toEqual('object');
    });
    it('Buildfire.imageLib should exist and be an object', function () {
        expect(typeof Buildfire.imageLib).toEqual('object');
    });
    it('Buildfire.imageLib should exist and be an object', function () {
        expect(typeof Buildfire.imageLib).toEqual('object');
    });

});<|endoftext|>


<commit_before>var gulp = require('gulp');
var mocha = require('gulp-mocha');
var jshint = require('gulp-jshint');
var eslint = require('gulp-eslint');

gulp.task('test', function() {
    return gulp.src('test/*.spec.js')
        .pipe(mocha({reporter: 'spec'}));
});

gulp.task('lint', ['test'], function() {
    return gulp.src('index.js')
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failOnError());
});

gulp.task('default', ['test', 'lint'], function() {
});<commit_msg>Oops, make sure to remove all references to jshint<commit_after>var gulp = require('gulp');
var mocha = require('gulp-mocha');
var eslint = require('gulp-eslint');

gulp.task('test', function() {
    return gulp.src('test/*.spec.js')
        .pipe(mocha({reporter: 'spec'}));
});

gulp.task('lint', ['test'], function() {
    return gulp.src('index.js')
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failOnError());
});

gulp.task('default', ['test', 'lint'], function() {
});<|endoftext|>


<commit_before>import 'topojson'
import Datamap from 'datamaps/dist/datamaps.usa'
import * as util from './utils/choropleth'
import colormap from 'colormap'
import * as marker from './markers/choropleth'

// Map interaction functions

// Draw map on given element
// Takes d3 instance
export default class Choropleth {
  constructor(d3, elementId, regionHook) {

    let footBB = d3.select('.footer').node().getBoundingClientRect(),
        chartBB = d3.select('#' + elementId).node().getBoundingClientRect()

    let divWidth = chartBB.width,
        divHeight = window.innerHeight - chartBB.top - footBB.height

    // Padding offsets
    divHeight -= 50

    // Limits
    divHeight = Math.min(Math.max(350, divHeight), 600)

    // Initialized datamap
    let datamap = new Datamap({
      element: document.getElementById(elementId),
      scope: 'usa',
      setProjection: (element, options) => {
        let projection = d3.geoAlbersUsa()
          .scale(divWidth)
          .translate([divWidth / 2, divHeight / 2])
        return {
          path: d3.geoPath().projection(projection),
          projection: projection
        }
      },
      fills: {
        defaultFill: '#ccc'
      },
      geographyConfig: {
        highlightOnHover: false,
        popupOnHover: false
      }
    })

    // Add hover info div
    this.tooltip = d3.select('body').append('div')
      .attr('id', 'choropleth-tooltip')
      .style('display', 'none')

    let svg = d3.select('#' + elementId + ' svg')
        .attr('height', divHeight)
        .attr('width', divWidth)
    this.width = svg.node().getBoundingClientRect().width
    this.height = svg.node().getBoundingClientRect().height
    this.svg = svg
    this.d3 = d3
    this.regionHook = regionHook
  }

  /**
   * Plot data on map
   * Triggered on:
   *   - Choropleth selector change
   *   - Season selector change
   */
  plot(data) {

    let d3 = this.d3,
        svg = this.svg,
        regionHook = this.regionHook,
        tooltip = this.tooltip

    let minData = data.range[0],
        maxData = data.range[1]

    let colormapName,
        limits = [],
        barLimits = []

    if (data.type === 'sequential') {
      // Set a 0 to max ranged colorscheme
      this.cmap = colormap({
        colormap: 'YIOrRd',
        nshades: 50,
        format: 'rgbaString'
      })

      limits = [maxData, 0]
      barLimits = [0, maxData]

    } else if (data.type === 'diverging') {
      this.cmap = colormap({
        colormap: 'RdBu',
        nshades: 50,
        format: 'rgbaString'
      }).reverse()

      let extreme = Math.max(Math.abs(maxData), Math.abs(minData))

      limits = [extreme, -extreme]
      barLimits = [-extreme, extreme]
    }

    this.colorScale = d3.scaleLinear()
      .domain(limits)
      .range([0, this.cmap.length - 0.01])

    // Setup color bar
    this.colorBar = new marker.ColorBar(d3, svg, this.cmap)
    this.colorBar.update(barLimits)

    let bb = svg.node().getBoundingClientRect()

    // Set on hover items
    d3.selectAll('.datamaps-subunit')
      .on('mouseover', function() {
        d3.selectAll('.datamaps-subunit')
          .filter(d => util.getCousins(this, data.data)
                  .indexOf(d.id) > -1)
          .style('opacity', '0.4')
        tooltip.style('display', null)
      })
      .on('mouseout', function() {
        d3.selectAll('.datamaps-subunit')
          .filter(d => util.getCousins(this, data.data)
                  .indexOf(d.id) > -1)
          .style('opacity', '1.0')
        tooltip.style('display', 'none')
      })
      .on('mousemove', function() {
        tooltip
          .style('top', (d3.event.pageY + 20) + 'px')
          .style('left', (d3.event.pageX + 20) + 'px')
          .html(util.tooltipText(this, data.data))
      })
      .on('click', function() {
        // Change the region selector
        regionHook(util.getRegionId(util.getSiblings(this, data.data).region))
      })

    // Save data
    this.data = data.data
  }

  /**
   * Transition on week change and region highlight
   * Triggered on:
   *   - Week change
   *   - Region selector change
   */
  update(ids) {
    let d3 = this.d3,
        data = this.data,
        colorScale = this.colorScale,
        cmap = this.cmap

    let highlightedStates = [],
        color = null
    if (ids.regionIdx >= 0) {
      highlightedStates = data[ids.regionIdx].states
    }

    // Update colors for given week
    data.map(d => {
      let value = d.value[ids.weekIdx].data
      let color = '#ccc'
      if (value) color = cmap[Math.floor(colorScale(value))]

      d.states.map(s => {
        let d3State = d3.select('.' + s)

        if (highlightedStates.indexOf(s) > -1) {
          d3State.style('stroke', '#333')
            .style('stroke-opacity', 1)
        } else {
          d3State.style('stroke', 'white')
            .style('stroke-opacity', 0)
        }

        d3State.style('fill', color)
        d3State.attr('data-value', value)
      })
    })
  }
}
<commit_msg>Use -1 as absence of data<commit_after>import 'topojson'
import Datamap from 'datamaps/dist/datamaps.usa'
import * as util from './utils/choropleth'
import colormap from 'colormap'
import * as marker from './markers/choropleth'

// Map interaction functions

// Draw map on given element
// Takes d3 instance
export default class Choropleth {
  constructor(d3, elementId, regionHook) {

    let footBB = d3.select('.footer').node().getBoundingClientRect(),
        chartBB = d3.select('#' + elementId).node().getBoundingClientRect()

    let divWidth = chartBB.width,
        divHeight = window.innerHeight - chartBB.top - footBB.height

    // Padding offsets
    divHeight -= 50

    // Limits
    divHeight = Math.min(Math.max(350, divHeight), 600)

    // Initialized datamap
    let datamap = new Datamap({
      element: document.getElementById(elementId),
      scope: 'usa',
      setProjection: (element, options) => {
        let projection = d3.geoAlbersUsa()
          .scale(divWidth)
          .translate([divWidth / 2, divHeight / 2])
        return {
          path: d3.geoPath().projection(projection),
          projection: projection
        }
      },
      fills: {
        defaultFill: '#ccc'
      },
      geographyConfig: {
        highlightOnHover: false,
        popupOnHover: false
      }
    })

    // Add hover info div
    this.tooltip = d3.select('body').append('div')
      .attr('id', 'choropleth-tooltip')
      .style('display', 'none')

    let svg = d3.select('#' + elementId + ' svg')
        .attr('height', divHeight)
        .attr('width', divWidth)
    this.width = svg.node().getBoundingClientRect().width
    this.height = svg.node().getBoundingClientRect().height
    this.svg = svg
    this.d3 = d3
    this.regionHook = regionHook
  }

  /**
   * Plot data on map
   * Triggered on:
   *   - Choropleth selector change
   *   - Season selector change
   */
  plot(data) {

    let d3 = this.d3,
        svg = this.svg,
        regionHook = this.regionHook,
        tooltip = this.tooltip

    let minData = data.range[0],
        maxData = data.range[1]

    let colormapName,
        limits = [],
        barLimits = []

    if (data.type === 'sequential') {
      // Set a 0 to max ranged colorscheme
      this.cmap = colormap({
        colormap: 'YIOrRd',
        nshades: 50,
        format: 'rgbaString'
      })

      limits = [maxData, 0]
      barLimits = [0, maxData]

    } else if (data.type === 'diverging') {
      this.cmap = colormap({
        colormap: 'RdBu',
        nshades: 50,
        format: 'rgbaString'
      }).reverse()

      let extreme = Math.max(Math.abs(maxData), Math.abs(minData))

      limits = [extreme, -extreme]
      barLimits = [-extreme, extreme]
    }

    this.colorScale = d3.scaleLinear()
      .domain(limits)
      .range([0, this.cmap.length - 0.01])

    // Setup color bar
    this.colorBar = new marker.ColorBar(d3, svg, this.cmap)
    this.colorBar.update(barLimits)

    let bb = svg.node().getBoundingClientRect()

    // Set on hover items
    d3.selectAll('.datamaps-subunit')
      .on('mouseover', function() {
        d3.selectAll('.datamaps-subunit')
          .filter(d => util.getCousins(this, data.data)
                  .indexOf(d.id) > -1)
          .style('opacity', '0.4')
        tooltip.style('display', null)
      })
      .on('mouseout', function() {
        d3.selectAll('.datamaps-subunit')
          .filter(d => util.getCousins(this, data.data)
                  .indexOf(d.id) > -1)
          .style('opacity', '1.0')
        tooltip.style('display', 'none')
      })
      .on('mousemove', function() {
        tooltip
          .style('top', (d3.event.pageY + 20) + 'px')
          .style('left', (d3.event.pageX + 20) + 'px')
          .html(util.tooltipText(this, data.data))
      })
      .on('click', function() {
        // Change the region selector
        regionHook(util.getRegionId(util.getSiblings(this, data.data).region))
      })

    // Save data
    this.data = data.data
  }

  /**
   * Transition on week change and region highlight
   * Triggered on:
   *   - Week change
   *   - Region selector change
   */
  update(ids) {
    let d3 = this.d3,
        data = this.data,
        colorScale = this.colorScale,
        cmap = this.cmap

    let highlightedStates = [],
        color = null
    if (ids.regionIdx >= 0) {
      highlightedStates = data[ids.regionIdx].states
    }

    // Update colors for given week
    data.map(d => {
      let value = d.value[ids.weekIdx].data
      let color = '#ccc'
      if (value !== -1) color = cmap[Math.floor(colorScale(value))]

      d.states.map(s => {
        let d3State = d3.select('.' + s)

        if (highlightedStates.indexOf(s) > -1) {
          d3State.style('stroke', '#333')
            .style('stroke-opacity', 1)
        } else {
          d3State.style('stroke', 'white')
            .style('stroke-opacity', 0)
        }

        d3State.style('fill', color)
        d3State.attr('data-value', value)
      })
    })
  }
}
<|endoftext|>


<commit_before>var fs = require('../');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
var test = require('tap').test;
var p = require('path').resolve(__dirname, 'files');

process.chdir(__dirname)

// Make sure to reserve the stderr fd
process.stderr.write('');

var num = 4097;
var paths = new Array(num);

test('make files', function (t) {
  rimraf.sync(p);
  mkdirp.sync(p);

  for (var i = 0; i < num; ++i) {
    paths[i] = 'files/file-' + i;
    fs.writeFileSync(paths[i], 'content');
  }

  t.end();
})

test('read files', function (t) {
  // now read them
  var done = 0;
  for (var i = 0; i < num; ++i) {
    fs.readFile(paths[i], function(err, data) {
      if (err)
        throw err;

      ++done;
      if (done === num) {
        t.pass('success');
        t.end()
      }
    });
  }
});

test('cleanup', function (t) {
  rimraf.sync(p);
  t.end();
});
<commit_msg>test: Use plan instead of manual count<commit_after>var fs = require('../');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
var test = require('tap').test;
var p = require('path').resolve(__dirname, 'files');

process.chdir(__dirname)

// Make sure to reserve the stderr fd
process.stderr.write('');

var num = 4097;
var paths = new Array(num);

test('make files', function (t) {
  rimraf.sync(p);
  mkdirp.sync(p);

  for (var i = 0; i < num; ++i) {
    paths[i] = 'files/file-' + i;
    fs.writeFileSync(paths[i], 'content');
  }

  t.end();
})

test('read files', function (t) {
  // now read them
  t.plan(num)
  for (var i = 0; i < num; ++i) {
    fs.readFile(paths[i], 'ascii', function(err, data) {
      if (err)
        throw err;

      t.equal(data, 'content')
    });
  }
});

test('cleanup', function (t) {
  rimraf.sync(p);
  t.end();
});
<|endoftext|>