<commit_before>'use strict';

var chai = require('chai');
var expect = chai.expect;

var PgDatabase = require('pg-database');
var authorSchema = require('pg-database/lib/schemas/authors');
var bookshelfMiddleware = require('../');

var database = new PgDatabase({
      'client': 'sqlite',
      'connection': {
        'filename': ':memory:'
      },
      'pool': {
        'max': 1
      }
    });

var bookshelf = database.bookshelf;

describe('CRUD methods on ORM objects', function () {
  var res, req, knex;

  beforeEach(function (done) {

    knex = database.bookshelf.knex;
    resetTable(done);

    res = {};
    req = {};
  });

  describe('#find', function() {
    it('should be possible to find an object by id', function (done) {
      req.where = {id: 1};

      bookshelfMiddleware.find({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.attributes.long_name).to.equal('George Abitbol');
        expect(res.body.attributes.short_name).to.equal('G.A.');
        done();
      });
    });

    it('should return null when an object is not found', function (done) {
      req.where = {id: 10};

      bookshelfMiddleware.find({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body).to.be.null;
        done();
      });
    });

    it('should be possible to add withRelated option in where', function (done) {
      req.where = {id: 1};
      req.opts = {withRelated: 'user'};

      bookshelfMiddleware.find({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        done();
      });
    });

    it('should fetch an author its long name', function (done) {
      req.where = {long_name: 'George Abitbol'};

      bookshelfMiddleware.find({model: database.Author})
      (req, res, function (err) {
        if (err) done(err);
        expect(res.body.attributes.long_name).to.equal('George Abitbol');
        expect(res.body.attributes.short_name).to.equal('G.A.');
        done();
      });
    });
  });

  describe('#findAll', function() {
    it('should fetch all authors', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.length).to.equal(2);
        expect(res.metadata.limit).to.equal(20);
        expect(res.metadata.offset).to.equal(0);
        expect(res.metadata.count).to.not.exist;
        done();
      });
    });

    it('should be possible to find objects by function', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
      };

      req.where = function (qb) {
        qb.where({id: 1});
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body).to.length(1);
        expect(res.body.models[0]).to.have.property('id', 1);
        done();
      });
    });

    it('should be possible to add a withRelated in where', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
      };

      req.where = {id: 1, withRelated: 'user'};

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body).to.length(0);
        done();
      });
    });

    it('should be possible to set a limit', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 1,
        offset: 0,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.length).to.equal(1);
        done();
      });
    });

    it('should be possible to set an offset', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 10,
        offset: 1,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.length).to.equal(1);
        expect(res.body.models[0]).to.have.property('id', 1);
        done();
      });
    });

    it('should be possible to set a sortBy', function (done) {
      req.options = {
        sortBy: 'shortName',
        sortDirection: 'ASC',
        limit: 10,
        offset: 0,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.models[0]).to.have.property('id', 1);
        done();
      });
    });

    it('should be possible to set a sortDirection', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'DESC',
        limit: 10,
        offset: 0,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.models[0]).to.have.property('id', 2);
        done();
      });
    });

    it('should be possible to find multiple values', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
      };

      req.whereIn = {id: [1, 2]};

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.length).to.equal(2);
        done();
      });
    });

    it('should be possible to count', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
        count: true
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.metadata).to.eql({
          offset: 0,
          limit: 20,
          count: 2
        });
        done();
      });
    });
  });

  describe('#create', function() {
    it('should create an author', function (done) {
      req.body = {
        long_name: 'Georges Abitbol',
        short_name: 'G.A.'
      };
      bookshelfMiddleware.create({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body).to.exists;
        expect(res.body.attributes.long_name).to.equal('Georges Abitbol');

        req.options = {
          sortBy: 'id',
          sortDirection: 'desc',
          limit: 20,
          offset: 0,
        };
        bookshelfMiddleware.findAll({model: database.Author})
        (req, res, function (){
          expect(res.body.length).to.equal(3);
          done();
        });
      });
    });
  });

  describe('#destroy', function() {
    it('should destroy an author', function (done) {
      req = {
        query: {
          id: 1
        }
      };
      bookshelfMiddleware.destroy({model: database.Author})
      (req, res, function (err) {
        if(err) return done(err);
        expect(res.body).to.exists;

        req.options = {
          sortBy: 'id',
          sortDirection: 'desc',
          limit: 20,
          offset: 0,
        };
        bookshelfMiddleware.findAll({model: database.Author})
        (req, res, function (){
          expect(res.body.length).to.equal(1);
          done();
        });
      });
    });

    it('should not destroy if author not found', function (done) {
      req = {
        query: {
          id: 10
        }
      }
      bookshelfMiddleware.destroy({model: database.Author})
      (req, res, function (err) {
        if(err) return done(err);
        expect(res.body).to.exists;

        req.options = {
          sortBy: 'id',
          sortDirection: 'desc',
          limit: 20,
          offset: 0,
        };
        bookshelfMiddleware.findAll({model: database.Author})
        (req, res, function (){
          expect(res.body.length).to.equal(2);
          done();
        });
      });
    });
  });

  describe('#search', function() {
    it('should search for an author', function (done) {
      req.query= {
          q: 'test'
      };

      function search(q, searchParams, next) {
        expect(q).to.equal('test');
        next(null, {
          documents: [{
            id: 0
          }, {
            id: 5
          }]
        });
      };

      bookshelfMiddleware.search({search: search})
      (req, res, function(err) {
        if(err) return done(err);
        expect(req.where.id).to.deep.equal([0, 5]);
        done();
      });
    });
  });

  function resetTable(done) {
    knex.schema.dropTableIfExists('authors')
    .exec(function () {
      knex.schema.createTable('authors', defineTable)
      .exec(populate.bind(null, done));
    });
  }

  function defineTable(table) {
    table.engine('InnoDB');
    table.timestamps();
    table.charset('utf8');
    authorSchema.build(table);
  }

  function populate(done) {
    database.Author.forge().save({
      long_name: 'George Abitbol',
      short_name: 'G.A.',
      origin: 'L\'homme le plus classe du monde'
    }).exec(function () {
      database.Author.forge().save({
        long_name: 'George Abitbol2',
        short_name: 'G.A.2',
        origin: 'L\'homme le plus classe du monde2'
      }).exec(done);
    });
  }
});

describe('req and res formatters', function() {
  describe('snake case formatter', function() {
    it('should convert camel-case keys to snake case', function() {
      var input = {
        where: {
          testData : 1,
          AnotherTestData : 'test'
        }
      };

      bookshelfMiddleware.snakeCaseKeys()(input, {}, function() {
        expect(input.where.testData).to.not.exists;
        expect(input.where.AnotherTestData).to.not.exists;
        expect(input.where.test_data).to.exists;
        expect(input.where.another_test_data).to.exists;
      });
    });

    it('should work with deep', function () {

      var input = {};
      input.where = {
        ar: [
          {
            bigTest: true
          }
        ],
        foo: { barTrue: true }
      };

      bookshelfMiddleware.snakeCaseKeys()(input, {}, function() {
        expect(input.where).to.eql({
          ar: [
            {
              big_test: true
            }
          ],
          foo: { bar_true: true }
        });
      });
    });
  });

  describe('#camelizeKeys', function () {
    it('should camelize all keys', function () {
      var input = {
        where:{
          first_name: 'Johny',
          last_name: 'Begood'
        }
      };

      bookshelfMiddleware.camelizeKeys()(input, {}, function() {
        expect(input.where).to.eql({
          firstName: 'Johny',
          lastName: 'Begood'
        });
      });
    });
  });

    it('should work with deep', function () {
    var input = {
      where:{
        ar: [
          {
            big_test: true
          }
        ],
        foo: { bar_true: true }
      }
    };
    bookshelfMiddleware.camelizeKeys()(input, {}, function() {
      expect(input.where).to.eql({
        ar: [
          {
            bigTest: true
          }
        ],
        foo: { barTrue: true }
      });
    });
  });

  describe('#formatFindAllOptions', function() {
    it('should provide default for findAll query', function () {
      var input = {};
      bookshelfMiddleware.formatFindAllOptions()(input, {}, function() {
        expect(input).to.deep.equal({
          options: {
            sortBy: 'id', sortDirection: 'desc', limit:20, offset:0,
            whereIn: {}
          },
          where: {}
        });
      });
    });

    it('should not override provided parameters', function () {
      var input = {
        options: {
          sortBy:'test',
          sortDirection: 'asc'
        }
      };
      bookshelfMiddleware.formatFindAllOptions()(input, {}, function() {
        expect(input.options.sortBy).to.equal('test');
        expect(input.options.sortDirection).to.equal('asc');
      });
    });

    it('should not convert input if where is a function', function () {
      var input = {
        where: function () {

        }
      };
      bookshelfMiddleware.formatFindAllOptions()(input, {}, function() {
        expect(input.where).to.be.a('function');
      });

    });

    it('should remove array from where value', function () {
      var input = {
        where: {id: [1, 2]}
      };

      bookshelfMiddleware.formatFindAllOptions()(input, {}, function() {
        expect(input.where).to.be.empty;
        expect(input.options.whereIn).to.eql({id: [1,2]});
      });
    });
  });

  describe('#formatFindOptions', function() {
    it('should provide default for find query', function() {
      var input = {};
      bookshelfMiddleware.formatFindOptions()(input, {}, function() {
        expect(input).to.deep.equal({
          options: {},
          where: {id: undefined}
        });
      });
    });

    it('should convert where to an object', function () {
      var input = {
        query: 1
      };
      bookshelfMiddleware.formatFindOptions()(input, {}, function() {
        expect(input.where).to.eql({ id: 1 });
      });

    });

    it('should pick withRelated from where', function () {
      var input = {
        query: {
          withRelated: 'test'
        }
      };
      bookshelfMiddleware.formatFindOptions()(input, {}, function() {
        expect(input.options.withRelated).to.eql('test');
        expect(input.where.withRelated).to.not.exists;
      });
    });
  });

  describe('#formatBackboneModel', function () {
    it('should convert model to JSON', function () {
      var model = new bookshelf.Model({ big_foo: 'bar' });

      var res = {};
      res.body = model;

      bookshelfMiddleware.formatBackboneModel()({}, res, function() {
        expect(res.body).to.eql({ bigFoo: 'bar' });
      });
    });
  });

  describe('#formatBackboneCollection', function () {
    it('should convert collection to JSON', function () {
      var model = new bookshelf.Model({ big_foo: 'bar' });
      var collection = new bookshelf.Collection([model]);

      var res = {};
      res.body = collection;

      bookshelfMiddleware.formatBackboneCollection()({}, res, function() {
        expect(res.body).to.eql([{ bigFoo: 'bar' }]);
      });
    });
  });
});
<commit_msg>updated test for previous fix<commit_after>'use strict';

var chai = require('chai');
var expect = chai.expect;

var PgDatabase = require('pg-database');
var authorSchema = require('pg-database/lib/schemas/authors');
var bookshelfMiddleware = require('../');

var database = new PgDatabase({
      'client': 'sqlite',
      'connection': {
        'filename': ':memory:'
      },
      'pool': {
        'max': 1
      }
    });

var bookshelf = database.bookshelf;

describe('CRUD methods on ORM objects', function () {
  var res, req, knex;

  beforeEach(function (done) {

    knex = database.bookshelf.knex;
    resetTable(done);

    res = {};
    req = {};
  });

  describe('#find', function() {
    it('should be possible to find an object by id', function (done) {
      req.where = {id: 1};

      bookshelfMiddleware.find({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.attributes.long_name).to.equal('George Abitbol');
        expect(res.body.attributes.short_name).to.equal('G.A.');
        done();
      });
    });

    it('should return null when an object is not found', function (done) {
      req.where = {id: 10};

      bookshelfMiddleware.find({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body).to.be.null;
        done();
      });
    });

    it('should be possible to add withRelated option in where', function (done) {
      req.where = {id: 1};
      req.opts = {withRelated: 'user'};

      bookshelfMiddleware.find({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        done();
      });
    });

    it('should fetch an author its long name', function (done) {
      req.where = {long_name: 'George Abitbol'};

      bookshelfMiddleware.find({model: database.Author})
      (req, res, function (err) {
        if (err) done(err);
        expect(res.body.attributes.long_name).to.equal('George Abitbol');
        expect(res.body.attributes.short_name).to.equal('G.A.');
        done();
      });
    });
  });

  describe('#findAll', function() {
    it('should fetch all authors', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.length).to.equal(2);
        expect(res.metadata.limit).to.equal(20);
        expect(res.metadata.offset).to.equal(0);
        expect(res.metadata.count).to.not.exist;
        done();
      });
    });

    it('should be possible to find objects by function', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
      };

      req.where = function (qb) {
        qb.where({id: 1});
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body).to.length(1);
        expect(res.body.models[0]).to.have.property('id', 1);
        done();
      });
    });

    it('should be possible to add a withRelated in where', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
      };

      req.where = {id: 1, withRelated: 'user'};

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body).to.length(0);
        done();
      });
    });

    it('should be possible to set a limit', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 1,
        offset: 0,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.length).to.equal(1);
        done();
      });
    });

    it('should be possible to set an offset', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 10,
        offset: 1,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.length).to.equal(1);
        expect(res.body.models[0]).to.have.property('id', 1);
        done();
      });
    });

    it('should be possible to set a sortBy', function (done) {
      req.options = {
        sortBy: 'shortName',
        sortDirection: 'ASC',
        limit: 10,
        offset: 0,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.models[0]).to.have.property('id', 1);
        done();
      });
    });

    it('should be possible to set a sortDirection', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'DESC',
        limit: 10,
        offset: 0,
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.models[0]).to.have.property('id', 2);
        done();
      });
    });

    it('should be possible to find multiple values', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
      };

      req.whereIn = {id: [1, 2]};

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body.length).to.equal(2);
        done();
      });
    });

    it('should be possible to count', function (done) {
      req.options = {
        sortBy: 'id',
        sortDirection: 'desc',
        limit: 20,
        offset: 0,
        count: true
      };

      bookshelfMiddleware.findAll({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.metadata).to.eql({
          offset: 0,
          limit: 20,
          count: 2
        });
        done();
      });
    });
  });

  describe('#create', function() {
    it('should create an author', function (done) {
      req.body = {
        long_name: 'Georges Abitbol',
        short_name: 'G.A.'
      };
      bookshelfMiddleware.create({model: database.Author})
      (req, res, function (err) {
        if (err) return done(err);
        expect(res.body).to.exists;
        expect(res.body.attributes.long_name).to.equal('Georges Abitbol');

        req.options = {
          sortBy: 'id',
          sortDirection: 'desc',
          limit: 20,
          offset: 0,
        };
        bookshelfMiddleware.findAll({model: database.Author})
        (req, res, function (){
          expect(res.body.length).to.equal(3);
          done();
        });
      });
    });
  });

  describe('#destroy', function() {
    it('should destroy an author', function (done) {
      req = {
        query: {
          id: 1
        }
      };
      bookshelfMiddleware.destroy({model: database.Author})
      (req, res, function (err) {
        if(err) return done(err);
        expect(res.body).to.exists;

        req.options = {
          sortBy: 'id',
          sortDirection: 'desc',
          limit: 20,
          offset: 0,
        };
        bookshelfMiddleware.findAll({model: database.Author})
        (req, res, function (){
          expect(res.body.length).to.equal(1);
          done();
        });
      });
    });

    it('should not destroy if author not found', function (done) {
      req = {
        query: {
          id: 10
        }
      }
      bookshelfMiddleware.destroy({model: database.Author})
      (req, res, function (err) {
        if(err) return done(err);
        expect(res.body).to.exists;

        req.options = {
          sortBy: 'id',
          sortDirection: 'desc',
          limit: 20,
          offset: 0,
        };
        bookshelfMiddleware.findAll({model: database.Author})
        (req, res, function (){
          expect(res.body.length).to.equal(2);
          done();
        });
      });
    });
  });

  describe('#search', function() {
    it('should search for an author', function (done) {
      req.query= {
          q: 'test'
      };

      function search(q, searchParams, next) {
        expect(q).to.equal('test');
        next(null, {
          documents: [{
            id: 0
          }, {
            id: 5
          }]
        });
      };

      bookshelfMiddleware.search({search: search})
      (req, res, function(err) {
        if(err) return done(err);
        expect(req.where.id).to.deep.equal([0, 5]);
        done();
      });
    });
  });

  function resetTable(done) {
    knex.schema.dropTableIfExists('authors')
    .exec(function () {
      knex.schema.createTable('authors', defineTable)
      .exec(populate.bind(null, done));
    });
  }

  function defineTable(table) {
    table.engine('InnoDB');
    table.timestamps();
    table.charset('utf8');
    authorSchema.build(table);
  }

  function populate(done) {
    database.Author.forge().save({
      long_name: 'George Abitbol',
      short_name: 'G.A.',
      origin: 'L\'homme le plus classe du monde'
    }).exec(function () {
      database.Author.forge().save({
        long_name: 'George Abitbol2',
        short_name: 'G.A.2',
        origin: 'L\'homme le plus classe du monde2'
      }).exec(done);
    });
  }
});

describe('req and res formatters', function() {
  describe('snake case formatter', function() {
    it('should convert camel-case keys to snake case', function() {
      var input = {
        where: {
          testData : 1,
          AnotherTestData : 'test'
        }
      };

      bookshelfMiddleware.snakeCaseKeys()(input, {}, function() {
        expect(input.where.testData).to.not.exists;
        expect(input.where.AnotherTestData).to.not.exists;
        expect(input.where.test_data).to.exists;
        expect(input.where.another_test_data).to.exists;
      });
    });

    it('should work with deep', function () {

      var input = {};
      input.where = {
        ar: [
          {
            bigTest: true
          }
        ],
        foo: { barTrue: true }
      };

      bookshelfMiddleware.snakeCaseKeys()(input, {}, function() {
        expect(input.where).to.eql({
          ar: [
            {
              big_test: true
            }
          ],
          foo: { bar_true: true }
        });
      });
    });
  });

  describe('#camelizeKeys', function () {
    it('should camelize all keys', function () {
      var input = {
        where:{
          first_name: 'Johny',
          last_name: 'Begood'
        }
      };

      bookshelfMiddleware.camelizeKeys()(input, {}, function() {
        expect(input.where).to.eql({
          firstName: 'Johny',
          lastName: 'Begood'
        });
      });
    });
  });

    it('should work with deep', function () {
    var input = {
      where:{
        ar: [
          {
            big_test: true
          }
        ],
        foo: { bar_true: true }
      }
    };
    bookshelfMiddleware.camelizeKeys()(input, {}, function() {
      expect(input.where).to.eql({
        ar: [
          {
            bigTest: true
          }
        ],
        foo: { barTrue: true }
      });
    });
  });

  describe('#formatFindAllOptions', function() {
    it('should provide default for findAll query', function () {
      var input = {};
      bookshelfMiddleware.formatFindAllOptions()(input, {}, function() {
        expect(input).to.deep.equal({
          options: {
            sortBy: 'id', sortDirection: 'desc', limit:20, offset:0,
            whereIn: {}
          },
          where: {}
        });
      });
    });

    it('should not override provided parameters', function () {
      var input = {
        options: {
          sortBy:'test',
          sortDirection: 'asc'
        }
      };
      bookshelfMiddleware.formatFindAllOptions()(input, {}, function() {
        expect(input.options.sortBy).to.equal('test');
        expect(input.options.sortDirection).to.equal('asc');
      });
    });

    it('should not convert input if where is a function', function () {
      var input = {
        where: function () {

        }
      };
      bookshelfMiddleware.formatFindAllOptions()(input, {}, function() {
        expect(input.where).to.be.a('function');
      });

    });

    it('should remove array from where value', function () {
      var input = {
        query: {id: [1, 2]}
      };

      bookshelfMiddleware.formatFindAllOptions()(input, {}, function() {
        expect(input.where).to.be.empty;
        expect(input.options.whereIn).to.eql({id: [1,2]});
      });
    });
  });

  describe('#formatFindOptions', function() {
    it('should provide default for find query', function() {
      var input = {};
      bookshelfMiddleware.formatFindOptions()(input, {}, function() {
        expect(input).to.deep.equal({
          options: {},
          where: {id: undefined}
        });
      });
    });

    it('should convert where to an object', function () {
      var input = {
        query: 1
      };
      bookshelfMiddleware.formatFindOptions()(input, {}, function() {
        expect(input.where).to.eql({ id: 1 });
      });

    });

    it('should pick withRelated from where', function () {
      var input = {
        query: {
          withRelated: 'test'
        }
      };
      bookshelfMiddleware.formatFindOptions()(input, {}, function() {
        expect(input.options.withRelated).to.eql('test');
        expect(input.where.withRelated).to.not.exists;
      });
    });
  });

  describe('#formatBackboneModel', function () {
    it('should convert model to JSON', function () {
      var model = new bookshelf.Model({ big_foo: 'bar' });

      var res = {};
      res.body = model;

      bookshelfMiddleware.formatBackboneModel()({}, res, function() {
        expect(res.body).to.eql({ bigFoo: 'bar' });
      });
    });
  });

  describe('#formatBackboneCollection', function () {
    it('should convert collection to JSON', function () {
      var model = new bookshelf.Model({ big_foo: 'bar' });
      var collection = new bookshelf.Collection([model]);

      var res = {};
      res.body = collection;

      bookshelfMiddleware.formatBackboneCollection()({}, res, function() {
        expect(res.body).to.eql([{ bigFoo: 'bar' }]);
      });
    });
  });
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Skip AD on Naver Video
// @namespace    http://elegwance.com
// @version      0.4
// @description  enjoy it
// @author       me@elegwance.com
// @include      *://*.naver.com/*/vod/index.nhn*
// @include      *://tv.naver.com/v/*
// ==/UserScript==

window.addEventListener('load', function() {
    function checkNonSkip() {
        console.log('checkNonSkip');

        if (rmcPlayer === null || !rmcPlayer.isPlaying()) {
            console.log('not init rmcPlayer');
            return;
        }

        var nonskip = document.getElementsByClassName('u_rmc_txt_nonskip');
        if (nonskip.length === 0) {
            return;
        }
        if (nonskip[0].style.display == 'block') {
            rmcPlayer.displayPlayer(player);
            console.log('nonskip video');
            return;
        }

        skipAd();
        clearInterval(intervalId);
    }

    function skipAd() {
        var button = document.getElementsByClassName('u_rmc_btn_skip')[0];

        button.style.display = 'block';
        button.click();
        console.log('skipAd');
    }

    var intervalId = setInterval(checkNonSkip, 500);
}, false);
<commit_msg>update for html5 video<commit_after>// ==UserScript==
// @name         Skip AD on Naver Video
// @namespace    http://elegwance.com
// @version      0.5
// @description  enjoy it
// @author       me@elegwance.com
// @include      *://*.naver.com/*/vod/index.nhn*
// @include      *://tv.naver.com/v/*
// ==/UserScript==

window.addEventListener('load', function() {
    var intervalId;

    function skipHtml5() {
        playerOptions.advertiseInfo = null;
        playerOptions.advertiseUrl = null;
        WrapPlayer.init(playerOptions);
    }

    function skipFlash() {
        if (rmcPlayer === null || !rmcPlayer.isPlaying()) {
            return;
        }

        var nonskip = document.getElementsByClassName('u_rmc_txt_nonskip');
        if (nonskip.length === 0) {
            return;
        }

        if (nonskip[0].style.display == 'block') {
            rmcPlayer.displayPlayer(player);
            return;
        }

        clickSkipButton();
        clearInterval(intervalId);
    }

    function clickSkipButton() {
        var button = document.getElementsByClassName('u_rmc_btn_skip')[0];

        button.style.display = 'block';
        button.click();
    }

    if (typeof WrapPlayer !== 'undefined') {
        // html5 video
        skipHtml5();
    } else {
        // flash video
        intervalId = setInterval(checkNonSkip, 500);
    }
}, false);
<|endoftext|>


<commit_before>var map;

function init() {

    var mercator = new OpenLayers.Projection("EPSG:900913");
    var geographic = new OpenLayers.Projection("EPSG:4326");

    map = new OpenLayers.Map({
        div: "map",
        projection: mercator,
        layers: [
            new OpenLayers.Layer.OSM(),
            new OpenLayers.Layer.PointTrack("Aircraft Tracks", {
                projection: geographic,
                strategies: [new OpenLayers.Strategy.Fixed()],
                protocol: new OpenLayers.Protocol.HTTP({
                    url: "kml-track.kml",
                    format: new OpenLayers.Format.KML({
                        extractTracks: true,
                        extractStyles: true
                    })
                }),
                dataFrom: OpenLayers.Layer.PointTrack.TARGET_NODE,
                styleFrom: OpenLayers.Layer.PointTrack.TARGET_NODE,
                eventListeners: {
                    "beforefeaturesadded": function(e) {
                        // group the tracks by fid and create one track for
                        // every fid
                        var fid, points = [], feature;
                        for (var i=0, len=e.features.length; i<len; i++) {
                            feature = e.features[i];
                            if (feature.fid !== fid || i === len-1) {
                                fid = feature.fid;
                                this.addNodes(points, {silent: true});
                                points = [];
                            }
                            points.push(feature);
                        }
                        return false;
                    }
                }
            })
        ],
        center: new OpenLayers.LonLat(-93.2735, 44.8349).transform(geographic, mercator),
        zoom: 8
    });

    map.addControl(new OpenLayers.Control.LayerSwitcher());

};

<commit_msg>fix the kml-pointtrack.html example<commit_after>var map;

function init() {

    var mercator = new OpenLayers.Projection("EPSG:900913");
    var geographic = new OpenLayers.Projection("EPSG:4326");

    map = new OpenLayers.Map({
        div: "map",
        projection: mercator,
        layers: [
            new OpenLayers.Layer.OSM(),
            new OpenLayers.Layer.PointTrack("Aircraft Tracks", {
                projection: geographic,
                strategies: [new OpenLayers.Strategy.Fixed()],
                protocol: new OpenLayers.Protocol.HTTP({
                    url: "kml-track.kml",
                    format: new OpenLayers.Format.KML({
                        extractTracks: true,
                        extractStyles: true
                    })
                }),
                dataFrom: OpenLayers.Layer.PointTrack.TARGET_NODE,
                styleFrom: OpenLayers.Layer.PointTrack.TARGET_NODE,
                eventListeners: {
                    "beforefeaturesadded": function(e) {
                        // group the tracks by fid and create one track for
                        // every fid
                        var fid, points = [], feature;
                        for (var i=0, len=e.features.length; i<len; i++) {
                            feature = e.features[i];
                            if ((fid && feature.fid !== fid) || i === len-1) {
                                this.addNodes(points, {silent: true});
                                points = [];
                            } else {
                                points.push(feature);
                            }
                            fid = feature.fid;
                        }
                        return false;
                    }
                }
            })
        ],
        center: new OpenLayers.LonLat(-93.2735, 44.8349).transform(geographic, mercator),
        zoom: 8
    });

    map.addControl(new OpenLayers.Control.LayerSwitcher());

};

<|endoftext|>


<commit_before>/*eslint vars-on-top:0*/

'use strict';

var expect = require('chai').expect;
var sinon = require('sinon');
var winston = require('winston');
var TestTransport = require('./mock/test-transport');
var index = require('../index');

describe('index', function () {

  var sandbox;

  beforeEach(function () {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function () {
    sandbox.restore();
  });

  describe('Log constructor', function () {

    it('should return a Log instance', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.be.an.instanceOf(index.Log);
    });

    it('should complain if no transports provided', function () {
      function tryMakeBadLog() {
        return new index.Log();
      }
      expect(tryMakeBadLog).to.throw(/No transports found/);
    });

    it('should have a debug method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('debug');
    });

    it('should have a info method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('info');
    });

    it('should have a notice method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('notice');
    });

    it('should have a warning method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('warning');
    });

    it('should have a error method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('error');
    });

    it('should have a crit method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('crit');
    });

    it('should have a alert method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('alert');
    });

    it('should have a emerg method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('emerg');
    });

    it('should support winston-loggly', function () {
      expect(winston.transports).to.have.property('Loggly');
    });

  });

  describe('log methods', function () {

    var log;
    var spy;

    beforeEach(function () {
      sandbox.stub(winston, 'transports', { TestTransport: TestTransport });

      spy = sinon.spy();
      log = new index.Log({
        transports: [{
          TestTransport: {
            level: 'debug',
            __log: spy
          }
        }],
        sentry: {}
      });
    });

    it('should log a message', function () {
      log.debug('say what?');

      sinon.assert.calledOnce(spy);
      sinon.assert.calledWith(spy, 'debug', 'say what?');
    });

    it('should log error properties', function () {
      log.error('oops', {}, new Error('dangit'));

      var args = spy.args[0];

      expect(args[2]).to.have.property('errMsg', 'dangit');
      expect(args[2]).to.have.property('errStack');
    });

    it('should log error as the second arg', function () {
      log.error('oops', new Error('dangit'));

      var args = spy.args[0];

      expect(args[2]).to.have.property('errMsg', 'dangit');
      expect(args[2]).to.have.property('errStack');
    });

    it('should log metadata', function () {
      log.debug('hi', { name: 'Dan' });

      var args = spy.args[0];

      expect(args[2]).to.have.property('name', 'Dan');
    });

  });

  describe('middleware', function () {

    it('should have middleware on the instance', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.have.property('middleware');
      expect(log.middleware).to.be.a('function');
    });

    it('should produce a middleware function', function () {
      var log = new index.Log({ transports: [], sentry: {} });
      var middleware = log.middleware();

      expect(middleware).to.be.a('function');
      expect(middleware).to.have.length(3);
    });

  });

  describe('_getSentryMeta', function () {

    it('should return null if meta is not defined', function () {
      var result = index._getSentryMeta();

      expect(result).to.be.null;
    });

    it('should add tags property', function () {
      var input = {
        tags: {
          key1: 'value1',
          key2: 'value2'
        }
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('tags');
      expect(result.tags).to.eql({
        key1: 'value1',
        key2: 'value2'
      });
    });

    it('should add fingerprint property', function () {
      var input = {
        fingerprint: 'fingerprintValue'
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('fingerprint', 'fingerprintValue');
    });

    it('should add fingerprint property', function () {
      var input = {
        level: 'error'
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('level', 'error');
    });

    it('should exclude tags, fingerprint, and level in extra', function () {
      var input = {
        level: 'error',
        tags: 'tagsValue',
        fingerprint: 'fingerprintValue',
        key1: 'value1',
        key2: 'value2'
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('extra');
      expect(result.extra).to.not.have.property('level');
      expect(result.extra).to.not.have.property('tags');
      expect(result.extra).to.not.have.property('fingerprint');
    });

    it('should include other property in extra', function () {
      var input = {
        level: 'error',
        tags: 'tagsValue',
        fingerprint: 'fingerprintValue',
        key1: 'value1',
        key2: 'value2'
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('extra');
      expect(result.extra).to.have.property('key1', 'value1');
      expect(result.extra).to.have.property('key2', 'value2');
    });

  });

});
<commit_msg>Fix typo in tests<commit_after>/*eslint vars-on-top:0*/

'use strict';

var expect = require('chai').expect;
var sinon = require('sinon');
var winston = require('winston');
var TestTransport = require('./mock/test-transport');
var index = require('../index');

describe('index', function () {

  var sandbox;

  beforeEach(function () {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function () {
    sandbox.restore();
  });

  describe('Log constructor', function () {

    it('should return a Log instance', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.be.an.instanceOf(index.Log);
    });

    it('should complain if no transports provided', function () {
      function tryMakeBadLog() {
        return new index.Log();
      }
      expect(tryMakeBadLog).to.throw(/No transports found/);
    });

    it('should have a debug method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('debug');
    });

    it('should have a info method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('info');
    });

    it('should have a notice method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('notice');
    });

    it('should have a warning method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('warning');
    });

    it('should have a error method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('error');
    });

    it('should have a crit method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('crit');
    });

    it('should have a alert method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('alert');
    });

    it('should have a emerg method', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.respondTo('emerg');
    });

    it('should support winston-loggly', function () {
      expect(winston.transports).to.have.property('Loggly');
    });

  });

  describe('log methods', function () {

    var log;
    var spy;

    beforeEach(function () {
      sandbox.stub(winston, 'transports', { TestTransport: TestTransport });

      spy = sinon.spy();
      log = new index.Log({
        transports: [{
          TestTransport: {
            level: 'debug',
            __log: spy
          }
        }],
        sentry: {}
      });
    });

    it('should log a message', function () {
      log.debug('say what?');

      sinon.assert.calledOnce(spy);
      sinon.assert.calledWith(spy, 'debug', 'say what?');
    });

    it('should log error properties', function () {
      log.error('oops', {}, new Error('dangit'));

      var args = spy.args[0];

      expect(args[2]).to.have.property('errMsg', 'dangit');
      expect(args[2]).to.have.property('errStack');
    });

    it('should log error as the second arg', function () {
      log.error('oops', new Error('dangit'));

      var args = spy.args[0];

      expect(args[2]).to.have.property('errMsg', 'dangit');
      expect(args[2]).to.have.property('errStack');
    });

    it('should log metadata', function () {
      log.debug('hi', { name: 'Dan' });

      var args = spy.args[0];

      expect(args[2]).to.have.property('name', 'Dan');
    });

  });

  describe('middleware', function () {

    it('should have middleware on the instance', function () {
      var log = new index.Log({ transports: [], sentry: {} });

      expect(log).to.have.property('middleware');
      expect(log.middleware).to.be.a('function');
    });

    it('should produce a middleware function', function () {
      var log = new index.Log({ transports: [], sentry: {} });
      var middleware = log.middleware();

      expect(middleware).to.be.a('function');
      expect(middleware).to.have.length(3);
    });

  });

  describe('_getSentryMeta', function () {

    it('should return null if meta is not defined', function () {
      var result = index._getSentryMeta();

      expect(result).to.be.null;
    });

    it('should add tags property', function () {
      var input = {
        tags: {
          key1: 'value1',
          key2: 'value2'
        }
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('tags');
      expect(result.tags).to.eql({
        key1: 'value1',
        key2: 'value2'
      });
    });

    it('should add fingerprint property', function () {
      var input = {
        fingerprint: 'fingerprintValue'
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('fingerprint', 'fingerprintValue');
    });

    it('should add level property', function () {
      var input = {
        level: 'error'
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('level', 'error');
    });

    it('should exclude tags, fingerprint, and level in extra', function () {
      var input = {
        level: 'error',
        tags: 'tagsValue',
        fingerprint: 'fingerprintValue',
        key1: 'value1',
        key2: 'value2'
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('extra');
      expect(result.extra).to.not.have.property('level');
      expect(result.extra).to.not.have.property('tags');
      expect(result.extra).to.not.have.property('fingerprint');
    });

    it('should include other property in extra', function () {
      var input = {
        level: 'error',
        tags: 'tagsValue',
        fingerprint: 'fingerprintValue',
        key1: 'value1',
        key2: 'value2'
      };

      var result = index._getSentryMeta(input);

      expect(result).to.have.property('extra');
      expect(result.extra).to.have.property('key1', 'value1');
      expect(result.extra).to.have.property('key2', 'value2');
    });

  });

});
<|endoftext|>


<commit_before>require('babel-register');
var request = require('supertest');
var chai = require('chai')
var expect = require ('chai').expect;
var httpMocks = require('node-mocks-http');
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var app = require('./../server/server');
var capitalize = require('./../server/utils/capitalize');
var mkDir = require('./../server/utils/mkDir');
var addStandardFiles = require('./../server/utils/addStandardFiles');
var fileController = require('./../server/utils/fileController');
var zipFunction = require('./../server/utils/zipFunction');

describe('Back-End Tests', function() {
  describe('Creating routes', function() {

    it('GET request to / return status code of 200 & Content-Type of html', function(done) {
      request(app)
        .get('/')
        .expect('Content-Type', /html/)
        .expect(200, done)
    });

  });

  describe('Testing middleware for /submit route', function() {
    //Request and response data objects
    var directory = path.join(__dirname, './../')
    var grandchildObj = {name: 'grandchild', children: [], position: {top: 53, left: 0}, height: 100, width: 100 }
    var childObj = {name: 'child', children: [grandchildObj], position: {top: 53, left: 0}, height: 100, width: 100 }
    var dataObj = {
      name: 'app',
      children: [
        {name: 'compA', children: [childObj], position: {top: 53, left: 0}, height: 100, width: 100},
        {name: 'compB', children: [], position: {top: 53, left: 0}, height: 100, width: 100},
        {name: 'compC', children: [], position: {top: 53, left: 0}, height: 100, width: 100}
      ],
      position: {top: 53, left: 0},
      height: 544,
      width: 833
    }
    var req = httpMocks.createRequest({
      method: 'POST',
      url: '/submit',
      body: {
        projectName: 'MOCHA_TEST_PROJECT',
        main: dataObj,
        server: 'hapi',
        task: 'grunt',
        template: 'es5'
      }
    });
    var res = httpMocks.createResponse();
    var next = function(){
      console.log('next executed');
    }

    // after(function(){
    //   var directory = path.join(__dirname, './../')
    //   console.log('file path: ', `${directory}${request.body.folderName}`)
    //   fs.stat(`${directory}${request.body.folderName}`, function(err, stats) {

    //     console.log('AFTER: ', stats);
    //     console.log('dirname: ', __dirname);
    //     console.log('error: ', err);
    //   });
    // });

    it('Unit test for capitalize middleware function', function(done) {
      capitalize(req, res, next);
      expect(req.body.main.name).to.eq('App');
      expect(req.body.main.children[0].name).to.eq('CompA');
      done();
    });

    it('Unit test for mkDir middleware function', function(done) {
      mkDir(req, res, function(){

        fs.stat(`${directory}${req.body.folderName}`, function(err, stats) {
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/css`, function(err, stats) {
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/server`, function(err, stats) {
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src`, function(err, stats) {
          expect(!!stats).to.eq(true);
          done();
        });
        expect(req.body.uniqueID).to.match(/\w{32}$/);
        expect(req.body.folderName).to.match(/MOCHA_TEST_PROJECT-\w{32}$/);
      });
    });

    it('Unit test for addStandardFiles middleware function', function(done){
      addStandardFiles(req, res, function(){
        fs.stat(`${directory}${req.body.folderName}/index.html`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/package.json`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/gruntfile.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/server/server.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/css/style.css`, function(err, stats){
          expect(!!stats).to.eq(true);
          done();
        });
      });
    });

    it('Unit test for fileController middleware function', function(done){
      fileController(req, res, function(){
        fs.stat(`${directory}${req.body.folderName}/src/CompA.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src/CompB.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src/CompC.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src/Child.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src/Grandchild.js`, function(err, stats){
          expect(!!stats).to.eq(true);
          done();
        });
      });
    });

    it('Unit test for zipFunction middleware function', function(done) {
      zipFunction(req, res, function(){
        fs.stat(`${directory}${req.body.folderName}`, function(err, stats) {
          expect(!!stats).to.eq(false);
        });
        fs.stat(`${directory}zips/${req.body.folderName}.zip`, function(err, stats) {
          expect(!!stats).to.eq(true);
          done();
        });
      });
    });

    it('POST request to /submit returns status code of 200 and name of zip file', function(done) {
      request(app)
        .post('/submit')
        .send(req.body)
        .end(function(err, response) {
          expect(response.status).to.eq(200);
          expect(response.text).to.match(/MOCHA_TEST_PROJECT-\w{32}$/);
          done();
        });
    });
  });
});
<commit_msg>cleaned up test<commit_after>require('babel-register');
var request = require('supertest');
var chai = require('chai')
var expect = require ('chai').expect;
var httpMocks = require('node-mocks-http');
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var app = require('./../server/server');
var capitalize = require('./../server/utils/capitalize');
var mkDir = require('./../server/utils/mkDir');
var addStandardFiles = require('./../server/utils/addStandardFiles');
var fileController = require('./../server/utils/fileController');
var zipFunction = require('./../server/utils/zipFunction');

describe('Back-End Tests', function() {
  describe('Creating routes', function() {

    it('GET request to / return status code of 200 & Content-Type of html', function(done) {
      request(app)
        .get('/')
        .expect('Content-Type', /html/)
        .expect(200, done)
    });

  });

  describe('Testing middleware for /submit route', function() {
    //Request and response data objects
    var directory = path.join(__dirname, './../')
    var grandchildObj = {name: 'grandchild', children: [], position: {top: 53, left: 0}, height: 100, width: 100 }
    var childObj = {name: 'child', children: [grandchildObj], position: {top: 53, left: 0}, height: 100, width: 100 }
    var dataObj = {
      name: 'app',
      children: [
        {name: 'compA', children: [childObj], position: {top: 53, left: 0}, height: 100, width: 100},
        {name: 'compB', children: [], position: {top: 53, left: 0}, height: 100, width: 100},
        {name: 'compC', children: [], position: {top: 53, left: 0}, height: 100, width: 100}
      ],
      position: {top: 53, left: 0},
      height: 544,
      width: 833
    }
    var req = httpMocks.createRequest({
      method: 'POST',
      url: '/submit',
      body: {
        projectName: 'MOCHA_TEST_PROJECT',
        main: dataObj,
        server: 'hapi',
        task: 'grunt',
        template: 'es5'
      }
    });
    var res = httpMocks.createResponse();
    var next = function(){
      console.log('next executed');
    }

    it('Unit test for capitalize middleware function', function(done) {
      capitalize(req, res, next);
      expect(req.body.main.name).to.eq('App');
      expect(req.body.main.children[0].name).to.eq('CompA');
      done();
    });

    it('Unit test for mkDir middleware function', function(done) {
      mkDir(req, res, function(){

        fs.stat(`${directory}${req.body.folderName}`, function(err, stats) {
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/css`, function(err, stats) {
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/server`, function(err, stats) {
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src`, function(err, stats) {
          expect(!!stats).to.eq(true);
          done();
        });
        expect(req.body.uniqueID).to.match(/\w{32}$/);
        expect(req.body.folderName).to.match(/MOCHA_TEST_PROJECT-\w{32}$/);
      });
    });

    it('Unit test for addStandardFiles middleware function', function(done){
      addStandardFiles(req, res, function(){
        fs.stat(`${directory}${req.body.folderName}/index.html`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/package.json`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/gruntfile.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/server/server.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/css/style.css`, function(err, stats){
          expect(!!stats).to.eq(true);
          done();
        });
      });
    });

    it('Unit test for fileController middleware function', function(done){
      fileController(req, res, function(){
        fs.stat(`${directory}${req.body.folderName}/src/CompA.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src/CompB.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src/CompC.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src/Child.js`, function(err, stats){
          expect(!!stats).to.eq(true);
        });
        fs.stat(`${directory}${req.body.folderName}/src/Grandchild.js`, function(err, stats){
          expect(!!stats).to.eq(true);
          done();
        });
      });
    });

    it('Unit test for zipFunction middleware function', function(done) {
      zipFunction(req, res, function(){
        fs.stat(`${directory}${req.body.folderName}`, function(err, stats) {
          expect(!!stats).to.eq(false);
        });
        fs.stat(`${directory}zips/${req.body.folderName}.zip`, function(err, stats) {
          expect(!!stats).to.eq(true);
          done();
        });
      });
    });

    it('POST request to /submit returns status code of 200 and name of zip file', function(done) {
      request(app)
        .post('/submit')
        .send(req.body)
        .end(function(err, response) {
          expect(response.status).to.eq(200);
          expect(response.text).to.match(/MOCHA_TEST_PROJECT-\w{32}$/);
          done();
        });
    });
  });
});
<|endoftext|>


<commit_before>// test suite
module.exports = {
  name: 'basis.js test suite',
  html: __dirname + '/env.html', // base env
  test: [
    //require('./spec/common/classes.js'),
    // require('./spec/core.js'),
    // require('./spec/date.js'),
    // require('./spec/crypt.js'),
    // require('./spec/ua.js'),
    // require('./spec/router.js'),
    // require('./spec/l10n.js'),
    // require('./spec/data.js'),
    // require('./spec/data.object.js'),
    // require('./spec/data.dataset.js'),
    // require('./spec/data.value.js'),
    // require('./spec/data.index.js'),
    // require('./spec/data.vector.js'),
    // require('./spec/entity.js'),
    // require('./spec/dom.wrapper.js'),
    require('./spec/template.js'),
    // require('./spec/ui.js'),
    // require('./spec/net.js'),
    // require('./spec/dom.js'),
    // require('./spec/cssom.js'),
    // require('./spec/layout.js'),
    // require('./spec/utils.info.js'),
    // require('./spec/tracker.js')
  ]
};

// it's a hack to mark basis.js to be updatable
// do it only when global __resources__ available, which using as a implicit
// indicator that we run on basisjs-tools dev-server
if (typeof __resources__ != 'undefined')
{
  var xhr = new XMLHttpRequest();
  xhr.open('HEAD', '../src/basis.js', true);
  xhr.setRequestHeader('X-Basis-Resource', 1);
  xhr.send('');
}
<commit_msg>uncomment wrongly commented tests<commit_after>// test suite
module.exports = {
  name: 'basis.js test suite',
  html: __dirname + '/env.html', // base env
  test: [
    //require('./spec/common/classes.js'),
    require('./spec/core.js'),
    require('./spec/date.js'),
    require('./spec/crypt.js'),
    require('./spec/ua.js'),
    require('./spec/router.js'),
    require('./spec/l10n.js'),
    require('./spec/data.js'),
    require('./spec/data.object.js'),
    require('./spec/data.dataset.js'),
    require('./spec/data.value.js'),
    require('./spec/data.index.js'),
    require('./spec/data.vector.js'),
    require('./spec/entity.js'),
    require('./spec/dom.wrapper.js'),
    require('./spec/template.js'),
    require('./spec/ui.js'),
    require('./spec/net.js'),
    require('./spec/dom.js'),
    require('./spec/cssom.js'),
    require('./spec/layout.js'),
    require('./spec/utils.info.js'),
    require('./spec/tracker.js')
  ]
};

// it's a hack to mark basis.js to be updatable
// do it only when global __resources__ available, which using as a implicit
// indicator that we run on basisjs-tools dev-server
if (typeof __resources__ != 'undefined')
{
  var xhr = new XMLHttpRequest();
  xhr.open('HEAD', '../src/basis.js', true);
  xhr.setRequestHeader('X-Basis-Resource', 1);
  xhr.send('');
}
<|endoftext|>


<commit_before>/**
 * Created by mamun on 8/12/17.
 */
<commit_msg>config updated<commit_after>var assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});
<|endoftext|>


<commit_before>const most = require('most');
const assert = require('chai').assert;
const Scheduler = require('most/lib/scheduler/Scheduler');
require('../lib/extend');

function sink(f, end, err) {
  return {
    event: f||(() => {}),
    end: end||(() => {}),
    error: err||(() => {})
  };
}

describe('Replay', () => {
  it('should exist as a stream operator', () => {
    const stream = most.just(0);
    assert.isFunction(stream.replay);
  });

  it('should behave transparently for the first observer', done => {
    const append = (a, x) => a.concat(x);
    const size = 5;
    const stream = most.iterate(function(x) { return x+1; }, 0).take(size).replay();

    stream.map(() => stream.reduce(append, []))
      .reduce(append, [])
      .then(function(arrayOfPromises) { return Promise.all(arrayOfPromises); })
      .then(function(arrayOfArrays) {
        console.log(arrayOfArrays);
        // all arrays should be identical with replay,
        // but different without it
      });
  });
});
<commit_msg>test(first-observer): assert streams are equal<commit_after>const most = require('most');
const assert = require('chai').assert;
const Scheduler = require('most/lib/scheduler/Scheduler');
require('../lib/extend');

function sink(f, end, err) {
  return {
    event: f||(() => {}),
    end: end||(() => {}),
    error: err||(() => {})
  };
}

describe('Replay', () => {
  it('should exist as a stream operator', () => {
    const stream = most.just(0);
    assert.isFunction(stream.replay);
  });

  it('should behave transparently for the first observer', done => {
    const append = (a, x) => a.concat(x);
    const size = 5;
    const stream = most.iterate(function(x) { return x+1; }, 0).take(size).replay()

    stream.map(() => stream.reduce(append, []))
      .reduce(append, [])
      .then(arrayOfPromises => Promise.all(arrayOfPromises))
      .then(function(arrayOfArrays) {
        arrayOfArrays.reduce((prev, curr) => {
          assert.deepEqual(prev, curr)
          return curr
        })
        done()
      });
  });
});
<|endoftext|>


<commit_before>function test(name, path) {
    describe(name, function() {
        require(path);
    });
}

describe('#dl-module', function(done) {
    this.timeout(2 * 60000);

    // Auth
    // test('@auth/account-manager', './auth/account-manager-test');
    // test('@AUTH/ACCOUNT', './auth/account');
    // test('@AUTH/ROLE', './auth/role');
    // test('@AUTH/API-ENDPOINT', './auth/api-endpoint');

    // test('@ETL/DIM-CATEGORY', './etl/dim-category');
    // test('@ETL/DIM-DIVISION', './etl/dim-division');
    // test('@ETL/DIM-SUPPLIER', './etl/dim-supplier');
    // test('@ETL/DIM-UNIT', './etl/dim-unit');
    // test('@ETL/FACT-PURCHASE-DURATION', './etl/fact-purchase-duration');
    // test('@ETL/FACT-TOTAL-HUTANG', './etl/fact-total-hutang');
    // test('@ETL/FACT-TOTAL-NILAI-PEMBELIAN', './etl/fact-total-nilai-pembelian');
    // test('@ETL/FACT-TOP-TEN-SUPPLIER', './etl/fact-top-ten-supplier');
    // test('@ETL/FACT-PURCHASE-ORDER-COMPARISON', './etl/fact-purchase-order-comparison');
    // test('@ETL/FACT-TIMELINESS-SUPPLIER', './etl/fact-timeliness-supplier');
    // test('@ETL/FACT-PURCHASING', './etl/fact-purchasing');

    // Master
    test('@MASTER/ACCOUNT-BANK', './master/account-bank');
    test('@MASTER/BUDGET', './master/budget');
    test('@MASTER/BUYER', './master/buyer');
    test('@MASTER/CATEGORY', './master/category');
    test('@MASTER/CURRENCY', './master/currency');
    test('@MASTER/DIVISION', './master/division');
    test('@MASTER/LAMP-STANDARD', './master/lamp-standard');
    test('@MASTER/LOT-MACHINE', './master/lot-machine');
    test('@MASTER/MACHINE', './master/machine');
    test('@MASTER/PRODUCT', './master/product');
    test('@MASTER/SUPPLIER', './master/supplier');
    test('@MASTER/THREAD-SPECIFICATION', './master/thread-specification');
    test('@MASTER/UNIT', './master/unit');
    test('@MASTER/UOM', './master/uom');
    test('@MASTER/USTER', './master/uster');
    test('@MASTER/VAT', './master/vat');
    test('@MASTER/YARN-EQUIVALENT-CONVERSION', './master/yarn-equivalent-coversion');
    test('@MASTER/ORDER-TYPE', './master/order-type');
    test('@MASTER/PROCESS-TYPE', './master/process-type');
    test('@MASTER/COLOR-TYPE', './master/color-type');
    test('@MASTER/INSTRUCTION', './master/instruction');

    //Purchasing
    // test('@PURCHASING/PURCHASE REQUEST', './purchasing/purchase-request');
    // test('@PURCHASING/PURCHASE ORDER', './purchasing/purchase-order');
    // test('@PURCHASING/PURCHASE ORDER EXTERNAL', './purchasing/purchase-order-external');
    test('@PURCHASING/DELIVERY ORDER', './purchasing/delivery-order');
    // test('@PURCHASING/UNIT RECEIPT NOTE', './purchasing/unit-receipt-note');
    // test('@PURCHASING/UNIT PAYMENT ORDER', './purchasing/unit-payment-order');
    // test('@PURCHASING/UNIT PAYMENT PRICE CORRECTION', './purchasing/unit-payment-price-correction-note');
    // test('@PURCHASING/UNIT PAYMENT QUANTITY CORRECTION', './purchasing/unit-payment-quantity-correction-note');

    //  test('@purchasing/purchase-order/report', './purchasing/purchase-order/report/report');

    // ok
    // test('@purchasing/delivery-order-manager', './purchasing/delivery-order-manager-test');

    // test('@purchasing/unit-receipt-note', './purchasing/unit-receipt-note-manager-test');
    // test('@purchasing/unit-payment-price-correction-note', './purchasing/unit-payment-price-correction-note-manager-test');
    // test('@purchasing/unit-payment-order', './purchasing/unit-payment-order-test');
    // test('@purchasing/purchase-request/create', './purchasing/purchase-request/create');
    // test('@purchasing/purchase-request/post', './purchasing/purchase-request/post');
    // test('@purchasing/purchase-order/create', './purchasing/purchase-order/create');
    // test('@purchasing/purchase-order/update', './purchasing/purchase-order/update');

    // ok
    // test('@purchasing/delivery-order/create', './purchasing/delivery-order/create');
    // test('@purchasing/unit-receipt-note/create', './purchasing/unit-receipt-note/create');

    // test('@purchasing/unit-payment-order/create', './purchasing/unit-payment-order/create');
    // test('@purchasing/unit-payment-price-correction-note/create', './purchasing/unit-payment-price-correction-note/create');
    // test('@purchasing/unit-payment-quantity-correction-note/create', './purchasing/unit-payment-quantity-correction-note/create');

    // //Production

    // test('@sales/production-order', './sales/production-order/create');

    // test('@production/winding-quality-sampling-manager', './production/spinning/winding/winding-quality-sampling-manager-test');
    // test('@production/winding-production-output-manager', './production/spinning/winding/winding-production-output-manager-test');
    test('@production/daily-operation', './production/finishing-printing/daily-operation');

    //Sales

    //test('@production/production-order', './sales/production-order/create');
});
<commit_msg>fix index<commit_after>function test(name, path) {
    describe(name, function() {
        require(path);
    });
}

describe('#dl-module', function(done) {
    this.timeout(2 * 60000);

    // Auth
    // test('@auth/account-manager', './auth/account-manager-test');
    // test('@AUTH/ACCOUNT', './auth/account');
    // test('@AUTH/ROLE', './auth/role');
    // test('@AUTH/API-ENDPOINT', './auth/api-endpoint');

    // test('@ETL/DIM-CATEGORY', './etl/dim-category');
    // test('@ETL/DIM-DIVISION', './etl/dim-division');
    // test('@ETL/DIM-SUPPLIER', './etl/dim-supplier');
    // test('@ETL/DIM-UNIT', './etl/dim-unit');
    // test('@ETL/FACT-PURCHASE-DURATION', './etl/fact-purchase-duration');
    // test('@ETL/FACT-TOTAL-HUTANG', './etl/fact-total-hutang');
    // test('@ETL/FACT-TOTAL-NILAI-PEMBELIAN', './etl/fact-total-nilai-pembelian');
    // test('@ETL/FACT-TOP-TEN-SUPPLIER', './etl/fact-top-ten-supplier');
    // test('@ETL/FACT-PURCHASE-ORDER-COMPARISON', './etl/fact-purchase-order-comparison');
    // test('@ETL/FACT-TIMELINESS-SUPPLIER', './etl/fact-timeliness-supplier');
    // test('@ETL/FACT-PURCHASING', './etl/fact-purchasing');

    // Master
    test('@MASTER/ACCOUNT-BANK', './master/account-bank');
    test('@MASTER/BUDGET', './master/budget');
    test('@MASTER/BUYER', './master/buyer');
    test('@MASTER/CATEGORY', './master/category');
    test('@MASTER/CURRENCY', './master/currency');
    test('@MASTER/DIVISION', './master/division');
    test('@MASTER/LAMP-STANDARD', './master/lamp-standard');
    test('@MASTER/LOT-MACHINE', './master/lot-machine');
    test('@MASTER/MACHINE', './master/machine');
    test('@MASTER/PRODUCT', './master/product');
    test('@MASTER/SUPPLIER', './master/supplier');
    test('@MASTER/THREAD-SPECIFICATION', './master/thread-specification');
    test('@MASTER/UNIT', './master/unit');
    test('@MASTER/UOM', './master/uom');
    test('@MASTER/USTER', './master/uster');
    test('@MASTER/VAT', './master/vat');
    test('@MASTER/YARN-EQUIVALENT-CONVERSION', './master/yarn-equivalent-coversion');
    test('@MASTER/ORDER-TYPE', './master/order-type');
    test('@MASTER/PROCESS-TYPE', './master/process-type');
    test('@MASTER/COLOR-TYPE', './master/color-type');
    test('@MASTER/INSTRUCTION', './master/instruction');

    //Purchasing
    test('@PURCHASING/PURCHASE REQUEST', './purchasing/purchase-request');
    test('@PURCHASING/PURCHASE ORDER', './purchasing/purchase-order');
    test('@PURCHASING/PURCHASE ORDER EXTERNAL', './purchasing/purchase-order-external');
    test('@PURCHASING/DELIVERY ORDER', './purchasing/delivery-order');
    test('@PURCHASING/UNIT RECEIPT NOTE', './purchasing/unit-receipt-note');
    test('@PURCHASING/UNIT PAYMENT ORDER', './purchasing/unit-payment-order');
    test('@PURCHASING/UNIT PAYMENT PRICE CORRECTION', './purchasing/unit-payment-price-correction-note');
    test('@PURCHASING/UNIT PAYMENT QUANTITY CORRECTION', './purchasing/unit-payment-quantity-correction-note');

     test('@purchasing/purchase-order/report', './purchasing/purchase-order/report/report');

    // ok
    // test('@purchasing/delivery-order-manager', './purchasing/delivery-order-manager-test');

    // test('@purchasing/unit-receipt-note', './purchasing/unit-receipt-note-manager-test');
    // test('@purchasing/unit-payment-price-correction-note', './purchasing/unit-payment-price-correction-note-manager-test');
    // test('@purchasing/unit-payment-order', './purchasing/unit-payment-order-test');
    // test('@purchasing/purchase-request/create', './purchasing/purchase-request/create');
    // test('@purchasing/purchase-request/post', './purchasing/purchase-request/post');
    // test('@purchasing/purchase-order/create', './purchasing/purchase-order/create');
    // test('@purchasing/purchase-order/update', './purchasing/purchase-order/update');

    // ok
    // test('@purchasing/delivery-order/create', './purchasing/delivery-order/create');
    // test('@purchasing/unit-receipt-note/create', './purchasing/unit-receipt-note/create');

    // test('@purchasing/unit-payment-order/create', './purchasing/unit-payment-order/create');
    // test('@purchasing/unit-payment-price-correction-note/create', './purchasing/unit-payment-price-correction-note/create');
    // test('@purchasing/unit-payment-quantity-correction-note/create', './purchasing/unit-payment-quantity-correction-note/create');

    // //Production

    // test('@sales/production-order', './sales/production-order/create');

    // test('@production/winding-quality-sampling-manager', './production/spinning/winding/winding-quality-sampling-manager-test');
    // test('@production/winding-production-output-manager', './production/spinning/winding/winding-production-output-manager-test');
    test('@production/daily-operation', './production/finishing-printing/daily-operation');

    //Sales

    //test('@production/production-order', './sales/production-order/create');
});
<|endoftext|>


<commit_before>frappe.ui.form.ControlDuration = frappe.ui.form.ControlData.extend({
	make_input: function() {
		this._super();
		this.make_picker();
	},

	make_picker: function() {
		this.inputs = [];
		this.set_duration_options();
		this.$picker = $(
			`

`
		);
		this.$wrapper.append(this.$picker);
		this.build_numeric_input('days', !this.duration_options.showDays);
		this.build_numeric_input('hrs', false);
		this.build_numeric_input('mins', false);
		this.build_numeric_input('secs', !this.duration_options.showSeconds);
		this.set_duration_picker();
		this.$picker.hide();
		this.bind_events();
		this.refresh();
	},

	build_numeric_input: function(label, hidden, max) {
		let $duration_input = $(`
			<input class="input-sm duration-input" data-duration="${label}" type="number" min="0" value="0">
		`)

		let $input = $(`<div class="row duration-row"></div>`).prepend($duration_input);

		if (max) {
			$duration_input.attr('max', max);
		}

		this.inputs[label] = $duration_input;

		let $control = $(`

${label}

`
		)

		if (hidden) {
			$control.addClass('hidden');
		}
		$control.prepend($input);
		$control.appendTo(this.$picker.find('.picker-row'));
	},

	set_duration_options() {
		this.duration_options = frappe.meta.get_duration_options(this.df, this.get_doc());
	},

	set_duration_picker() {
		let total_duration = frappe.utils.seconds_to_duration(this.value, this.duration_options);

		if (total_duration.days) {
			this.$picker.find(`[data-duration='days']`).prop('value', total_duration.days);
		}
		if (total_duration.hours) {
			this.$picker.find(`[data-duration='hrs']`).prop('value', total_duration.hours);
		}
		if (total_duration.minutes) {
			this.$picker.find(`[data-duration='mins']`).prop('value', total_duration.minutes);
		}
		if (total_duration.seconds) {
			this.$picker.find(`[data-duration='secs']`).prop('value', total_duration.seconds);
		}
	},

	bind_events: function() {
		let me = this;
		let clicked = false;

		this.$picker.on('change', '.duration-input', () => {
			clicked = false;
			me.set_value(me.duration_to_seconds());
			me.set_focus();
		});

		this.$wrapper.find(".duration-input").mousedown(() => {
			clicked = true;
		});

		this.$input.on("focus", () => {
			this.$picker.show();
		});

		this.$input.on("blur", () => {
			if (clicked) {
				clicked = false;
			} else {
				this.$picker.hide();
			}
		});
	},

	get_value() {
		return cint(this.value);
	},

	refresh_input: function() {
		this._super();
		this.set_duration_picker();
	},

	format_for_input: function(value) {
		return frappe.utils.get_formatted_duration(value, this.duration_options);
	},

	duration_to_seconds() {
		let value = 0;
		if (this.inputs) {
			let total_duration = {
				minutes : parseInt(this.inputs.mins.val()),
				hours : parseInt(this.inputs.hrs.val()),
			};
			if (this.duration_options.showDays) {
				total_duration.days = parseInt(this.inputs.days.val());
			}
			if (this.duration_options.showSeconds) {
				total_duration.seconds = parseInt(this.inputs.secs.val());
			}

			if (total_duration.days) {
				value += total_duration.days * 24 * 60 * 60;
			}
			if (total_duration.hours) {
				value += total_duration.hours * 60 * 60;
			}
			if (total_duration.minutes) {
				value += total_duration.minutes * 60;
			}
			if (total_duration.seconds) {
				value += total_duration.seconds;
			}
		}
		return value;
	}
});<commit_msg>fix: set duration options in refresh_input<commit_after>frappe.ui.form.ControlDuration = frappe.ui.form.ControlData.extend({
	make_input: function() {
		this._super();
		this.make_picker();
	},

	make_picker: function() {
		this.inputs = [];
		this.set_duration_options();
		this.$picker = $(
			`

`
		);
		this.$wrapper.append(this.$picker);
		this.build_numeric_input("days", !this.duration_options.showDays);
		this.build_numeric_input("hrs", false);
		this.build_numeric_input("mins", false);
		this.build_numeric_input("secs", !this.duration_options.showSeconds);
		this.set_duration_picker();
		this.$picker.hide();
		this.bind_events();
		this.refresh();
	},

	build_numeric_input: function(label, hidden, max) {
		let $duration_input = $(`
			<input class="input-sm duration-input" data-duration="${label}" type="number" min="0" value="0">
		`)

		let $input = $(`<div class="row duration-row"></div>`).prepend($duration_input);

		if (max) {
			$duration_input.attr("max", max);
		}

		this.inputs[label] = $duration_input;

		let $control = $(`

${label}

`
		)

		if (hidden) {
			$control.addClass("hidden");
		}
		$control.prepend($input);
		$control.appendTo(this.$picker.find(".picker-row"));
	},

	set_duration_options() {
		this.duration_options = frappe.meta.get_duration_options(this.df, this.get_doc());
	},

	set_duration_picker() {
		let total_duration = frappe.utils.seconds_to_duration(this.value, this.duration_options);

		if (total_duration.days) {
			this.$picker.find(`[data-duration="days"]`).prop("value", total_duration.days);
		}
		if (total_duration.hours) {
			this.$picker.find(`[data-duration="hrs"]`).prop("value", total_duration.hours);
		}
		if (total_duration.minutes) {
			this.$picker.find(`[data-duration="mins"]`).prop("value", total_duration.minutes);
		}
		if (total_duration.seconds) {
			this.$picker.find(`[data-duration="secs"]`).prop("value", total_duration.seconds);
		}
	},

	bind_events: function() {
		let me = this;
		let clicked = false;

		this.$picker.on("change", ".duration-input", () => {
			clicked = false;
			me.set_value(me.duration_to_seconds());
			me.set_focus();
		});

		this.$wrapper.find(".duration-input").mousedown(() => {
			clicked = true;
		});

		this.$input.on("focus", () => {
			this.$picker.show();
		});

		this.$input.on("blur", () => {
			if (clicked) {
				clicked = false;
			} else {
				this.$picker.hide();
			}
		});
	},

	get_value() {
		return cint(this.value);
	},

	refresh_input: function() {
		this._super();
		this.set_duration_options();
		this.set_duration_picker();
	},

	format_for_input: function(value) {
		return frappe.utils.get_formatted_duration(value, this.duration_options);
	},

	duration_to_seconds() {
		let value = 0;
		if (this.inputs) {
			let total_duration = {
				minutes : parseInt(this.inputs.mins.val()),
				hours : parseInt(this.inputs.hrs.val()),
			};
			if (this.duration_options.showDays) {
				total_duration.days = parseInt(this.inputs.days.val());
			}
			if (this.duration_options.showSeconds) {
				total_duration.seconds = parseInt(this.inputs.secs.val());
			}

			if (total_duration.days) {
				value += total_duration.days * 24 * 60 * 60;
			}
			if (total_duration.hours) {
				value += total_duration.hours * 60 * 60;
			}
			if (total_duration.minutes) {
				value += total_duration.minutes * 60;
			}
			if (total_duration.seconds) {
				value += total_duration.seconds;
			}
		}
		return value;
	}
});<|endoftext|>