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

describe('MathUtil', function(){
    describe('average',function(){
       it('should yield expected results', function(){
           var instruments = [1, 2, 3, 4, 5, 6, 7, 8, 9, 25];
           var avg = MathUtil.average(instruments);
           assert.equal(6.48074069840786, avg.deviation);
       })
    });
    describe('RSI', function(){
       it('should youeld expected results', function(){
          var instruments = [44.34,
                  44.09,
                  44.15,
                  43.61,
                  44.33,
                  44.83,
                  45.10,
                  45.42,
                  45.84,
                  46.08,
                  45.89,
                  46.03,
                  45.61,
                  46.28,
                  46.28,
                  46.00,
                  46.03,
                  46.41,
                  46.22,
                  45.64,
                  46.21,
                  46.25,
                  45.71,
                  46.45,
                  45.78,
                  45.35,
                  44.03,
                  44.18,
                  44.22,
                  44.57,
                  43.42,
                  42.66,
                  43.13].reverse(),
              rsi = MathUtil.RSI(instruments, 14);
           assert.equal(Math.round(rsi[0]*100)/100, 37.77);
           assert.equal(Math.round(rsi[1]*100)/100, 33.08);
           assert.equal(Math.round(rsi[2]*100)/100, 37.30);
       });
    });

    describe('average', function(){
       it('should yield expected results', function(){
           var instruments = [86.16,
                   89.09,
                   88.78,
                   90.32,
                   89.07,
                   91.15,
                   89.44,
                   89.18,
                   86.93,
                   87.68,
                   86.96,
                   89.43,
                   89.32,
                   88.72,
                   87.45,
                   87.26,
                   89.50,
                   87.90,
                   89.13,
                   90.70,
                   92.90,
                   92.98,
                   91.80,
                   92.66,
                   92.68,
                   92.30,
                   92.77,
                   92.54,
                   92.95,
                   93.20,
                   91.07,
                   89.83,
                   89.74,
                   90.40,
                   90.74,
                   88.02,
                   88.09,
                   88.84,
                   90.78,
                   90.54,
                   91.39,
                   90.65].reverse(),
               arr = instruments.slice(0,20),
               avg = MathUtil.average(arr);
           assert.equal(Math.round(avg.deviation * 100)/100, 1.55);
       });
    });
    describe('STOCHRSI', function(){
       it('should yield expected results', function(){
          var instruments = [
              54.09,
              59.90,
              58.20,
              59.76,
              52.35,
              52.82,
              56.94,
              57.47,
              55.26,
              57.51,
              54.80,
              51.47,
              56.16,
              58.34,
              56.02,
              60.22,
              56.75,
              57.38,
              50.23,
              57.06,
              61.51,
              63.69,
              66.22,
              69.16,
              70.73,
              67.79,
              68.82,
              62.38,
              67.59,
              67.59
              ].reverse(),
              stochrsi = MathUtil.STOCHRSI(instruments,14);
           assert.equal(71.51115405773173, stochrsi[0]);
           assert.equal(71.51115405773176, stochrsi[1]);
           assert.equal(46.65265157825128, stochrsi[2]);
       });
    });

    describe('SMA',function(){
       it('should yield expected results', function(){
           var instruments = [86.16,
                   89.09,
                   88.78,
                   90.32,
                   89.07,
                   91.15,
                   89.44,
                   89.18,
                   86.93,
                   87.68,
                   86.96,
                   89.43,
                   89.32,
                   88.72,
                   87.45,
                   87.26,
                   89.50,
                   87.90,
                   89.13,
                   90.70,
                   92.90,
                   92.98,
                   91.80,
                   92.66,
                   92.68,
                   92.30,
                   92.77,
                   92.54,
                   92.95,
                   93.20,
                   91.07,
                   89.83,
                   89.74,
                   90.40,
                   90.74,
                   88.02,
                   88.09,
                   88.84,
                   90.78,
                   90.54,
                   91.39,
                   90.65].reverse(),
               sma = MathUtil.SMA(instruments,20);
           assert.equal(Math.round(sma[0] * 100) / 100,91.05);
       });
    });

    describe('BBANDS', function(){
       it('should yield expected results', function(){
          var instruments = [86.16,
              89.09,
              88.78,
              90.32,
              89.07,
              91.15,
              89.44,
              89.18,
              86.93,
              87.68,
              86.96,
              89.43,
              89.32,
              88.72,
              87.45,
              87.26,
              89.50,
              87.90,
              89.13,
              90.70,
              92.90,
              92.98,
              91.80,
              92.66,
              92.68,
              92.30,
              92.77,
              92.54,
              92.95,
              93.20,
              91.07,
              89.83,
              89.74,
              90.40,
              90.74,
              88.02,
              88.09,
              88.84,
              90.78,
              90.54,
              91.39,
              90.65].reverse(),
              bbands = MathUtil.BBANDS(instruments,20);
           assert.equal(Math.round(bbands.middleband[0] * 100) / 100, 91.05);
           assert.equal(Math.round(bbands.lowband[0] * 100) / 100, 87.95);
           assert.equal(Math.round(bbands.highband[0] * 100) / 100,94.15);
       });
    });
});
<commit_msg>correcting floating values for RSI and STOCHRSI to enable build passing<commit_after>var MathUtil = require('../index');
var assert = require('assert');

describe('MathUtil', function(){
    describe('average',function(){
       it('should yield expected results', function(){
           var instruments = [1, 2, 3, 4, 5, 6, 7, 8, 9, 25];
           var avg = MathUtil.average(instruments);
           assert.equal(6.48074069840786, avg.deviation);
       })
    });
    describe('RSI', function(){
       it('should yield expected results', function(){
          var instruments = [44.34,
                  44.09,
                  44.15,
                  43.61,
                  44.33,
                  44.83,
                  45.10,
                  45.42,
                  45.84,
                  46.08,
                  45.89,
                  46.03,
                  45.61,
                  46.28,
                  46.28,
                  46.00,
                  46.03,
                  46.41,
                  46.22,
                  45.64,
                  46.21,
                  46.25,
                  45.71,
                  46.45,
                  45.78,
                  45.35,
                  44.03,
                  44.18,
                  44.22,
                  44.57,
                  43.42,
                  42.66,
                  43.13].reverse(),
              rsi = MathUtil.RSI(instruments, 14);
           assert.equal(Math.round(rsi[0]*100)/100, 37.71);
           assert.equal(Math.round(rsi[1]*100)/100, 32.87);
           assert.equal(Math.round(rsi[2]*100)/100, 37.21);
       });
    });

    describe('average', function(){
       it('should yield expected results', function(){
           var instruments = [86.16,
                   89.09,
                   88.78,
                   90.32,
                   89.07,
                   91.15,
                   89.44,
                   89.18,
                   86.93,
                   87.68,
                   86.96,
                   89.43,
                   89.32,
                   88.72,
                   87.45,
                   87.26,
                   89.50,
                   87.90,
                   89.13,
                   90.70,
                   92.90,
                   92.98,
                   91.80,
                   92.66,
                   92.68,
                   92.30,
                   92.77,
                   92.54,
                   92.95,
                   93.20,
                   91.07,
                   89.83,
                   89.74,
                   90.40,
                   90.74,
                   88.02,
                   88.09,
                   88.84,
                   90.78,
                   90.54,
                   91.39,
                   90.65].reverse(),
               arr = instruments.slice(0,20),
               avg = MathUtil.average(arr);
           assert.equal(Math.round(avg.deviation * 100)/100, 1.55);
       });
    });
    describe('STOCHRSI', function(){
       it('should yield expected results', function(){
          var instruments = [
              54.09,
              59.90,
              58.20,
              59.76,
              52.35,
              52.82,
              56.94,
              57.47,
              55.26,
              57.51,
              54.80,
              51.47,
              56.16,
              58.34,
              56.02,
              60.22,
              56.75,
              57.38,
              50.23,
              57.06,
              61.51,
              63.69,
              66.22,
              69.16,
              70.73,
              67.79,
              68.82,
              62.38,
              67.59,
              67.59
              ].reverse(),
              stochrsi = MathUtil.STOCHRSI(instruments,14);
           assert.equal(71.1924916245241, stochrsi[0]);
           assert.equal(73.4735209177603, stochrsi[1]);
           assert.equal(40.46074791866111, stochrsi[2]);
       });
    });

    describe('SMA',function(){
       it('should yield expected results', function(){
           var instruments = [86.16,
                   89.09,
                   88.78,
                   90.32,
                   89.07,
                   91.15,
                   89.44,
                   89.18,
                   86.93,
                   87.68,
                   86.96,
                   89.43,
                   89.32,
                   88.72,
                   87.45,
                   87.26,
                   89.50,
                   87.90,
                   89.13,
                   90.70,
                   92.90,
                   92.98,
                   91.80,
                   92.66,
                   92.68,
                   92.30,
                   92.77,
                   92.54,
                   92.95,
                   93.20,
                   91.07,
                   89.83,
                   89.74,
                   90.40,
                   90.74,
                   88.02,
                   88.09,
                   88.84,
                   90.78,
                   90.54,
                   91.39,
                   90.65].reverse(),
               sma = MathUtil.SMA(instruments,20);
           assert.equal(Math.round(sma[0] * 100) / 100,91.05);
       });
    });

    describe('BBANDS', function(){
       it('should yield expected results', function(){
          var instruments = [86.16,
              89.09,
              88.78,
              90.32,
              89.07,
              91.15,
              89.44,
              89.18,
              86.93,
              87.68,
              86.96,
              89.43,
              89.32,
              88.72,
              87.45,
              87.26,
              89.50,
              87.90,
              89.13,
              90.70,
              92.90,
              92.98,
              91.80,
              92.66,
              92.68,
              92.30,
              92.77,
              92.54,
              92.95,
              93.20,
              91.07,
              89.83,
              89.74,
              90.40,
              90.74,
              88.02,
              88.09,
              88.84,
              90.78,
              90.54,
              91.39,
              90.65].reverse(),
              bbands = MathUtil.BBANDS(instruments,20);
           assert.equal(Math.round(bbands.middleband[0] * 100) / 100, 91.05);
           assert.equal(Math.round(bbands.lowband[0] * 100) / 100, 87.95);
           assert.equal(Math.round(bbands.highband[0] * 100) / 100,94.15);
       });
    });
});
<|endoftext|>


<commit_before>import settings from './settings'

module.exports = {
  findDistance: (pos1, pos2) => {
    return Math.sqrt(Math.pow(pos2.x - pos1.x, 2) + Math.pow(pos2.y - pos1.y, 2))
  },

  limitPositions: (x,y,r) => {
    x = Math.max(r, Math.min(x, (settings.width - r)));
    y = Math.max(r, Math.min(y, (settings.height - r)));
    return [x,y];
  },

  chooseOne: function(args) {
    args = Array.prototype.slice.call(arguments);
    if(args.length === 1 && typeof Array.isArray(args[0])) {
      return args[0][Math.floor(Math.random() * args[0].length)]
    }
    return args[Math.floor(Math.random() * args.length)];
  },

  randomInt: (limit) => {
    return Math.floor(Math.random() * limit);
  },

  getAvgPosition: (eve) => {
    for(var j = 0; j < eve.bodyParts.length; j++) {
      xPos += eve.bodyParts[j].pos.x;
      yPos += eve.bodyParts[j].pos.y;
    }
    var pos = {
      x:xPos / eve.bodyParts.length,
      y:yPos / eve.bodyParts.length,
    }
    return pos;
  }
}<commit_msg>Add helper function to get average postition of eve<commit_after>import settings from './settings'

module.exports = {
  findDistance: (pos1, pos2) => {
    return Math.sqrt(Math.pow(pos2.x - pos1.x, 2) + Math.pow(pos2.y - pos1.y, 2))
  },

  limitPositions: (x,y,r) => {
    x = Math.max(r, Math.min(x, (settings.width - r)));
    y = Math.max(r, Math.min(y, (settings.height - r)));
    return [x,y];
  },

  chooseOne: function(args) {
    args = Array.prototype.slice.call(arguments);
    if(args.length === 1 && typeof Array.isArray(args[0])) {
      return args[0][Math.floor(Math.random() * args[0].length)]
    }
    return args[Math.floor(Math.random() * args.length)];
  },

  randomInt: (limit) => {
    return Math.floor(Math.random() * limit);
  },

  getAvgPosition: (eve) => {
    var xPos = 0;
    var yPos = 0;
    for(var j = 0; j < eve.bodyParts.length; j++) {
      xPos += eve.bodyParts[j].pos.x;
      yPos += eve.bodyParts[j].pos.y;
    }
    var pos = {
      x:xPos / eve.bodyParts.length,
      y:yPos / eve.bodyParts.length,
    }
    return pos;
  }
}<|endoftext|>


<commit_before>'use strict';
const db = require('../db'),
      uuid = require('uuid');

class Base {
  constructor(properties) {
    Object.assign(this, properties);
  }

  static type() {
    return 'Base';
  }

  static fields() {
    return [];
  }

  static all() {

    const type = this.type();

    return new Promise(function(resolve, reject) {

      let data = [];

      db.query({type: type})
        .on('data', function(d) {
          data.push(d[type]);
        })
        .on('end', function() {
          resolve(data);
        });

    });

  }

  static create(sent) {

    const type = this.type();

    return new Promise(function(resolve, reject) {

      const obj = {type: type};

      sent.id = uuid.v1();
      sent.updated_at = (new Date()).toISOString();
      sent.created_at = sent.updated_at;
      obj[type] = sent;

      db.put(`${type}|${sent.id}`, obj, function(err) {

        if(err) return reject(err);

        resolve(sent);

      });

    });

  }

}

exports = module.exports = Base;
<commit_msg>adds get & replace to base server model class<commit_after>'use strict';
const db = require('../db'),
      uuid = require('uuid');

class Base {
  constructor(properties) {
    Object.assign(this, properties);
  }

  static type() {
    return 'Base';
  }

  static fields() {
    return [];
  }

  static all() {

    const type = this.type();

    return new Promise(function(resolve, reject) {

      let data = [];

      db.query({type: type})
        .on('data', function(d) {
          data.push(d[type]);
        })
        .on('end', function() {
          resolve(data);
        });

    });

  }

  static get(...args) {

    const type = this.type(),
          id_key_name = args.pop();

    return new Promise(function(resolve, reject) {

      let data = null,
          query = {type: type},
          id = {}, key = {}, name = {};

      id[`${type}.id`] = id_key_name;
      key[`${type}.key`] = id_key_name;
      name[`${type}.name`] = id_key_name;
      query['$or'] = [id, key, name];

      db.query(query)
        .once('data', function(d) {
          data = d[type];
        })
        .on('end', function() {
          resolve(data);
        });

    });

  }

  static create(sent) {

    const type = this.type();

    return new Promise(function(resolve, reject) {

      const obj = {type: type};

      sent.id = uuid.v1();
      sent.updated_at = (new Date()).toISOString();
      sent.created_at = sent.updated_at;
      obj[type] = sent;

      db.put(`${type}|${sent.id}`, obj, function(err) {

        if(err) return reject(err);

        resolve(sent);

      });

    });

  }

  static replace(...args) {

    const type = this.type(),
          sent = args.pop(),
          id = args.pop();

    return new Promise(function(resolve, reject) {

      const obj = {type: type};

      sent.updated_at = (new Date()).toISOString();
      obj[type] = sent;

      db.put(`${type}|${sent.id}`, obj, function(err) {

        if(err) return reject(err);

        resolve(sent);

      });

    });

  }

}

exports = module.exports = Base;
<|endoftext|>


<commit_before>'use strict';
module.exports = function(sequelize, DataTypes) {
  var campaign = sequelize.define('campaign', {
    name: DataTypes.STRING,
    fromName: DataTypes.STRING,
    fromEmail: DataTypes.STRING,
    emailSubject: DataTypes.STRING,
    emailBody: DataTypes.TEXT,
    slug: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        campaign.belongsTo(models.user);
        campaign.belongsTo(models.list);
        campaign.hasOne(models.campaignanalytics);
      }
    }
  });
  return campaign;
};
<commit_msg>Fix Campaign relationship with CampaignSubscriber<commit_after>'use strict';
module.exports = function(sequelize, DataTypes) {
  var campaign = sequelize.define('campaign', {
    name: DataTypes.STRING,
    fromName: DataTypes.STRING,
    fromEmail: DataTypes.STRING,
    emailSubject: DataTypes.STRING,
    emailBody: DataTypes.TEXT,
    slug: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        campaign.belongsTo(models.user);
        campaign.belongsTo(models.list);
        campaign.hasMany(models.campaignsubscriber);
        campaign.hasOne(models.campaignanalytics);
      }
    }
  });
  return campaign;
};
<|endoftext|>


<commit_before>//
//   Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

const _ = require('lodash'),
      redis = require('../lib/redis').createClient(),
      notification = require('../lib/notification');

exports.sendSet = function*(userId, sessionId) {
    let settings = (yield redis.hgetall(`settings:${userId}`)) || {};

    _.defaults(settings, {
        activeDesktop: 0
    });

    let user = yield redis.hgetall(`user:${userId}`);

    let command = {
        id: 'SET',
        settings: {
            activeDesktop: parseInt(settings.activeDesktop),
            email: user.email,
            emailConfirmed: user.emailConfirmed === 'true'
        }
    };

    if (sessionId) {
        yield notification.send(userId, sessionId, command);
    } else {
        yield notification.broadcast(userId, command);
    }
};
<commit_msg>Send theme setting during startup<commit_after>//
//   Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

const _ = require('lodash'),
      redis = require('../lib/redis').createClient(),
      notification = require('../lib/notification');

exports.sendSet = function*(userId, sessionId) {
    let settings = (yield redis.hgetall(`settings:${userId}`)) || {};

    _.defaults(settings, {
        activeDesktop: 0,
        theme: 'default'
    });

    let user = yield redis.hgetall(`user:${userId}`);

    let command = {
        id: 'SET',
        settings: {
            activeDesktop: parseInt(settings.activeDesktop),
            theme: settings.theme,
            email: user.email,
            emailConfirmed: user.emailConfirmed === 'true'
        }
    };

    if (sessionId) {
        yield notification.send(userId, sessionId, command);
    } else {
        yield notification.broadcast(userId, command);
    }
};
<|endoftext|>


<commit_before>// nodeunit tests for encdec.js
var encdec = require('../lib/encdec');

console.log("ENCDEC");
console.log(encdec);

exports.group = {
  setUp: function(callback) {
    this.base58 = encdec.create();
    console.log("DEBUG SETUP");
    console.log(this);
    console.log("END DEBUG");
    callback();
  },

  testBase58Encode: function(test) {
    console.log("DEBUG TEST ENCODE");
    console.log(this);
    console.log("END DEBUG");
    test.expect(5);
    test.equals(this.base58.encode(0), '');
    test.equals(this.base58.encode(-1), '');
    test.equals(this.base58.encode(10002343), 'Tgmc');

    // Call encode on the same number to check the cache
    // returns the same result
    test.equals(this.base58.encode(1000), 'if');
    test.equals(this.base58.encode(1000), 'if');

    test.done();
  },

  testBase58Decode: function(test) {
    test.expect(5);

    test.equals(this.base58.decode('Tgmc', 10002343));
    test.equals(this.base58.decode('if'), 1000);

    // Call decode a few times on the same number to check the cache is
    // working correctly
    test.equals(this.base58.decode('if'), 1000);
    test.equals(this.base58.decode('if'), 1000);

    test.equals(this.base58.decode(''), 0);

    test.done();
  },

  tearDown: function(callback) {
    callback();
  }
};<commit_msg>Fixed failing unit test.<commit_after>// nodeunit tests for encdec.js
var encdec = require('../lib/encdec');

exports.group = {
  setUp: function(callback) {
    this.base58 = encdec.create();
    callback();
  },

  testBase58Encode: function(test) {
    test.expect(5);
    test.equals(this.base58.encode(0), '');
    test.equals(this.base58.encode(-1), '');
    test.equals(this.base58.encode(10002343), 'Tgmc');

    // Call encode on the same number to check the cache
    // returns the same result
    test.equals(this.base58.encode(1000), 'if');
    test.equals(this.base58.encode(1000), 'if');

    test.done();
  },

  testBase58Decode: function(test) {
    test.expect(5);

    test.equals(this.base58.decode('Tgmc'), 10002343);
    test.equals(this.base58.decode('if'), 1000);

    // Call decode a few times on the same number to check the cache is
    // working correctly
    test.equals(this.base58.decode('if'), 1000);
    test.equals(this.base58.decode('if'), 1000);

    test.equals(this.base58.decode(''), 0);

    test.done();
  },

  tearDown: function(callback) {
    callback();
  }
};<|endoftext|>


<commit_before>
require.paths.unshift(__dirname + '/../lib/');

Client = require('client');
EventEmitter = require('events').EventEmitter;

sys = require('sys');
assert = require('assert');
BufferList = require(__dirname+'/buffer-list')
buffers = require(__dirname + '/test-buffers');
Connection = require('connection');
var args = require(__dirname + '/cli');

assert.same = function(actual, expected) {
  for(var key in expected) {
    assert.equal(actual[key], expected[key]);
  }
};

assert.emits = function(item, eventName, callback) {
  var called = false;
  var id = setTimeout(function() {
    test("Should have called " + eventName, function() {
      assert.ok(called, "Expected '" + eventName + "' to be called.")
    });
  },20000);

  item.once(eventName, function() {
    called = true;
    clearTimeout(id);
    assert.ok(true);
    if(callback) {
      callback.apply(item, arguments);
    }
  });
};

assert.UTCDate = function(actual, year, month, day, hours, min, sec, milisecond) {
  var actualYear = actual.getUTCFullYear();
  assert.equal(actualYear, year, "expected year " + year + " but got " + actualYear);

  var actualDate = actual.getUTCDate();
  assert.equal(actualDate, day, "expected day " + day + " but got " + actualDate);

  var actualHours = actual.getUTCHours();
  assert.equal(actualHours, hours, "expected hours " + hours + " but got " + actualHours);

  var actualMin = actual.getUTCMinutes();
  assert.equal(actualMin, min, "expected min " + min + " but got " + actualMin);

  var actualSec = actual.getUTCSeconds();
  assert.equal(actualSec, sec, "expected sec " + sec + " but got " + actualSec);

  var actualMili = actual.getUTCMilliseconds();
  assert.equal(actualMili, milisecond, "expected milisecond " + milisecond + " but got " + actualMili);
};

assert.equalBuffers = function(actual, expected) {
  if(actual.length != expected.length) {
    console.log("");
    console.log("actual " + sys.inspect(actual));
    console.log("expect " + sys.inspect(expected));
    console.log("");
    assert.equal(actual.length, expected.length);
  }
  for(var i = 0; i < actual.length; i++) {
    if(actual[i] != expected[i]) {
      console.log(actual);
      console.log(expected);
    }
    assert.equal(actual[i],expected[i]);
  }
};

assert.empty = function(actual) {
  assert.length(actual, 0);
};

assert.length = function(actual, expectedLength) {
  assert.equal(actual.length, expectedLength);
};

var expect = function(callback) {
  var executed = false;
  setTimeout(function() {
    assert.ok(executed, "Expected execution never fired");
  }, 1000)

  return function(err, queryResult) {
    executed = true;
    callback.apply(this, arguments)
  }
}
assert.calls = expect;

['equal', 'length', 'empty', 'strictEqual', 'emits', 'equalBuffers', 'same', 'calls', 'ok'].forEach(function(name) {
  var old = assert[name];
  assert[name] = function() {
    test.assertCount++
    return old.apply(this, arguments);
  };
});

test = function(name, action) {
  try{
    test.testCount ++;
    var result = action();
    if(result === false) {
      test.ignored.push(name);
      process.stdout.write('?');
    }else{
      process.stdout.write('.');
    }
  }catch(e) {
    process.stdout.write('E');
    test.errors.push({name: name, e: e});
  }
};

test.assertCount = test.assertCount || 0;
test.testCount = test.testCount || 0;
test.ignored = test.ignored || [];
test.errors = test.errors || [];
test.start = test.start || new Date();

process.on('exit', function() {
  console.log('');
  var duration = ((new Date() - test.start)/1000);
  console.log(test.testCount + ' tests ' + test.assertCount + ' assertions in ' + duration + ' seconds');
  test.ignored.forEach(function(name) {
    console.log("Ignored: " + name);
  });
  test.errors.forEach(function(error) {
    console.log("Error: " + error.name);
  });
  test.errors.forEach(function(error) {
    throw error.e;
  });
});

module.exports = {
  args: args
};
<commit_msg>make 'assert.calls' short circuit on function call<commit_after>
require.paths.unshift(__dirname + '/../lib/');

Client = require('client');
EventEmitter = require('events').EventEmitter;

sys = require('sys');
assert = require('assert');
BufferList = require(__dirname+'/buffer-list')
buffers = require(__dirname + '/test-buffers');
Connection = require('connection');
var args = require(__dirname + '/cli');

assert.same = function(actual, expected) {
  for(var key in expected) {
    assert.equal(actual[key], expected[key]);
  }
};

assert.emits = function(item, eventName, callback) {
  var called = false;
  var id = setTimeout(function() {
    test("Should have called " + eventName, function() {
      assert.ok(called, "Expected '" + eventName + "' to be called.")
    });
  },20000);

  item.once(eventName, function() {
    called = true;
    clearTimeout(id);
    assert.ok(true);
    if(callback) {
      callback.apply(item, arguments);
    }
  });
};

assert.UTCDate = function(actual, year, month, day, hours, min, sec, milisecond) {
  var actualYear = actual.getUTCFullYear();
  assert.equal(actualYear, year, "expected year " + year + " but got " + actualYear);

  var actualDate = actual.getUTCDate();
  assert.equal(actualDate, day, "expected day " + day + " but got " + actualDate);

  var actualHours = actual.getUTCHours();
  assert.equal(actualHours, hours, "expected hours " + hours + " but got " + actualHours);

  var actualMin = actual.getUTCMinutes();
  assert.equal(actualMin, min, "expected min " + min + " but got " + actualMin);

  var actualSec = actual.getUTCSeconds();
  assert.equal(actualSec, sec, "expected sec " + sec + " but got " + actualSec);

  var actualMili = actual.getUTCMilliseconds();
  assert.equal(actualMili, milisecond, "expected milisecond " + milisecond + " but got " + actualMili);
};

assert.equalBuffers = function(actual, expected) {
  if(actual.length != expected.length) {
    console.log("");
    console.log("actual " + sys.inspect(actual));
    console.log("expect " + sys.inspect(expected));
    console.log("");
    assert.equal(actual.length, expected.length);
  }
  for(var i = 0; i < actual.length; i++) {
    if(actual[i] != expected[i]) {
      console.log(actual);
      console.log(expected);
    }
    assert.equal(actual[i],expected[i]);
  }
};

assert.empty = function(actual) {
  assert.length(actual, 0);
};

assert.length = function(actual, expectedLength) {
  assert.equal(actual.length, expectedLength);
};

var expect = function(callback) {
  var executed = false;
  var id = setTimeout(function() {
    assert.ok(executed, "Expected execution never fired");
  }, 1000)

  return function(err, queryResult) {
    clearTimeout(id);
    assert.ok(true);
    callback.apply(this, arguments)
  }
}
assert.calls = expect;

['equal', 'length', 'empty', 'strictEqual', 'emits', 'equalBuffers', 'same', 'calls', 'ok'].forEach(function(name) {
  var old = assert[name];
  assert[name] = function() {
    test.assertCount++
    return old.apply(this, arguments);
  };
});

test = function(name, action) {
  try{
    test.testCount ++;
    var result = action();
    if(result === false) {
      test.ignored.push(name);
      process.stdout.write('?');
    }else{
      process.stdout.write('.');
    }
  }catch(e) {
    process.stdout.write('E');
    test.errors.push({name: name, e: e});
  }
};

test.assertCount = test.assertCount || 0;
test.testCount = test.testCount || 0;
test.ignored = test.ignored || [];
test.errors = test.errors || [];
test.start = test.start || new Date();

process.on('exit', function() {
  console.log('');
  var duration = ((new Date() - test.start)/1000);
  console.log(test.testCount + ' tests ' + test.assertCount + ' assertions in ' + duration + ' seconds');
  test.ignored.forEach(function(name) {
    console.log("Ignored: " + name);
  });
  test.errors.forEach(function(error) {
    console.log("Error: " + error.name);
  });
  test.errors.forEach(function(error) {
    throw error.e;
  });
});

module.exports = {
  args: args
};
<|endoftext|>


<commit_before>var _ = require('underscore');
var upnp = require("./lib/upnp.js");
var binary = require('binary');
var xml2js = require('xml2js');
var xmlParser = new xml2js.Parser({explicitArray: false});
var async = require('async');
var config = require('../config.js');
var m3u = require('./m3u.js');

var uriTrackProcessor = function(prefix) {
    return function (uri) {
        if (uri.indexOf('http:') === 0) {
            return path.join(prefix, decodeURIComponent(uri.replace(/http:.*\/minimserver\/\*\/[^\/.]*\//, '').replace(/\*/g, '%')));
        } else {
            return uri;
        }
    };
};

var processReadListResponse = function (device, callback) {
    var trackProcessor = uriTrackProcessor(config.musicRoot);
    return function(res) {
        var body = '';
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            body += chunk;
        });
        res.on('end', function () {
            xmlParser.parseString(body, function (err, result) {
                xmlParser.parseString(result['s:Envelope']['s:Body']['u:ReadListResponse'].TrackList, function (err, result) {
                    var tracks = [];
                    if (_.isArray(result.TrackList.Entry)) {
                        _.each(result.TrackList.Entry, function (track) {
                            tracks.push({
                                track: trackProcessor(track.Uri),
                                metadata: track.Metadata
                            });
                        });
                    } else {
                        if (result.TrackList.Entry) {
                            tracks.push({
                                track: trackProcessor(result.TrackList.Entry.Uri),
                                metadata: result.TrackList.Entry.Metadata
                            });
                        }
                    }
                    callback(tracks);
                });
            });
        });
    };
};

var generatePlaylist = function (device, idArray, playlistName, callback) {
    var idArrayString = '';
    _.each(idArray, function (id) {
        idArrayString += (id + ' ');
    });
    var storePlaylist = function (tracks) {
        m3u.write(tracks, playlistName, callback);
    };
    upnp.soapRequest(
        device,
        'Ds/Playlist',
        'urn:av-openhome.org:service:Playlist:1',
        'ReadList',
        '<IdList>'+idArrayString+'</IdList>',
        processReadListResponse(device, storePlaylist)
    );
};

var processPlaylistResponse = function (device, playlistName, callback) {
    return function(res) {
        var body = '';
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            body += chunk;
        });
        res.on('end', function () {
            xmlParser.parseString(body, function (err, result) {
                var buffer = new Buffer(result['s:Envelope']['s:Body']['u:IdArrayResponse'].Array, 'base64');
                var arrayList = [];
                var binaryList = binary.parse(buffer);
                _.each(_.range(buffer.length / 4), function () {
                    arrayList.push(binaryList.word32bu('a').vars.a);
                });
                generatePlaylist(device, arrayList, playlistName, callback);
            });
        });
    };
};

exports.PlaylistManager = function(device) {
    function deleteAll(callback) {
        upnp.soapRequest(
            device,
            'Ds/Playlist',
            'urn:av-openhome.org:service:Playlist:1',
            'DeleteAll',
            '',
            function (res) {
                if (res.statusCode == 200) {
                    callback();
                } else {
                    callback(new Error("Delete failed with status " + res.statusCode));
                }
            }
        );
    };
    function queueTrack(trackDetailsXml, afterId, callback) {
        xmlParser.parseString(trackDetailsXml, function (err, result) {
            var trackUri = result['DIDL-Lite']['item']['res']
                .replace(/&/g, "&");
            var metadata = trackDetailsXml
                .replace(/&/g, "&")
                .replace(/</g, "<")
                .replace(/>/g, ">")
                .replace(/"/g, """);
            upnp.soapRequest(
                device,
                'Ds/Playlist',
                'urn:av-openhome.org:service:Playlist:1',
                'Insert',
                '<AfterId>' + afterId + '</AfterId><Uri>' + trackUri + '</Uri><Metadata>' + metadata + '</Metadata>',
                function (res) {
                    if (res.statusCode == 200) {
                        callback();
                    } else {
                        callback(new Error("Queue failed with " + res.statusCode));
                    }
                }
            );
        });
    };
    this.replacePlaylist = function (playlistName, callback) {
        async.series({
            "delete": function (iterCallback) {
                deleteAll(iterCallback);
            },
            "tracks": function (iterCallback) {
                m3u.read(playlistName, iterCallback);
            }
        }, function (err, results) {
            if (err) {
                callback(err);
            } else {
                async.mapSeries(results.tracks, function (trackXml, iterCallback) {
                    queueTrack(trackXml, 0, iterCallback);
                }, callback);
            }
        });
    };
    this.savePlaylist = function (playlistName, callback) {
        upnp.soapRequest(
            device,
            'Ds/Playlist',
            'urn:av-openhome.org:service:Playlist:1',
            'IdArray',
            '',
            processPlaylistResponse(device, playlistName, callback)
        );
    };
};<commit_msg>Split up callbacks to avoid having to pass playlistname down the chain<commit_after>var _ = require('underscore');
var upnp = require("./lib/upnp.js");
var binary = require('binary');
var xml2js = require('xml2js');
var xmlParser = new xml2js.Parser({explicitArray: false});
var async = require('async');
var config = require('../config.js');
var m3u = require('./m3u.js');

var uriTrackProcessor = function(prefix) {
    return function (uri) {
        if (uri.indexOf('http:') === 0) {
            return path.join(prefix, decodeURIComponent(uri.replace(/http:.*\/minimserver\/\*\/[^\/.]*\//, '').replace(/\*/g, '%')));
        } else {
            return uri;
        }
    };
};

exports.PlaylistManager = function(device) {
    function processReadListResponse(device, callback) {
        var trackProcessor = uriTrackProcessor(config.musicRoot);
        return function(res) {
            var body = '';
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                body += chunk;
            });
            res.once('end', function () {
                xmlParser.parseString(body, function (err, result) {
                    xmlParser.parseString(result['s:Envelope']['s:Body']['u:ReadListResponse'].TrackList, function (err, result) {
                        if (err) {
                            callback(err);
                        } else {
                            var tracks = [];
                            if (_.isArray(result.TrackList.Entry)) {
                                _.each(result.TrackList.Entry, function (track) {
                                    tracks.push({
                                        track: trackProcessor(track.Uri),
                                        metadata: track.Metadata
                                    });
                                });
                            } else {
                                if (result.TrackList.Entry) {
                                    tracks.push({
                                        track: trackProcessor(result.TrackList.Entry.Uri),
                                        metadata: result.TrackList.Entry.Metadata
                                    });
                                }
                            }
                            callback(null, tracks);
                        }
                    });
                });
            });
        };
    };
    function generatePlaylist(idArray, callback) {
        var idArrayString = '';
        _.each(idArray, function (id) {
            idArrayString += (id + ' ');
        });
        upnp.soapRequest(
            device,
            'Ds/Playlist',
            'urn:av-openhome.org:service:Playlist:1',
            'ReadList',
            '<IdList>'+idArrayString+'</IdList>',
            processReadListResponse(device, callback)
        );
    };
    function trackIds(callback) {
        upnp.soapRequest(
            device,
            'Ds/Playlist',
            'urn:av-openhome.org:service:Playlist:1',
            'IdArray',
            '',
            function (res) {
                var body = '';
                res.setEncoding('utf8');
                res.on('data', function (chunk) {
                    body += chunk;
                });
                res.once('end', function () {
                    xmlParser.parseString(body, function (err, result) {
                        var buffer = new Buffer(result['s:Envelope']['s:Body']['u:IdArrayResponse'].Array, 'base64');
                        var arrayList = [];
                        var binaryList = binary.parse(buffer);
                        _.each(_.range(buffer.length / 4), function () {
                            arrayList.push(binaryList.word32bu('a').vars.a);
                        });
                        callback(null, arrayList);
                    });
                });
            }
        );
    };
    function deleteAll(callback) {
        upnp.soapRequest(
            device,
            'Ds/Playlist',
            'urn:av-openhome.org:service:Playlist:1',
            'DeleteAll',
            '',
            function (res) {
                if (res.statusCode == 200) {
                    callback();
                } else {
                    callback(new Error("Delete failed with status " + res.statusCode));
                }
            }
        );
    };
    function queueTrack(trackDetailsXml, afterId, callback) {
        xmlParser.parseString(trackDetailsXml, function (err, result) {
            var trackUri = result['DIDL-Lite']['item']['res']
                .replace(/&/g, "&");
            var metadata = trackDetailsXml
                .replace(/&/g, "&")
                .replace(/</g, "<")
                .replace(/>/g, ">")
                .replace(/"/g, """);
            upnp.soapRequest(
                device,
                'Ds/Playlist',
                'urn:av-openhome.org:service:Playlist:1',
                'Insert',
                '<AfterId>' + afterId + '</AfterId><Uri>' + trackUri + '</Uri><Metadata>' + metadata + '</Metadata>',
                function (res) {
                    if (res.statusCode == 200) {
                        callback();
                    } else {
                        callback(new Error("Queue failed with " + res.statusCode));
                    }
                }
            );
        });
    };
    function queueAllTracks(tracks, callback) {
        async.mapSeries(
            tracks,
            function (trackXml, iterCallback) {
                queueTrack(trackXml, 0, iterCallback);
            },
            callback);
    };
    this.replacePlaylist = function (playlistName, callback) {
        async.series({
            "delete": function (iterCallback) {
                deleteAll(iterCallback);
            },
            "tracks": function (iterCallback) {
                m3u.read(playlistName, iterCallback);
            }
        }, function (err, results) {
            if (err) {
                callback(err);
            }
            if (results && results.tracks) {
                queueAllTracks(results.tracks, callback);
            }
        });
    };
    this.savePlaylist = function (playlistName, callback) {
        trackIds(function(err, trackids) {
            if (err) {
                callback(err);
            }
            if (trackids) {
                generatePlaylist(trackids, function(err, tracks) {
                    if (err) {
                        callback(err);
                    }
                    if (tracks) {
                        m3u.write(tracks, playlistName, callback)
                    }
                });
            }
        });
    };
};<|endoftext|>


<commit_before>'use strict';

var path = require('path');

var arrayify = require('arrayify'),
    autoPlug = require('auto-plug'),
    glob = require('glob'),
    Options = require('defined-options');

var Task = require('./task.js');

var is = Options.is;

function Plug(gulp, options) {
  this.gulp = gulp;
  this.tasks = {};
  this.plugins = {};
  this.setOptions(options);
  [
    ['util', 'gulp-util'],
    ['runSequence', 'run-sequence']
  ]
    .forEach(function(mod) {
      Object.defineProperty(this, mod[0], {
        get: function() {
          return require(mod[1]);
        }
      });
    }.bind(this));
}

Plug.prototype.setOptions = function(options) {
  if (!this.hasOwnProperty('options')) {
    this.options = new Options({
      module: {
        default: module.parent.parent,
        validate: 'object'
      },
      require: {
        default: function() {
          return this.options.module.require;
        },
        validate: 'function'
      },
      cwd: {
        default: function() {
          return path.dirname(this.options.module.filename);
        },
        validate: 'string!empty'
      },
      tasksDir: {
        default: '.gulpplug',
        validate: 'string!empty'
      },
      tasksGlob: {
        default: '**/*.js',
        validate: 'string!empty'
      },
      getTaskName: {
        default: function() {
          return getTasknameFromFilepath;
        },
        validate: 'function'
      }
    });
  }
  options = typeof options === 'object' ? options : {};
  this.options.merge(options);
  if (this.options.validate('module', options.module)) {
    ['require', 'cwd'].forEach(function(rel) {
      if (!this.options.validate(rel, options[rel])) {
        this.options.default(rel);
      }
    }.bind(this));
  }
  return this;
};

Plug.prototype.getTasksFromGlob = function() {
  return glob.sync(this.options.tasksGlob, {
    cwd: path.join(this.options.cwd, this.options.tasksDir)
  }).reduce(function(tasks, filepath) {
    tasks.push([this.getTasknameFromFilepath(filepath), filepath]);
    return tasks;
  }.bind(this), []);
};

Plug.prototype.addTasks = function(tasks) {
  tasks = tasks || this.getTasksFromGlob();
  arrayify(tasks).forEach(function(task) {
    this.addTask.apply(this, arrayify(task));
  }.bind(this));
  return this;
};

Plug.prototype.addTask = function(task, taskFile) {
  var taskModule = task.length && taskFile ?
    this.options.require(path.join(this.options.cwd, this.options.tasksDir, taskFile)) : false;
  task = new Task(task, taskModule);
  if (task.isValid()) {
    this.gulp.task(task.name, task.dependencies, task.fn.bind(this));
    this.tasks[task.name] = task;
  }
  return this;
};

Plug.prototype.addSequence = function(taskName, sequence, taskDescription) {
  if (!is('string!empty', taskName)) return this;
  sequence = arrayify(sequence).filter(function(seq) {
    return is(['string!empty[]', 'string!empty'], seq);
  });
  taskDescription = is('string!empty', taskDescription) ?
    taskDescription : sequence.reduce(function(descr, seq) {
      return descr.concat([Array.isArray(seq) ?
          this.util.colors.gray('[') +
          seq.map(function(seq_) {
            return this.util.colors.cyan(seq_);
          }.bind(this)).join(this.util.colors.gray(' + ')) +
          this.util.colors.gray(']') :
        this.util.colors.cyan(seq)]);
    }.bind(this), []).join(this.util.colors.gray(', '));
  this.addTask({
    name: taskName,
    description: taskDescription,
    fn: function(done) {
      this.runSequence.apply(this.gulp, sequence.concat([done]));
    }
  });
  return this;
};

Plug.prototype.getTasks = function() {
  return Object.keys(this.tasks).reduce(function(tasks, taskName) {
    tasks.push(this.tasks[taskName]);
    return tasks;
  }.bind(this), []);
};

Plug.prototype.addHelpTask = function() {
  this.addTask({
    name: 'help',
    fn: helpTask,
    description: 'display help message'
  });
  if (!this.gulp.hasTask('default')) {
    this.gulp.task('default', ['help']);
  }
  return this;
};

function helpTask(done) {
  var line = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━';
  this.util.log(this.util.colors.gray(line));
  this.util.log(this.util.colors.yellow('Available Tasks:'));
  this.getTasks().filter(function(task) {
    return task.description !== false;
  }).forEach(function(task) {
    this.util.log(
      this.util.colors.cyan(task.name) +
      this.util.colors.gray(' ➜ ') +
      (typeof task.description === 'string' && task.description.length > 0 ?
        this.util.colors.white(task.description) : this.util.colors.gray('(no description)')
      )
    );
  }.bind(this));
  this.util.log(this.util.colors.gray(line));
  done();
}

Plug.prototype.getTasknameFromFilepath = function(filepath) {
  return this.options.getTaskName(filepath);
};

function getTasknameFromFilepath(filepath) {
  return filepath
    .replace(/([^a-z0-9_\.\/-]+)|(\.[^\.]+$)/gi, '')
    .replace(new RegExp(path.sep, 'g'), ':');
}

Plug.prototype.loadPlugins = function(autoPlugOptions) {
  autoPlugOptions = autoPlugOptions || {};
  if (!autoPlugOptions.hasOwnProperty('module')) {
    autoPlugOptions.module = this.options.module;
  }
  autoPlugOptions.prefix = 'gulp';
  this.plugins = autoPlug(autoPlugOptions);
  return this;
};

module.exports = Plug;
<commit_msg>sort tasks by tasknames when displaying help task<commit_after>'use strict';

var path = require('path');

var arrayify = require('arrayify'),
    autoPlug = require('auto-plug'),
    glob = require('glob'),
    Options = require('defined-options');

var Task = require('./task.js');

var is = Options.is;

function Plug(gulp, options) {
  this.gulp = gulp;
  this.tasks = {};
  this.plugins = {};
  this.setOptions(options);
  [
    ['util', 'gulp-util'],
    ['runSequence', 'run-sequence']
  ]
    .forEach(function(mod) {
      Object.defineProperty(this, mod[0], {
        get: function() {
          return require(mod[1]);
        }
      });
    }.bind(this));
}

Plug.prototype.setOptions = function(options) {
  if (!this.hasOwnProperty('options')) {
    this.options = new Options({
      module: {
        default: module.parent.parent,
        validate: 'object'
      },
      require: {
        default: function() {
          return this.options.module.require;
        },
        validate: 'function'
      },
      cwd: {
        default: function() {
          return path.dirname(this.options.module.filename);
        },
        validate: 'string!empty'
      },
      tasksDir: {
        default: '.gulpplug',
        validate: 'string!empty'
      },
      tasksGlob: {
        default: '**/*.js',
        validate: 'string!empty'
      },
      getTaskName: {
        default: function() {
          return getTasknameFromFilepath;
        },
        validate: 'function'
      }
    });
  }
  options = typeof options === 'object' ? options : {};
  this.options.merge(options);
  if (this.options.validate('module', options.module)) {
    ['require', 'cwd'].forEach(function(rel) {
      if (!this.options.validate(rel, options[rel])) {
        this.options.default(rel);
      }
    }.bind(this));
  }
  return this;
};

Plug.prototype.getTasksFromGlob = function() {
  return glob.sync(this.options.tasksGlob, {
    cwd: path.join(this.options.cwd, this.options.tasksDir)
  }).reduce(function(tasks, filepath) {
    tasks.push([this.getTasknameFromFilepath(filepath), filepath]);
    return tasks;
  }.bind(this), []);
};

Plug.prototype.addTasks = function(tasks) {
  tasks = tasks || this.getTasksFromGlob();
  arrayify(tasks).forEach(function(task) {
    this.addTask.apply(this, arrayify(task));
  }.bind(this));
  return this;
};

Plug.prototype.addTask = function(task, taskFile) {
  var taskModule = task.length && taskFile ?
    this.options.require(path.join(this.options.cwd, this.options.tasksDir, taskFile)) : false;
  task = new Task(task, taskModule);
  if (task.isValid()) {
    this.gulp.task(task.name, task.dependencies, task.fn.bind(this));
    this.tasks[task.name] = task;
  }
  return this;
};

Plug.prototype.addSequence = function(taskName, sequence, taskDescription) {
  if (!is('string!empty', taskName)) return this;
  sequence = arrayify(sequence).filter(function(seq) {
    return is(['string!empty[]', 'string!empty'], seq);
  });
  taskDescription = is('string!empty', taskDescription) ?
    taskDescription : sequence.reduce(function(descr, seq) {
      return descr.concat([Array.isArray(seq) ?
          this.util.colors.gray('[') +
          seq.map(function(seq_) {
            return this.util.colors.cyan(seq_);
          }.bind(this)).join(this.util.colors.gray(' + ')) +
          this.util.colors.gray(']') :
        this.util.colors.cyan(seq)]);
    }.bind(this), []).join(this.util.colors.gray(', '));
  this.addTask({
    name: taskName,
    description: taskDescription,
    fn: function(done) {
      this.runSequence.apply(this.gulp, sequence.concat([done]));
    }
  });
  return this;
};

Plug.prototype.getTasks = function() {
  return Object.keys(this.tasks).reduce(function(tasks, taskName) {
    tasks.push(this.tasks[taskName]);
    return tasks;
  }.bind(this), []);
};

Plug.prototype.addHelpTask = function() {
  this.addTask({
    name: 'help',
    fn: helpTask,
    description: 'display help message'
  });
  if (!this.gulp.hasTask('default')) {
    this.gulp.task('default', ['help']);
  }
  return this;
};

function helpTask(done) {
  var line = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━';
  this.util.log(this.util.colors.gray(line));
  this.util.log(this.util.colors.yellow('Available Tasks:'));
  this.getTasks().filter(function(task) {
    return task.description !== false;
  }).sort(function(taskA, taskB) {
    if (taskA.name < taskB.name) return -1;
    if (taskA.name > taskB.name) return 1;
    return 0;
  }).forEach(function(task) {
    this.util.log(
      this.util.colors.cyan(task.name) +
      this.util.colors.gray(' ➜ ') +
      (typeof task.description === 'string' && task.description.length > 0 ?
        this.util.colors.white(task.description) : this.util.colors.gray('(no description)')
      )
    );
  }.bind(this));
  this.util.log(this.util.colors.gray(line));
  done();
}

Plug.prototype.getTasknameFromFilepath = function(filepath) {
  return this.options.getTaskName(filepath);
};

function getTasknameFromFilepath(filepath) {
  return filepath
    .replace(/([^a-z0-9_\.\/-]+)|(\.[^\.]+$)/gi, '')
    .replace(new RegExp(path.sep, 'g'), ':');
}

Plug.prototype.loadPlugins = function(autoPlugOptions) {
  autoPlugOptions = autoPlugOptions || {};
  if (!autoPlugOptions.hasOwnProperty('module')) {
    autoPlugOptions.module = this.options.module;
  }
  autoPlugOptions.prefix = 'gulp';
  this.plugins = autoPlug(autoPlugOptions);
  return this;
};

module.exports = Plug;
<|endoftext|>


<commit_before>const Environment = require('./environment.js')

module.exports = class TestEnvironment extends Environment {
  constructor (data) {
    super()

    if (typeof data === 'string') {
      data = JSON.parse(data)
    }

    let self = this

    if (data.accounts) {
      data.accounts.forEach((account) => {
        self.state.set(new Uint8Array(account[0]).toString(), account[1])
      })
    }

    if (data.address) {
      self.address = new Uint8Array(data.address)
    }

    if (data.origin) {
      self.origin = new Uint8Array(data.origin)
    }

    if (data.caller) {
      self.caller = new Uint8Array(data.caller)
    }

    if (data.callValue) {
      self.callValue = new Uint8Array(data.callValue)
    }

    if (data.callData) {
      self.callData = hexStr2arrayBuf(data.callData)
    }
  }
}

function hexStr2arrayBuf (string) {
  const ab = new ArrayBuffer(string.length / 2)
  const view = new Uint8Array(ab)
  string = [...string]
  let temp = ''
  string.forEach((el, i) => {
    temp += el
    if (i % 2) {
      view[(i + 1) / 2 - 1] = parseInt(temp, 16)
      temp = ''
    }
  })
  return ab
}
<commit_msg>TestEnvironment: include coinbase, gasPrice and gasLimit<commit_after>const Environment = require('./environment.js')

module.exports = class TestEnvironment extends Environment {
  constructor (data) {
    super()

    if (typeof data === 'string') {
      data = JSON.parse(data)
    }

    let self = this

    if (data.accounts) {
      data.accounts.forEach((account) => {
        self.state.set(new Uint8Array(account[0]).toString(), account[1])
      })
    }

    if (data.address) {
      self.address = new Uint8Array(data.address)
    }

    if (data.origin) {
      self.origin = new Uint8Array(data.origin)
    }

    if (data.caller) {
      self.caller = new Uint8Array(data.caller)
    }

    if (data.coinbase) {
      self.coinbase = new Uint8Array(data.coinbase)
    }

    if (data.callValue) {
      self.callValue = new Uint8Array(data.callValue)
    }

    if (data.callData) {
      self.callData = hexStr2arrayBuf(data.callData)
    }

    if (data.gasPrice) {
      self.gasPrice = data.gasPrice
    }

    if (data.gasLimit) {
      self.gasLimit = data.gasLimit
    }
  }
}

function hexStr2arrayBuf (string) {
  const ab = new ArrayBuffer(string.length / 2)
  const view = new Uint8Array(ab)
  string = [...string]
  let temp = ''
  string.forEach((el, i) => {
    temp += el
    if (i % 2) {
      view[(i + 1) / 2 - 1] = parseInt(temp, 16)
      temp = ''
    }
  })
  return ab
}
<|endoftext|>


<commit_before>"use strict";
/*jshint eqnull:true */
/*jshint globalstrict:true */
/*jshint node:true */
/* global describe */
/* global it */

var expect = require('expect.js');
var sinon = require('sinon');
var Promises = require('best-promise');
var qacServices = require('../lib/qac-services.js');
var fs = require('fs-promise');
var request = require('supertest');
var helper=require('../test/test-helper.js');

qacServices.config(helper.testConfig);

describe("qac-services overview",function(){
    function testOverview(groupName) {
        it('make the overview: '+groupName, function(done) {
            var content;
            qacServices.makeOverviewMd(groupName).then(function(contentMd) {
                content = contentMd;
                return fs.readFile(helper.testConfig.repository+'/expected/resume-'+groupName+'.md', {encoding:'utf8'});
            }).then(function(expectedContent) {
                expect(content).to.be(expectedContent);
            }).then(done,done);
        });
    };
    testOverview('sourcetravelers');
    testOverview('codenautas');
    it("obtain html",function(done){
        var htmlContent = "random 123123123123 html content";
        var mock = sinon.stub(qacServices, 'makeOverviewHtml');
        mock.withArgs('sourcetravelers').returns(Promises.resolve(htmlContent));
        var server = createServer();
        var agent=request(server);
        agent
        .get('/sourcetravelers')
        .expect(htmlContent)
        .end(done);
    });
});

var express = require('express');

function createServer(opts, fn) {
    qacServices.config(opts);
    var _serve = qacServices.overviewServe();
    var app = express();
    app.listen();
    app.use(_serve);
    return app;
}
<commit_msg>Elimino test poco claro de overviews<commit_after>"use strict";
/*jshint eqnull:true */
/*jshint globalstrict:true */
/*jshint node:true */
/* global describe */
/* global it */

var expect = require('expect.js');
var sinon = require('sinon');
var Promises = require('best-promise');
var qacServices = require('../lib/qac-services.js');
var fs = require('fs-promise');
var request = require('supertest');
var helper=require('../test/test-helper.js');

qacServices.config(helper.testConfig);

describe("qac-services overview",function(){
    it('make the overview ', function(done) {
        var content;
        qacServices.makeOverviewMd('sourcetravelers').then(function(contentMd) {
            content = contentMd;
            return fs.readFile(helper.testConfig.repository+'/expected/resume-sourcetravelers.md', {encoding:'utf8'});
        }).then(function(expectedContent) {
            expect(content).to.be(expectedContent);
        }).then(done,done);
    });
    it("obtain html",function(done){
        var htmlContent = "random 123123123123 html content";
        var mock = sinon.stub(qacServices, 'makeOverviewHtml');
        mock.withArgs('sourcetravelers').returns(Promises.resolve(htmlContent));
        var server = createServer();
        var agent=request(server);
        agent
        .get('/sourcetravelers')
        .expect(htmlContent)
        .end(done);
    });
});

var express = require('express');

function createServer(opts, fn) {
    qacServices.config(opts);
    var _serve = qacServices.overviewServe();
    var app = express();
    app.listen();
    app.use(_serve);
    return app;
}
<|endoftext|>


<commit_before>'use strict';

var chai = chai || require('chai');
var should = chai.should();
var expect = chai.expect;
var bitcore = bitcore || require('../bitcore');
var fs = require('fs');

var PayPro = bitcore.PayPro;
var Key = bitcore.Key;

describe('PayPro', function() {

  it('should be able to create class', function() {
    should.exist(PayPro);
  });

  describe('#Output', function() {

    it('should not fail', function() {
      var obj = {};
      var output = new PayPro.Output();
      output.$set('amount', 20);
    });

    it('should be able to set the amount of an output', function() {
      var output = new PayPro.Output();
      output.set('amount', 20);
      output.get('amount').toInt().should.equal(20);
    });

  });

  describe('#PaymentDetails', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.PaymentDetails();
    });

    it('should set the memo', function() {
      var obj = {};
      var pd = new PayPro.PaymentDetails();
      pd.set('memo', 'test memo');
      pd.get('memo').should.equal('test memo');
    });

    it('should serialize', function() {
      var obj = {};
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      pd.set('memo', 'test memo');
      var hex = pd.toHex();
      hex.length.should.be.greaterThan(0);
    });

  });

  describe('#PaymentRequest', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.PaymentRequest();
    });

    it('should serialize', function() {
      var obj = {};
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var pr = new PayPro.PaymentRequest();
      pr.set('serialized_payment_details', pdbuf);
      var prhex = pr.toHex();
      prhex.length.should.be.greaterThan(0);
    });

  });

  describe('#Payment', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.Payment();
    });

    it('should serialize', function() {
      var obj = {};
      var p = new PayPro.Payment();
      p.set('memo', 'this is a memo');
      p.get('memo').should.equal('this is a memo');
      var phex = p.toHex();
      phex.length.should.be.greaterThan(0);
    });

  });

  describe('#PaymentACK', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.PaymentACK();
    });

    it('should serialize', function() {
      var obj = {};
      var p = new PayPro.Payment();
      var pa = new PayPro.PaymentACK();
      pa.set('payment', p);
      pa.set('memo', 'this is a memo');
      pa.get('memo').should.equal('this is a memo');
      var pahex = pa.toHex();
      pahex.length.should.be.greaterThan(0);
    });

  });

  describe('#X509Certificates', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.X509Certificates();
    });

    it('should serialize', function() {
      var obj = {};
      var x = new PayPro.X509Certificates();
      var fakecertificate = new Buffer([0, 0, 0, 0]);
      x.set('certificate', [fakecertificate]);
      var xhex = x.toHex();
      xhex.length.should.be.greaterThan(0);
    });

  });

  describe('#isValidSize', function() {

    it('should return true for validly sized payment', function() {
      var paypro = new PayPro();
      paypro.makePayment();
      paypro.set('memo', 'test memo');
      paypro.isValidSize().should.equal(true);
    });

  });

  describe('#getContentType', function() {

    it('should get a content type for payment', function() {
      var paypro = new PayPro();
      paypro.makePayment();
      paypro.set('memo', 'test memo');
      paypro.getContentType().should.equal('application/bitcoin-payment');
    });

  });

  describe('#set', function() {

    it('should set a field', function() {
      var obj = {};
      var paypro = new PayPro();
      paypro.makePaymentDetails();
      paypro.set('memo', 'test memo');
      paypro.get('memo').should.equal('test memo');
    });

  });

  describe('#get', function() {

    it('should get a field', function() {
      var obj = {};
      var paypro = new PayPro();
      paypro.makePaymentDetails();
      paypro.set('memo', 'test memo');
      paypro.get('memo').should.equal('test memo');
    });

  });

  describe('#setObj', function() {

    it('should set properties of paymentdetails', function() {
      var pd = new PayPro.PaymentDetails();
      var paypro = new PayPro();
      paypro.messageType = "PaymentDetails";
      paypro.message = pd;
      paypro.setObj({
        time: 0
      });
      paypro.get('time').should.equal(0);
    });

  });

  describe('#serializeForSig', function() {

    it('should serialize a PaymentRequest and not fail', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();

      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      var buf = paypro.serializeForSig();
      buf.length.should.be.greaterThan(0);
    });

  });

  describe('#serialize', function() {

    it('should serialize', function() {
      var obj = {};
      var paypro = new PayPro();
      paypro.makePaymentDetails();
      paypro.set('memo', 'test memo');
      paypro.set('time', 0);
      var buf = paypro.serialize();
      buf.length.should.be.greaterThan(0);
      Buffer.isBuffer(buf).should.equal(true);
    });

  });

  describe('#deserialize', function() {

    it('should deserialize a serialized message', function() {
      var obj = {};
      var paypro = new PayPro();
      paypro.makePaymentDetails();
      paypro.set('memo', 'test memo');
      paypro.set('time', 0);
      var buf = paypro.serialize();
      var paypro2 = new PayPro();
      paypro2.deserialize(buf, 'PaymentDetails');
      paypro2.get('memo').should.equal('test memo');
      paypro2.get('time').should.equal(0);
    });

  });

  describe('#sign', function() {

    it('should sign a payment request', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'SIN');
      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      paypro.sign(key);
      var sig = paypro.get('signature');
      sig.length.should.be.greaterThan(0);
    });

  });

  describe('#verify', function() {

    it('should verify a signed payment request', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'SIN');
      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      paypro.sign(key);
      var verify = paypro.verify();
      verify.should.equal(true);
    });

  });

  describe('#sinSign', function() {

    it('should sign assuming pki_type is SIN', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'SIN');
      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      var sig = paypro.sinSign(key);
      sig.length.should.be.greaterThan(0);
    });

  });

  describe('#sinVerify', function() {

    it('should verify assuming pki_type is SIN', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'SIN');
      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      paypro.sign(key);
      var verify = paypro.sinVerify();
      verify.should.equal(true);
    });

  });

  var x509sig = new Buffer(0);
  var x509path = __dirname + '/data/x509.der';
  var x509cert = fs.readFileSync(x509path);

  describe('#x509Sign', function() {
    it('should sign assuming pki_type is x509', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'x509+sha256');

      var key = require('fs').readFileSync(__dirname + '/data/x509.der');
      paypro.set('pki_data', key); // contains one or more x509 certs
      //paypro.set('pki_data', x509cert); // contains one or more x509 certs

      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      var sig = paypro.get('signature');
      x509sig = sig;
      sig.length.should.be.greaterThan(0);
    });
  });

  describe('#x509Verify', function() {
    it('should verify assuming pki_type is x509', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'x509+sha256');

      paypro.set('signature', x509sig); // sig buffer
      paypro.set('pki_data', x509cert); // contains one or more x509 certs

      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      paypro.sign(key);
      var verify = paypro.verify();
      verify.should.equal(true);
    });

  });
});
<commit_msg>x509: try different certs/keys/pems.<commit_after>'use strict';

var chai = chai || require('chai');
var should = chai.should();
var expect = chai.expect;
var bitcore = bitcore || require('../bitcore');
var fs = require('fs');

var PayPro = bitcore.PayPro;
var Key = bitcore.Key;

describe('PayPro', function() {

  it('should be able to create class', function() {
    should.exist(PayPro);
  });

  describe('#Output', function() {

    it('should not fail', function() {
      var obj = {};
      var output = new PayPro.Output();
      output.$set('amount', 20);
    });

    it('should be able to set the amount of an output', function() {
      var output = new PayPro.Output();
      output.set('amount', 20);
      output.get('amount').toInt().should.equal(20);
    });

  });

  describe('#PaymentDetails', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.PaymentDetails();
    });

    it('should set the memo', function() {
      var obj = {};
      var pd = new PayPro.PaymentDetails();
      pd.set('memo', 'test memo');
      pd.get('memo').should.equal('test memo');
    });

    it('should serialize', function() {
      var obj = {};
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      pd.set('memo', 'test memo');
      var hex = pd.toHex();
      hex.length.should.be.greaterThan(0);
    });

  });

  describe('#PaymentRequest', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.PaymentRequest();
    });

    it('should serialize', function() {
      var obj = {};
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var pr = new PayPro.PaymentRequest();
      pr.set('serialized_payment_details', pdbuf);
      var prhex = pr.toHex();
      prhex.length.should.be.greaterThan(0);
    });

  });

  describe('#Payment', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.Payment();
    });

    it('should serialize', function() {
      var obj = {};
      var p = new PayPro.Payment();
      p.set('memo', 'this is a memo');
      p.get('memo').should.equal('this is a memo');
      var phex = p.toHex();
      phex.length.should.be.greaterThan(0);
    });

  });

  describe('#PaymentACK', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.PaymentACK();
    });

    it('should serialize', function() {
      var obj = {};
      var p = new PayPro.Payment();
      var pa = new PayPro.PaymentACK();
      pa.set('payment', p);
      pa.set('memo', 'this is a memo');
      pa.get('memo').should.equal('this is a memo');
      var pahex = pa.toHex();
      pahex.length.should.be.greaterThan(0);
    });

  });

  describe('#X509Certificates', function() {

    it('should not fail', function() {
      var obj = {};
      var pd = new PayPro.X509Certificates();
    });

    it('should serialize', function() {
      var obj = {};
      var x = new PayPro.X509Certificates();
      var fakecertificate = new Buffer([0, 0, 0, 0]);
      x.set('certificate', [fakecertificate]);
      var xhex = x.toHex();
      xhex.length.should.be.greaterThan(0);
    });

  });

  describe('#isValidSize', function() {

    it('should return true for validly sized payment', function() {
      var paypro = new PayPro();
      paypro.makePayment();
      paypro.set('memo', 'test memo');
      paypro.isValidSize().should.equal(true);
    });

  });

  describe('#getContentType', function() {

    it('should get a content type for payment', function() {
      var paypro = new PayPro();
      paypro.makePayment();
      paypro.set('memo', 'test memo');
      paypro.getContentType().should.equal('application/bitcoin-payment');
    });

  });

  describe('#set', function() {

    it('should set a field', function() {
      var obj = {};
      var paypro = new PayPro();
      paypro.makePaymentDetails();
      paypro.set('memo', 'test memo');
      paypro.get('memo').should.equal('test memo');
    });

  });

  describe('#get', function() {

    it('should get a field', function() {
      var obj = {};
      var paypro = new PayPro();
      paypro.makePaymentDetails();
      paypro.set('memo', 'test memo');
      paypro.get('memo').should.equal('test memo');
    });

  });

  describe('#setObj', function() {

    it('should set properties of paymentdetails', function() {
      var pd = new PayPro.PaymentDetails();
      var paypro = new PayPro();
      paypro.messageType = "PaymentDetails";
      paypro.message = pd;
      paypro.setObj({
        time: 0
      });
      paypro.get('time').should.equal(0);
    });

  });

  describe('#serializeForSig', function() {

    it('should serialize a PaymentRequest and not fail', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();

      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      var buf = paypro.serializeForSig();
      buf.length.should.be.greaterThan(0);
    });

  });

  describe('#serialize', function() {

    it('should serialize', function() {
      var obj = {};
      var paypro = new PayPro();
      paypro.makePaymentDetails();
      paypro.set('memo', 'test memo');
      paypro.set('time', 0);
      var buf = paypro.serialize();
      buf.length.should.be.greaterThan(0);
      Buffer.isBuffer(buf).should.equal(true);
    });

  });

  describe('#deserialize', function() {

    it('should deserialize a serialized message', function() {
      var obj = {};
      var paypro = new PayPro();
      paypro.makePaymentDetails();
      paypro.set('memo', 'test memo');
      paypro.set('time', 0);
      var buf = paypro.serialize();
      var paypro2 = new PayPro();
      paypro2.deserialize(buf, 'PaymentDetails');
      paypro2.get('memo').should.equal('test memo');
      paypro2.get('time').should.equal(0);
    });

  });

  describe('#sign', function() {

    it('should sign a payment request', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'SIN');
      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      paypro.sign(key);
      var sig = paypro.get('signature');
      sig.length.should.be.greaterThan(0);
    });

  });

  describe('#verify', function() {

    it('should verify a signed payment request', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'SIN');
      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      paypro.sign(key);
      var verify = paypro.verify();
      verify.should.equal(true);
    });

  });

  describe('#sinSign', function() {

    it('should sign assuming pki_type is SIN', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'SIN');
      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      var sig = paypro.sinSign(key);
      sig.length.should.be.greaterThan(0);
    });

  });

  describe('#sinVerify', function() {

    it('should verify assuming pki_type is SIN', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'SIN');
      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      paypro.sign(key);
      var verify = paypro.sinVerify();
      verify.should.equal(true);
    });

  });

  var x509sig = new Buffer(0);
  var x509path = __dirname + '/data/x509.der';
  var x509cert = fs.readFileSync(x509path);

  describe('#x509Sign', function() {
    it('should sign assuming pki_type is x509', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'x509+sha256');

      var key = require('fs').readFileSync(__dirname + '/data/x509.pem');
      paypro.set('pki_data', key); // contains one or more x509 certs
      //paypro.set('pki_data', x509cert); // contains one or more x509 certs

      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      var sig = paypro.get('signature');
      x509sig = sig;
      sig.length.should.be.greaterThan(0);
    });
  });

  describe('#x509Verify', function() {
    it('should verify assuming pki_type is x509', function() {
      var pd = new PayPro.PaymentDetails();
      pd.set('time', 0);
      var pdbuf = pd.toBuffer();
      var paypro = new PayPro();
      paypro.makePaymentRequest();
      paypro.set('serialized_payment_details', pdbuf);
      paypro.set('pki_type', 'x509+sha256');

      paypro.set('signature', x509sig); // sig buffer
      paypro.set('pki_data', x509cert); // contains one or more x509 certs

      var key = new bitcore.Key();
      key.private = bitcore.util.sha256('test key');
      key.regenerateSync();
      paypro.sign(key);
      var verify = paypro.verify();
      verify.should.equal(true);
    });

  });
});
<|endoftext|>