<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Poll = mongoose.model('Poll'),
  Opt = mongoose.model('Opt'),
  Vote = mongoose.model('Vote'),
  Polltag = mongoose.model('Polltag'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Poll
 */
exports.create = function(req, res) {
  var poll = new Poll(req.body);
  poll.user = req.user;

  var tags = req.body.tags;
  var opts = req.body.opts;
  var promises = [];
  poll.save()
    .then(_poll => {
      poll = _poll;
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = _poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        var _opt = new Opt(opt);
        _opt.user = req.user;
        _opt.poll = poll;
        promises.push(_opt.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Poll
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var poll = req.poll ? req.poll.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  poll.isCurrentUserOwner = req.user && poll.user && poll.user._id.toString() === req.user._id.toString();
  poll.canEdit = req.user && req.user.roles && req.user.roles.length && req.user.roles.indexOf('admin') > -1;

  res.jsonp(poll);
};

/**
 * Update a Poll
 */
exports.update = function(req, res) {
  var poll = req.poll;
  poll = _.extend(poll, req.body);
  var tags = req.body.tags || [];
  var opts = req.body.opts || [];
  var promises = [];
  poll.save()
    .then(_poll => {
      return Polltag.remove({ poll: _poll._id });
    }, handleError)
    .then(() => {
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        if (opt._id) {
          promises.push(() => {
            Opt.findById(opt._id).exec((err, _opt) => {
              _opt = _.extend(_opt, opt);
              return _opt.save();
            });
          });
        } else {
          var _opt = new Opt(opt);
          _opt.user = req.user;
          _opt.poll = poll;
          promises.push(_opt.save());
        }
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Poll
 */
exports.delete = function(req, res) {
  var poll = req.poll;
  poll.remove()
    .then(() => {
      return Opt.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      return Vote.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Polls
 */
exports.list = function(req, res) {
  Poll.find().sort('-created').populate('user', 'displayName').exec(function(err, polls) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polls);
    }
  });
};

/**
 * List of Opts in poll
 */
exports.findOpts = function(req, res) {
  Poll.findOpts(req.poll._id).populate('user', 'displayName').exec(function(err, opts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(opts);
    }
  });
};

/**
 * List of Cmts in poll
 */
exports.findCmts = function(req, res) {
  Poll.findCmts(req.poll._id).populate('user', 'displayName profileImageURL').exec(function(err, cmts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(cmts);
    }
  });
};

/**
 * List of Tags in poll
 */
exports.findTags = function(req, res) {
  Poll.findTags(req.poll._id).populate('tag').exec(function(err, polltags) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polltags);
    }
  });
};

/**
 * List of Votes in poll
 */
exports.findVotes = function(req, res) {
  Poll.findVotes(req.poll._id).exec(function(err, votes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(votes);
    }
  });
};

/**
 * Vote in poll of user
 */
exports.findOwnerVote = function(req, res) {
  var condition = {};
  condition.poll = req.poll._id;
  if (req.user) {
    condition.user = req.user._id;
    condition.guest = false;
  } else {
    condition.ip = req.headers["X-Forwarded-For"] || req.headers["x-forwarded-for"] || req.client.remoteAddress;
    condition.guest = true;
  }
  Poll.findOwnerVote(condition).exec(function(err, vote) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(vote);
    }
  });
};

/**
 * Get all info of vote in poll
 */
exports.findVoteopts = function(req, res) {
  var rs = {};
  Poll.findVotes(req.poll._id).exec(function(err, _votes) {
    if (err) {
      handleError(err);
    } else {
      rs.votes = _votes;
      rs.voteopts = [];
      _votes.forEach(vote => {
        Vote.findOpts(vote._id).exec(function(err, opts) {
          if (err) {
            handleError(err);
          } else {
            console.log(opts);
            rs.voteopts.push(opts);
          }
        });
      });
      console.log(rs);
      res.jsonp(rs);
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Poll middleware
 */
exports.pollByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Poll is invalid'
    });
  }

  Poll.findById(id).populate('user', 'displayName profileImageURL').exec(function(err, poll) {
    if (err) {
      return next(err);
    } else if (!poll) {
      return res.status(404).send({
        message: 'No Poll with that identifier has been found'
      });
    }
    req.poll = poll;
    next();
  });
};
<commit_msg>Commited from lenh at 2017年 6月 21日 水曜日 11:09:07<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Poll = mongoose.model('Poll'),
  Opt = mongoose.model('Opt'),
  Vote = mongoose.model('Vote'),
  Voteopt = mongoose.model('Voteopt'),
  Polltag = mongoose.model('Polltag'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Poll
 */
exports.create = function(req, res) {
  var poll = new Poll(req.body);
  poll.user = req.user;

  var tags = req.body.tags;
  var opts = req.body.opts;
  var promises = [];
  poll.save()
    .then(_poll => {
      poll = _poll;
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = _poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        var _opt = new Opt(opt);
        _opt.user = req.user;
        _opt.poll = poll;
        promises.push(_opt.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Poll
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var poll = req.poll ? req.poll.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  poll.isCurrentUserOwner = req.user && poll.user && poll.user._id.toString() === req.user._id.toString();
  poll.canEdit = req.user && req.user.roles && req.user.roles.length && req.user.roles.indexOf('admin') > -1;

  res.jsonp(poll);
};

/**
 * Update a Poll
 */
exports.update = function(req, res) {
  var poll = req.poll;
  poll = _.extend(poll, req.body);
  var tags = req.body.tags || [];
  var opts = req.body.opts || [];
  var promises = [];
  poll.save()
    .then(_poll => {
      return Polltag.remove({ poll: _poll._id });
    }, handleError)
    .then(() => {
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        if (opt._id) {
          promises.push(() => {
            Opt.findById(opt._id).exec((err, _opt) => {
              _opt = _.extend(_opt, opt);
              return _opt.save();
            });
          });
        } else {
          var _opt = new Opt(opt);
          _opt.user = req.user;
          _opt.poll = poll;
          promises.push(_opt.save());
        }
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Poll
 */
exports.delete = function(req, res) {
  var poll = req.poll;
  poll.remove()
    .then(() => {
      return Opt.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      return Vote.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Polls
 */
exports.list = function(req, res) {
  Poll.find().sort('-created').populate('user', 'displayName').exec(function(err, polls) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polls);
    }
  });
};

/**
 * List of Opts in poll
 */
exports.findOpts = function(req, res) {
  Poll.findOpts(req.poll._id).populate('user', 'displayName').exec(function(err, opts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(opts);
    }
  });
};

/**
 * List of Cmts in poll
 */
exports.findCmts = function(req, res) {
  Poll.findCmts(req.poll._id).populate('user', 'displayName profileImageURL').exec(function(err, cmts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(cmts);
    }
  });
};

/**
 * List of Tags in poll
 */
exports.findTags = function(req, res) {
  Poll.findTags(req.poll._id).populate('tag').exec(function(err, polltags) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polltags);
    }
  });
};

/**
 * List of Votes in poll
 */
exports.findVotes = function(req, res) {
  Poll.findVotes(req.poll._id).exec(function(err, votes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(votes);
    }
  });
};

/**
 * Vote in poll of user
 */
exports.findOwnerVote = function(req, res) {
  var condition = {};
  condition.poll = req.poll._id;
  if (req.user) {
    condition.user = req.user._id;
    condition.guest = false;
  } else {
    condition.ip = req.headers["X-Forwarded-For"] || req.headers["x-forwarded-for"] || req.client.remoteAddress;
    condition.guest = true;
  }
  Poll.findOwnerVote(condition).exec(function(err, vote) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(vote);
    }
  });
};

/**
 * Get all info of vote in poll
 */
exports.findVoteopts = function(req, res) {
  var rs = {}, ids;
  Poll.findVotes(req.poll._id).exec(function(err, _votes) {
    if (err) {
      handleError(err);
    } else {
      rs.votes = _votes;
      rs.voteopts = [];
      ids = _.pluck(_votes, '_id')
      Voteopt.find({ vote: { $in: ids } }).exec(function(err, opts) {
        if (err) {
          handleError(err);
        } else {
          rs.voteopts = opts;
          res.jsonp(rs);
        }
      });
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Poll middleware
 */
exports.pollByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Poll is invalid'
    });
  }

  Poll.findById(id).populate('user', 'displayName profileImageURL').exec(function(err, poll) {
    if (err) {
      return next(err);
    } else if (!poll) {
      return res.status(404).send({
        message: 'No Poll with that identifier has been found'
      });
    }
    req.poll = poll;
    next();
  });
};
<|endoftext|>


<commit_before>const { describe, it } = require('mocha')
const assert = require('assert')

const ECPair = require('../src/ecpair')
const Psbt = require('..').Psbt
const NETWORKS = require('../src/networks')

const fixtures = require('./fixtures/psbt')

const upperCaseFirstLetter = str => str.replace(/^./, s => s.toUpperCase())

const b = hex => Buffer.from(hex, 'hex');

const initBuffers = (attr, data) => {
  if ([
    'nonWitnessUtxo',
    'redeemScript',
    'witnessScript'
  ].includes(attr)) {
    data = b(data)
  } else if (attr === 'bip32Derivation') {
    data.masterFingerprint = b(data.masterFingerprint)
    data.pubkey = b(data.pubkey)
  }  else if (attr === 'witnessUtxo') {
    data.script = b(data.script)
  }

  return data
};

describe(`Psbt`, () => {
  describe('BIP174 Test Vectors', () => {
    fixtures.bip174.invalid.forEach(f => {
      it(`Invalid: ${f.description}`, () => {
        assert.throws(() => {
          Psbt.fromBase64(f.psbt)
        }, {message: f.errorMessage})
      })
    })

    fixtures.bip174.valid.forEach(f => {
      it(`Valid: ${f.description}`, () => {
        assert.doesNotThrow(() => {
          Psbt.fromBase64(f.psbt)
        })
      })
    })

    fixtures.bip174.failSignChecks.forEach(f => {
      const keyPair = ECPair.makeRandom()
      it(`Fails Signer checks: ${f.description}`, () => {
        const psbt =  Psbt.fromBase64(f.psbt)
        assert.throws(() => {
          psbt.signInput(f.inputToCheck, keyPair)
        }, {message: f.errorMessage})
      })
    })

    fixtures.bip174.creator.forEach(f => {
      it('Creates expected PSBT', () => {
        const psbt = new Psbt()
        for (const input of f.inputs) {
          psbt.addInput(input)
        }
        for (const output of f.outputs) {
          const script = Buffer.from(output.script, 'hex');
          psbt.addOutput({...output, script})
        }
        assert.strictEqual(psbt.toBase64(), f.result)
      })
    })

    fixtures.bip174.updater.forEach(f => {
      it('Updates PSBT to the expected result', () => {
        const psbt = Psbt.fromBase64(f.psbt)

        for (const inputOrOutput of ['input', 'output']) {
          const fixtureData = f[`${inputOrOutput}Data`]
          if (fixtureData) {
            for (const [i, data] of fixtureData.entries()) {
              const attrs = Object.keys(data)
              for (const attr of attrs) {
                const upperAttr = upperCaseFirstLetter(attr)
                let adder = psbt[`add${upperAttr}To${upperCaseFirstLetter(inputOrOutput)}`]
                if (adder !== undefined) {
                  adder = adder.bind(psbt)
                  const arg = data[attr]
                  if (Array.isArray(arg)) {
                    arg.forEach(a => adder(i, initBuffers(attr, a)))
                  } else {
                    adder(i, initBuffers(attr, arg))
                  }
                }
              }
            }
          }
        }

        assert.strictEqual(psbt.toBase64(), f.result)
      })
    })
  })

  fixtures.bip174.signer.forEach(f => {
    it('Signs PSBT to the expected result', () => {
      const psbt =  Psbt.fromBase64(f.psbt)

      f.keys.forEach(({inputToSign, WIF}) => {
        const keyPair = ECPair.fromWIF(WIF, NETWORKS.testnet);
        psbt.signInput(inputToSign, keyPair);
      })

      assert.strictEqual(psbt.toBase64(), f.result)
    })
  })

  fixtures.bip174.combiner.forEach(f => {
    it('Combines two PSBTs to the expected result', () => {
      const psbts =  f.psbts.map(psbt => Psbt.fromBase64(psbt))

      psbts[0].combine(psbts[1])

      // Produces a different Base64 string due to implemetation specific key-value ordering.
      // That means this test will fail:
      // assert.strictEqual(psbts[0].toBase64(), f.result)
      // However, if we compare the actual PSBT properties we can see they are logically identical:
      assert.deepStrictEqual(psbts[0], Psbt.fromBase64(f.result))
    })
  })

  fixtures.bip174.finalizer.forEach(f => {
    it('Finalizes inputs and gives the expected PSBT', () => {
      const psbt =  Psbt.fromBase64(f.psbt)

      psbt.finalizeAllInputs()

      assert.strictEqual(psbt.toBase64(), f.result)
    })
  })

  fixtures.bip174.extractor.forEach(f => {
    it('Extracts the expected transaction from a PSBT', () => {
      const psbt =  Psbt.fromBase64(f.psbt)

      const transaction = psbt.extractTransaction().toHex()

      assert.strictEqual(transaction, f.transaction)
    })
  })

  describe('signInput', () => {
    fixtures.signInput.checks.forEach(f => {
      it(f.description, () => {
        const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt)
        assert.doesNotThrow(() => {
          psbtThatShouldsign.signInput(
            f.shouldSign.inputToCheck,
            ECPair.fromWIF(f.shouldSign.WIF),
          )
        })

        const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt)
        assert.throws(() => {
          psbtThatShouldThrow.signInput(
            f.shouldThrow.inputToCheck,
            ECPair.fromWIF(f.shouldThrow.WIF),
          )
        }, {message: f.shouldThrow.errorMessage})
      })
    })
  })

  describe('fromTransaction', () => {
    fixtures.fromTransaction.forEach(f => {
      it('Creates the expected PSBT from a transaction buffer', () => {
        const psbt = Psbt.fromTransaction(Buffer.from(f.transaction, 'hex'))
        assert.strictEqual(psbt.toBase64(), f.result)
      })
    })
  })

  describe('setVersion', () => {
    it('Sets the version value of the unsigned transaction', () => {
      const psbt = new Psbt()

      assert.strictEqual(psbt.extractTransaction().version, 2)
      psbt.setVersion(1)
      assert.strictEqual(psbt.extractTransaction().version, 1)
    })
  })
})
<commit_msg>Test setLocktime<commit_after>const { describe, it } = require('mocha')
const assert = require('assert')

const ECPair = require('../src/ecpair')
const Psbt = require('..').Psbt
const NETWORKS = require('../src/networks')

const fixtures = require('./fixtures/psbt')

const upperCaseFirstLetter = str => str.replace(/^./, s => s.toUpperCase())

const b = hex => Buffer.from(hex, 'hex');

const initBuffers = (attr, data) => {
  if ([
    'nonWitnessUtxo',
    'redeemScript',
    'witnessScript'
  ].includes(attr)) {
    data = b(data)
  } else if (attr === 'bip32Derivation') {
    data.masterFingerprint = b(data.masterFingerprint)
    data.pubkey = b(data.pubkey)
  }  else if (attr === 'witnessUtxo') {
    data.script = b(data.script)
  }

  return data
};

describe(`Psbt`, () => {
  describe('BIP174 Test Vectors', () => {
    fixtures.bip174.invalid.forEach(f => {
      it(`Invalid: ${f.description}`, () => {
        assert.throws(() => {
          Psbt.fromBase64(f.psbt)
        }, {message: f.errorMessage})
      })
    })

    fixtures.bip174.valid.forEach(f => {
      it(`Valid: ${f.description}`, () => {
        assert.doesNotThrow(() => {
          Psbt.fromBase64(f.psbt)
        })
      })
    })

    fixtures.bip174.failSignChecks.forEach(f => {
      const keyPair = ECPair.makeRandom()
      it(`Fails Signer checks: ${f.description}`, () => {
        const psbt =  Psbt.fromBase64(f.psbt)
        assert.throws(() => {
          psbt.signInput(f.inputToCheck, keyPair)
        }, {message: f.errorMessage})
      })
    })

    fixtures.bip174.creator.forEach(f => {
      it('Creates expected PSBT', () => {
        const psbt = new Psbt()
        for (const input of f.inputs) {
          psbt.addInput(input)
        }
        for (const output of f.outputs) {
          const script = Buffer.from(output.script, 'hex');
          psbt.addOutput({...output, script})
        }
        assert.strictEqual(psbt.toBase64(), f.result)
      })
    })

    fixtures.bip174.updater.forEach(f => {
      it('Updates PSBT to the expected result', () => {
        const psbt = Psbt.fromBase64(f.psbt)

        for (const inputOrOutput of ['input', 'output']) {
          const fixtureData = f[`${inputOrOutput}Data`]
          if (fixtureData) {
            for (const [i, data] of fixtureData.entries()) {
              const attrs = Object.keys(data)
              for (const attr of attrs) {
                const upperAttr = upperCaseFirstLetter(attr)
                let adder = psbt[`add${upperAttr}To${upperCaseFirstLetter(inputOrOutput)}`]
                if (adder !== undefined) {
                  adder = adder.bind(psbt)
                  const arg = data[attr]
                  if (Array.isArray(arg)) {
                    arg.forEach(a => adder(i, initBuffers(attr, a)))
                  } else {
                    adder(i, initBuffers(attr, arg))
                  }
                }
              }
            }
          }
        }

        assert.strictEqual(psbt.toBase64(), f.result)
      })
    })
  })

  fixtures.bip174.signer.forEach(f => {
    it('Signs PSBT to the expected result', () => {
      const psbt =  Psbt.fromBase64(f.psbt)

      f.keys.forEach(({inputToSign, WIF}) => {
        const keyPair = ECPair.fromWIF(WIF, NETWORKS.testnet);
        psbt.signInput(inputToSign, keyPair);
      })

      assert.strictEqual(psbt.toBase64(), f.result)
    })
  })

  fixtures.bip174.combiner.forEach(f => {
    it('Combines two PSBTs to the expected result', () => {
      const psbts =  f.psbts.map(psbt => Psbt.fromBase64(psbt))

      psbts[0].combine(psbts[1])

      // Produces a different Base64 string due to implemetation specific key-value ordering.
      // That means this test will fail:
      // assert.strictEqual(psbts[0].toBase64(), f.result)
      // However, if we compare the actual PSBT properties we can see they are logically identical:
      assert.deepStrictEqual(psbts[0], Psbt.fromBase64(f.result))
    })
  })

  fixtures.bip174.finalizer.forEach(f => {
    it('Finalizes inputs and gives the expected PSBT', () => {
      const psbt =  Psbt.fromBase64(f.psbt)

      psbt.finalizeAllInputs()

      assert.strictEqual(psbt.toBase64(), f.result)
    })
  })

  fixtures.bip174.extractor.forEach(f => {
    it('Extracts the expected transaction from a PSBT', () => {
      const psbt =  Psbt.fromBase64(f.psbt)

      const transaction = psbt.extractTransaction().toHex()

      assert.strictEqual(transaction, f.transaction)
    })
  })

  describe('signInput', () => {
    fixtures.signInput.checks.forEach(f => {
      it(f.description, () => {
        const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt)
        assert.doesNotThrow(() => {
          psbtThatShouldsign.signInput(
            f.shouldSign.inputToCheck,
            ECPair.fromWIF(f.shouldSign.WIF),
          )
        })

        const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt)
        assert.throws(() => {
          psbtThatShouldThrow.signInput(
            f.shouldThrow.inputToCheck,
            ECPair.fromWIF(f.shouldThrow.WIF),
          )
        }, {message: f.shouldThrow.errorMessage})
      })
    })
  })

  describe('fromTransaction', () => {
    fixtures.fromTransaction.forEach(f => {
      it('Creates the expected PSBT from a transaction buffer', () => {
        const psbt = Psbt.fromTransaction(Buffer.from(f.transaction, 'hex'))
        assert.strictEqual(psbt.toBase64(), f.result)
      })
    })
  })

  describe('setVersion', () => {
    it('Sets the version value of the unsigned transaction', () => {
      const psbt = new Psbt()

      assert.strictEqual(psbt.extractTransaction().version, 2)
      psbt.setVersion(1)
      assert.strictEqual(psbt.extractTransaction().version, 1)
    })
  })

  describe('setLocktime', () => {
    it('Sets the nLockTime value of the unsigned transaction', () => {
      const psbt = new Psbt()

      assert.strictEqual(psbt.extractTransaction().locktime, 0)
      psbt.setLocktime(1)
      assert.strictEqual(psbt.extractTransaction().locktime, 1)
    })
  })
})
<|endoftext|>


<commit_before>
console.log("HERE", test);

test("TinyColor initialization", function() {
	ok ( typeof tinycolor != "undefined", "tinycolor is initialized on the page" );
	ok ( typeof tinycolor("red") == "object", "tinycolor is able to be instantiated." );
});

module("Color translations");

test("Named colors", function() {
	equals (tinycolor("red").toHexCss(), "#ff0000", "red matches hex");
});

test("RGB colors", function() {
	equals (tinycolor("rgb 255 0 0").toHexCss(), "#ff0000", "spaced input");
	equals (tinycolor("rgb(255, 0, 0)").toHexCss(), "#ff0000", "parenthesized input");
	equals (tinycolor("rgb (255, 0, 0)").toHexCss(), "#ff0000", "parenthesized spaced input");
	equals (tinycolor({ r: 255, g: 0, b: 0 }).toHexCss(), "#ff0000", "object input");
});

test("Hex colors", function() {
	equals (tinycolor("ff0000").toHexCss(), "#ff0000", "6 character, no pound");
	equals (tinycolor("#ff0000").toHexCss(), "#ff0000", "6 character, with pound");
	equals (tinycolor("f00").toHexCss(), "#ff0000", "3 character, no pound");
	equals (tinycolor("#f00").toHexCss(), "#ff0000", "3 character, with pound");
});

module("Utilities");

test("Color equality", function() {
	ok (tinycolor.equals("#ff0000", "#ff0000"), "Same hex");
	ok (tinycolor.equals("ff0000", "#ff0000"), "Same hex");
	ok (tinycolor.equals("#f00", "#ff0000"), "Same hex");
	ok (tinycolor.equals("f00", "#ff0000"), "Same hex");
	ok (!tinycolor.equals("#ff0000", "#00ff00"), "Different hex");
});<commit_msg>playing with qunit functions, same instead of equals to allow object compare<commit_after>
console.log("HERE", test);

test("TinyColor initialization", function() {
	ok ( typeof tinycolor != "undefined", "tinycolor is initialized on the page" );
	ok ( typeof tinycolor("red") == "object", "tinycolor is able to be instantiated." );
});

module("Color translations");

test("Named colors", function() {
	equals (tinycolor("red").toHexCss(), "#ff0000", "red matches hex");
});

test("RGB colors", function() {
	equals (tinycolor("rgb 255 0 0").toHexCss(), "#ff0000", "spaced input");
	equals (tinycolor("rgb(255, 0, 0)").toHexCss(), "#ff0000", "parenthesized input");
	equals (tinycolor("rgb (255, 0, 0)").toHexCss(), "#ff0000", "parenthesized spaced input");
	equals (tinycolor({ r: 255, g: 0, b: 0 }).toHexCss(), "#ff0000", "object input");
	same (tinycolor({ r: 255, g: 0, b: 0 }).toRgb(), { r: 255, g: 0, b: 0 }, "object input and compare");
});

test("Hex colors", function() {
	equals (tinycolor("ff0000").toHexCss(), "#ff0000", "6 character, no pound");
	equals (tinycolor("#ff0000").toHexCss(), "#ff0000", "6 character, with pound");
	equals (tinycolor("f00").toHexCss(), "#ff0000", "3 character, no pound");
	equals (tinycolor("#f00").toHexCss(), "#ff0000", "3 character, with pound");
});

module("Utilities");

test("Color equality", function() {
	ok (tinycolor.equals("#ff0000", "#ff0000"), "Same hex");
	ok (tinycolor.equals("ff0000", "#ff0000"), "Same hex");
	ok (tinycolor.equals("#f00", "#ff0000"), "Same hex");
	ok (tinycolor.equals("f00", "#ff0000"), "Same hex");
	ok (!tinycolor.equals("#ff0000", "#00ff00"), "Different hex");
});<|endoftext|>


<commit_before>/* global describe, it, before, after, afterEach */
'use strict'

var _ = require('lodash')
var flic = require('../lib/flic')
var Node = flic.Node
var Bridge = flic.Bridge

var assert = require('assert')

var async = require('async')

describe('Bridge', function () {
  describe('construction', function () {
    var test_bridge

    it('can still be accessed through flic.bridge', function () {
      assert(Bridge === flic.bridge)
    })

    it('should construct normally', function (done) {
      test_bridge = flic.createBridge()
      test_bridge._server.unref()
      assert(test_bridge instanceof Bridge)
      assert.equal(test_bridge._config.port, 8221)
      test_bridge._server.close(done)
    })

    it('should allow setting of the listening port', function (done) {
      test_bridge = flic.createBridge({
        port: 9003
      })
      test_bridge._server.unref()
      assert(test_bridge instanceof Bridge)
      assert.equal(test_bridge._config.port, 9003)
      test_bridge._server.close(done)
    })
  })

  describe('close', function () {
    var b, good_nodes

    good_nodes = []

    before(function (done) {
      done = _.after(2, done)
      b = flic.createBridge()
      b._server.unref()
      good_nodes.push(flic.createNode({
        id: 'node_1',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      }))
      good_nodes.push(flic.createNode({
        id: 'node_2',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      }))
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
    })

    it('should send a close message to all connected nodes', function (done) {
      async.parallel([
        function (cb) {
          good_nodes[0].on('close', function (parting_data) {
            assert.equal(parting_data, 'live long and prosper')
            cb()
          })
        },
        function (cb) {
          good_nodes[1].on('close', function (parting_data) {
            assert.equal(parting_data, 'live long and prosper')
            cb()
          })
        }
      ], done)

      b.close(['live long and prosper'])
    })
  })
})

describe('Node', function () {
  describe('construction', function () {
    var b, b2

    before(function () {
      b2 = flic.createBridge({
        port: 9823
      })
      b = flic.createBridge()
      b._server.unref()
      b2._server.unref()
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
      b2._server && b2._server._handle && b2._server.close()
    })

    it('can still be accessed through flic.node', function () {
      assert(Node === flic.node)
    })

    it('should be backwards compatible with v1.x', function (done) {
      var node = new Node('node_22', function (err) {
        assert.ifError(err)
        done()
      })
      assert(node instanceof Node)
    })

    it('should construct normally and callback when connected to the bridge', function (done) {
      flic.createNode({
        id: 'node_1',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      })
    })

    it('should fail because the name is taken', function (done) {
      flic.createNode({
        id: 'node_1',
        connect_callback: function (err) {
          assert(err)
          done()
        }
      })
    })

    it('should fail because there is no bridge listening on specified port', function (done) {
      this.timeout(3000)

      flic.createNode({
        id: 'muh_dumb_node',
        port: 9999,
        connect_callback: function (err) {
          assert(err)
          done()
        }
      })
    })

    it('should be able to connect normally to a server on a different port', function (done) {
      flic.createNode({
        id: 'node_3',
        port: 9823,
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      })
    })
  })

  describe('tell', function () {
    var b, good_nodes

    good_nodes = []

    before(function (done) {
      done = _.after(2, done)
      b = new Bridge()
      b._server.unref()
      good_nodes.push(flic.createNode({
        id: 'node_1',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      }))
      good_nodes.push(flic.createNode({
        id: 'node_2',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      }))
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
    })

    afterEach(function () {
      good_nodes.forEach(function (n) {
        n.removeAllListeners()
      })
    })

    it('should be able to contact another node', function (done) {
      good_nodes[0].on('test_event', function (param1) {
        assert.equal(param1, 'test_param')
        done()
      })
      good_nodes[1].tell('node_1:test_event', 'test_param')
    })

    it('should be able to contact another node and send callbacks', function (done) {
      good_nodes[0].on('test_event', function (param1, ack) {
        assert.equal(param1, 'test_param')
        ack('my-reply')
      })
      good_nodes[1].tell('node_1:test_event', 'test_param', function (a) {
        assert.equal(a, 'my-reply')
        done()
      })
    })

    it("should fail if the who and what format is not valid ('node_name:remote_event')", function () {
      assert.throws(function () {
        good_nodes[1].tell('node_1-what-the-hell')
      })
      assert.throws(function () {
        good_nodes[1].tell('node_1:too:many:colons')
      })
    })

    it('should fail if the node being told does not exist', function (done) {
      good_nodes[0].tell('me-no-exist:remote_event', function (err) {
        assert.equal(err, 'unknown-node')
        done()
      })
    })
  })

  describe('shout', function () {
    var b, good_nodes

    good_nodes = []

    before(function (done) {
      b = flic.createBridge()
      async.parallel([
        function (cb) {
          good_nodes.push(flic.createNode({id: 'node_1', connect_callback: cb}))
        },
        function (cb) {
          good_nodes.push(flic.createNode({id: 'node_2', connect_callback: cb}))
        },
        function (cb) {
          good_nodes.push(flic.createNode({id: 'node_3', connect_callback: cb}))
        }
      ], function (err) {
        assert.ifError(err)
        done()
      })
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
    })

    afterEach(function () {
      good_nodes.forEach(function (n) {
        n.removeAllListeners()
      })
    })

    it('should send events to all connected nodes', function (done) {
      async.parallel([
        function (done) {
          good_nodes[0].on('shout_eve', function (param1) {
            assert.equal(param1, 'test-param')
            done()
          })
        },
        function (done) {
          good_nodes[1].on('shout_eve', function (param1) {
            assert.equal(param1, 'test-param')
            done()
          })
        }
      ], done)

      good_nodes[2].shout('shout_eve', 'test-param')
    })
  })

  describe('leave', function () {
    var b

    before(function () {
      b = flic.createBridge()
      b._server.unref()
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
    })

    it('should tell the bridge that it is leaving', function (done) {
      var x = flic.createNode({
        id: 'leaving_node',
        connect_callback: function (err) {
          assert.ifError(err)
          x.leave()
          setTimeout(function () {
            assert.ok(!b._sockets.hasOwnProperty('leaving_node'), b._sockets)
            done()
          }, 20)
        }
      })
    })
  })
})
<commit_msg>write a regression test for backwards compat through createNode<commit_after>/* global describe, it, before, after, afterEach */
'use strict'

var _ = require('lodash')
var flic = require('../lib/flic')
var Node = flic.Node
var Bridge = flic.Bridge

var assert = require('assert')

var async = require('async')

describe('Bridge', function () {
  describe('construction', function () {
    var test_bridge

    it('can still be accessed through flic.bridge', function () {
      assert(Bridge === flic.bridge)
    })

    it('should construct normally', function (done) {
      test_bridge = flic.createBridge()
      test_bridge._server.unref()
      assert(test_bridge instanceof Bridge)
      assert.equal(test_bridge._config.port, 8221)
      test_bridge._server.close(done)
    })

    it('should allow setting of the listening port', function (done) {
      test_bridge = flic.createBridge({
        port: 9003
      })
      test_bridge._server.unref()
      assert(test_bridge instanceof Bridge)
      assert.equal(test_bridge._config.port, 9003)
      test_bridge._server.close(done)
    })
  })

  describe('close', function () {
    var b, good_nodes

    good_nodes = []

    before(function (done) {
      done = _.after(2, done)
      b = flic.createBridge()
      b._server.unref()
      good_nodes.push(flic.createNode({
        id: 'node_1',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      }))
      good_nodes.push(flic.createNode({
        id: 'node_2',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      }))
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
    })

    it('should send a close message to all connected nodes', function (done) {
      async.parallel([
        function (cb) {
          good_nodes[0].on('close', function (parting_data) {
            assert.equal(parting_data, 'live long and prosper')
            cb()
          })
        },
        function (cb) {
          good_nodes[1].on('close', function (parting_data) {
            assert.equal(parting_data, 'live long and prosper')
            cb()
          })
        }
      ], done)

      b.close(['live long and prosper'])
    })
  })
})

describe('Node', function () {
  describe('construction', function () {
    var b, b2

    before(function () {
      b2 = flic.createBridge({
        port: 9823
      })
      b = flic.createBridge()
      b._server.unref()
      b2._server.unref()
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
      b2._server && b2._server._handle && b2._server.close()
    })

    it('can still be accessed through flic.node', function () {
      assert(Node === flic.node)
    })

    it('should be backwards compatible with v1.x', function (done) {
      done = _.after(2, done)
      var node = new Node('node_22', function (err) {
        assert.ifError(err)
        done()
      })
      assert(node instanceof Node)

      var node2 = flic.createNode('node_34', function (err) {
        assert.ifError(err)
        done()
      })
      assert(node2 instanceof Node)
    })

    it('should construct normally and callback when connected to the bridge', function (done) {
      flic.createNode({
        id: 'node_1',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      })
    })

    it('should fail because the name is taken', function (done) {
      flic.createNode({
        id: 'node_1',
        connect_callback: function (err) {
          assert(err)
          done()
        }
      })
    })

    it('should fail because there is no bridge listening on specified port', function (done) {
      this.timeout(3000)

      flic.createNode({
        id: 'muh_dumb_node',
        port: 9999,
        connect_callback: function (err) {
          assert(err)
          done()
        }
      })
    })

    it('should be able to connect normally to a server on a different port', function (done) {
      flic.createNode({
        id: 'node_3',
        port: 9823,
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      })
    })
  })

  describe('tell', function () {
    var b, good_nodes

    good_nodes = []

    before(function (done) {
      done = _.after(2, done)
      b = new Bridge()
      b._server.unref()
      good_nodes.push(flic.createNode({
        id: 'node_1',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      }))
      good_nodes.push(flic.createNode({
        id: 'node_2',
        connect_callback: function (err) {
          assert.ifError(err)
          done()
        }
      }))
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
    })

    afterEach(function () {
      good_nodes.forEach(function (n) {
        n.removeAllListeners()
      })
    })

    it('should be able to contact another node', function (done) {
      good_nodes[0].on('test_event', function (param1) {
        assert.equal(param1, 'test_param')
        done()
      })
      good_nodes[1].tell('node_1:test_event', 'test_param')
    })

    it('should be able to contact another node and send callbacks', function (done) {
      good_nodes[0].on('test_event', function (param1, ack) {
        assert.equal(param1, 'test_param')
        ack('my-reply')
      })
      good_nodes[1].tell('node_1:test_event', 'test_param', function (a) {
        assert.equal(a, 'my-reply')
        done()
      })
    })

    it("should fail if the who and what format is not valid ('node_name:remote_event')", function () {
      assert.throws(function () {
        good_nodes[1].tell('node_1-what-the-hell')
      })
      assert.throws(function () {
        good_nodes[1].tell('node_1:too:many:colons')
      })
    })

    it('should fail if the node being told does not exist', function (done) {
      good_nodes[0].tell('me-no-exist:remote_event', function (err) {
        assert.equal(err, 'unknown-node')
        done()
      })
    })
  })

  describe('shout', function () {
    var b, good_nodes

    good_nodes = []

    before(function (done) {
      b = flic.createBridge()
      async.parallel([
        function (cb) {
          good_nodes.push(flic.createNode({id: 'node_1', connect_callback: cb}))
        },
        function (cb) {
          good_nodes.push(flic.createNode({id: 'node_2', connect_callback: cb}))
        },
        function (cb) {
          good_nodes.push(flic.createNode({id: 'node_3', connect_callback: cb}))
        }
      ], function (err) {
        assert.ifError(err)
        done()
      })
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
    })

    afterEach(function () {
      good_nodes.forEach(function (n) {
        n.removeAllListeners()
      })
    })

    it('should send events to all connected nodes', function (done) {
      async.parallel([
        function (done) {
          good_nodes[0].on('shout_eve', function (param1) {
            assert.equal(param1, 'test-param')
            done()
          })
        },
        function (done) {
          good_nodes[1].on('shout_eve', function (param1) {
            assert.equal(param1, 'test-param')
            done()
          })
        }
      ], done)

      good_nodes[2].shout('shout_eve', 'test-param')
    })
  })

  describe('leave', function () {
    var b

    before(function () {
      b = flic.createBridge()
      b._server.unref()
    })

    after(function () {
      b._server && b._server._handle && b._server.close()
    })

    it('should tell the bridge that it is leaving', function (done) {
      var x = flic.createNode({
        id: 'leaving_node',
        connect_callback: function (err) {
          assert.ifError(err)
          x.leave()
          setTimeout(function () {
            assert.ok(!b._sockets.hasOwnProperty('leaving_node'), b._sockets)
            done()
          }, 20)
        }
      })
    })
  })
})
<|endoftext|>


<commit_before>/*
 * JavaScript Canvas to Blob Test
 * https://github.com/blueimp/JavaScript-Canvas-to-Blob
 *
 * Copyright 2012, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * https://opensource.org/licenses/MIT
 */

/* global describe, it, chai, dataURLtoBlob */

;(function () {
  'use strict'

  var expect = chai.expect
  var canvasToBlob = function (canvas, callback, type, quality) {
    setTimeout(function () {
      callback(dataURLtoBlob(canvas.toDataURL(type, quality)))
    })
  }

  // 80x60px GIF image (color black, base64 data):
  var b64Data =
    'R0lGODdhUAA8AIABAAAAAP///ywAAAAAUAA8AAACS4SPqcvtD6' +
    'OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofE' +
    'ovGITCqXzKbzCY1Kp9Sq9YrNarfcrvcLDovH5PKsAAA7'
  var imageUrl = 'data:image/gif;base64,' + b64Data
  var blob = dataURLtoBlob(imageUrl)

  describe('canvas.toBlob', function () {
    it('Converts a canvas element to a blob and passes it to the callback function', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(canvas, function (newBlob) {
            expect(newBlob).to.be.a.instanceOf(Blob)
            done()
          })
        },
        { canvas: true }
      )
    })

    it('Converts a canvas element to a PNG blob', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(
            canvas,
            function (newBlob) {
              expect(newBlob.type).to.equal('image/png')
              done()
            },
            'image/png'
          )
        },
        { canvas: true }
      )
    })

    it('Converts a canvas element to a JPG blob', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(
            canvas,
            function (newBlob) {
              expect(newBlob.type).to.equal('image/jpeg')
              done()
            },
            'image/jpeg'
          )
        },
        { canvas: true }
      )
    })

    it('Keeps the aspect ratio of the canvas image', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(canvas, function (newBlob) {
            window.loadImage(newBlob, function (img) {
              expect(img.width).to.equal(canvas.width)
              expect(img.height).to.equal(canvas.height)
              done()
            })
          })
        },
        { canvas: true }
      )
    })

    it('Keeps the image data of the canvas image', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(canvas, function (newBlob) {
            window.loadImage(
              newBlob,
              function (newCanvas) {
                var canvasData = canvas
                  .getContext('2d')
                  .getImageData(0, 0, canvas.width, canvas.height)
                var newCanvasData = newCanvas
                  .getContext('2d')
                  .getImageData(0, 0, newCanvas.width, newCanvas.height)
                expect(canvasData.width).to.equal(newCanvasData.width)
                expect(canvasData.height).to.equal(newCanvasData.height)
                done()
              },
              { canvas: true }
            )
          })
        },
        { canvas: true }
      )
    })
  })
})()
<commit_msg>Use a black and white sample image.<commit_after>/*
 * JavaScript Canvas to Blob Test
 * https://github.com/blueimp/JavaScript-Canvas-to-Blob
 *
 * Copyright 2012, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * https://opensource.org/licenses/MIT
 */

/* global describe, it, chai, dataURLtoBlob */

;(function () {
  'use strict'

  var expect = chai.expect
  var canvasToBlob = function (canvas, callback, type, quality) {
    setTimeout(function () {
      callback(dataURLtoBlob(canvas.toDataURL(type, quality)))
    })
  }

  // black 60x40 GIF
  // Image data layout (B=black, F=white), scaled to 3x2:
  // BFF
  // BBB
  var b64Data =
    'R0lGODlhPAAoAPECAAAAAP///wAAAAAAACH5BAUAAAIALAAAAAA8ACgAQAJihI+Zwe0Po3Sq' +
    '1okztvzoDwbdSJbmiaaqGbbTCrjyA9f2jef6Ts6+uPrNYEIZsdg6IkG8pvMJjUqnVOgypLxm' +
    'stpXsLv9gr2q8UZshnDTjTUbWH7TqvS6/Y7P6/f8vv9vVwAAOw=='
  var imageUrl = 'data:image/gif;base64,' + b64Data
  var blob = dataURLtoBlob(imageUrl)

  describe('canvas.toBlob', function () {
    it('Converts a canvas element to a blob and passes it to the callback function', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(canvas, function (newBlob) {
            expect(newBlob).to.be.a.instanceOf(Blob)
            done()
          })
        },
        { canvas: true }
      )
    })

    it('Converts a canvas element to a PNG blob', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(
            canvas,
            function (newBlob) {
              expect(newBlob.type).to.equal('image/png')
              done()
            },
            'image/png'
          )
        },
        { canvas: true }
      )
    })

    it('Converts a canvas element to a JPG blob', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(
            canvas,
            function (newBlob) {
              expect(newBlob.type).to.equal('image/jpeg')
              done()
            },
            'image/jpeg'
          )
        },
        { canvas: true }
      )
    })

    it('Keeps the aspect ratio of the canvas image', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(canvas, function (newBlob) {
            window.loadImage(newBlob, function (img) {
              expect(img.width).to.equal(canvas.width)
              expect(img.height).to.equal(canvas.height)
              done()
            })
          })
        },
        { canvas: true }
      )
    })

    it('Keeps the image data of the canvas image', function (done) {
      window.loadImage(
        blob,
        function (canvas) {
          canvasToBlob(canvas, function (newBlob) {
            window.loadImage(
              newBlob,
              function (newCanvas) {
                var canvasData = canvas
                  .getContext('2d')
                  .getImageData(0, 0, canvas.width, canvas.height)
                var newCanvasData = newCanvas
                  .getContext('2d')
                  .getImageData(0, 0, newCanvas.width, newCanvas.height)
                expect(canvasData.width).to.equal(newCanvasData.width)
                expect(canvasData.height).to.equal(newCanvasData.height)
                done()
              },
              { canvas: true }
            )
          })
        },
        { canvas: true }
      )
    })
  })
})()
<|endoftext|>


<commit_before>'use strict';
/* global require */

var test = require('tape');
var fs = require('fs');
var jadeDoc = require('../');
var jadeDocParser = require('../lib/parser');

/**
 * Simple Jade tag
 */

test('tag', function(assert){

  var stream = jadeDoc({
    input: ['./test/fixtures/tag.jade']
  });

  stream.on('data', function(data){

    var actual = data.meta.name;
    var expected = 'some-tag';
    assert.equal(actual, expected, 'Name should match name inside YAML data');

    actual = data.file;
    expected = 'test/fixtures/tag.jade';
    assert.equal(actual, expected, 'Filename should match the jade file');

    actual = data.source;
    expected = 'div.some-tag\n  | this is some tag #{foo}';
    assert.equal(actual, expected, 'Source code block should be correct');

    actual = data.output;
    expected = '
this is some tag foo
';
    assert.equal(actual, expected, 'Its html output should be correct');

    assert.end();
  });
});

/**
 * Mixins
 */

test('mixins', function(assert){

  var stream = jadeDoc({
    input: ['./test/fixtures/mixins.jade']
  });

  stream.on('data', function(data){

    var actual = data.meta.name;
    var expected = 'mixin';
    assert.equal(actual, expected, 'Name should match name inside YAML data');

    actual = data.meta.description;
    expected = 'this is jade mixin documentation';
    assert.equal(actual, expected, 'Description should match description inside YAML data');

    actual = data.file;
    expected = 'test/fixtures/mixins.jade';
    assert.equal(actual, expected, 'Filename should match the jade file');

    actual = Array.isArray(data.meta.arguments);
    expected = true;
    assert.equal(actual, expected, 'Arguments should be an array');

    actual = data.meta.arguments[0].name;
    expected = 'arg1';
    assert.equal(actual, expected, 'Argument 1 name should be arg1');

    actual = data.meta.arguments[0].type;
    expected = 'string';
    assert.equal(actual, expected, 'Argument 1 type should be string');

    actual = data.meta.arguments[0].original;
    expected = '{string} arg1 - this is arg1';
    assert.equal(actual, expected, 'Argument 1 original should be the jsdoc string');

    actual = data.meta.arguments[1].name;
    expected = 'arg2';
    assert.equal(actual, expected, 'Argument 2 name should be arg1');

    actual = data.meta.arguments[1].type;
    expected = 'string';
    assert.equal(actual, expected, 'Argument 2 type should be string');

    actual = data.meta.arguments[1].original;
    expected = '{string} arg2 - this is arg2';
    assert.equal(actual, expected, 'Argument 2 original should be the jsdoc string');

    actual = data.source;
    expected = 'mixin mixin2(arg1, arg2)\n  div this is a mixin #{arg1}\n  div this is the same mixin #{arg2}';
    assert.equal(actual, expected, 'Source should match the complete mixin code block');

    actual = data.output;
    expected = '
this is a mixin foo

this is the same mixin faa

this is a mixin faa

this is the same mixin foo
';
    assert.equal(actual, expected, 'HTML output should be the rendered mixin with passed arguments.');

    actual = data.meta.examples;
    expected = ["+mixin2('foo', 'faa')", "+mixin2('faa', 'foo')"];
    assert.deepEqual(actual, expected, 'examples should be an array');

    assert.end();
  });
});

/**
 * Include
 */

test('Include', function(assert){

  var stream = jadeDoc({
    input: ['./test/fixtures/include.jade']
  });

  stream.on('data', function(data){

    var actual = data.meta.name;
    var expected = 'inclusion tag';
    assert.equal(actual, expected, 'Name should match name inside YAML data');

    actual = data.meta.description;
    expected = 'this is an inclusion tag';
    assert.equal(actual, expected, 'Description should match description inside YAML data');

    actual = data.file;
    expected = 'test/fixtures/include.jade';
    assert.equal(actual, expected, 'Filename should match the jade file');

    actual = data.source;
    expected = 'div\n  include mixins.jade\n  +mixin2(\'foo\', \'faa\')';
    assert.equal(actual, expected, 'Source should match the complete mixin code block');

    actual = data.output;
    expected = '

this is a mixin foo

this is the same mixin faa

';
    assert.equal(actual, expected, 'HTML output should be the rendered mixin with passed arguments.');

    assert.end();
  });
});

/**
 * Extends
 */

test('Extends', function(assert){

  var stream = jadeDoc({
    input: ['./test/fixtures/extends.jade']
  });

  stream.on('data', function(data){

    var actual = data.meta.name;
    var expected = 'extends';
    assert.equal(actual, expected, 'Name should match name inside YAML data');

    actual = data.file;
    expected = 'test/fixtures/extends.jade';
    assert.equal(actual, expected, 'Filename should match the jade file');

    actual = data.source;
    expected = 'extends tag.jade';
    assert.equal(actual, expected, 'Source should match the extends tag');

    actual = data.output;
    expected = '
this is some tag foo

this is some other tag
';
    assert.equal(actual, expected, 'Output should match the html compiled from tag.jade');

    assert.end();
  });
});

/**
 * Parser
 */

test('Parser: extract jadedoc', function(assert){
  var src = fs.readFileSync('./test/fixtures/multiple.jade').toString();

  var actual = jadeDocParser.extractJadedocBlocks(src);
  var expected =  [ { code: 'p foo', comment: '//- @jadedoc\n  name: foo', lineNumber: 1 }, { code: 'p faa', comment: '//- @jadedoc', lineNumber: 6 } ];
  assert.deepEqual(actual, expected, 'extractor should return array with objects');

  actual = jadeDocParser.extractJadedocBlocks('//- @jadedoc\nname: foo');
  expected = [ { code: 'name: foo', comment: '//- @jadedoc', lineNumber: 1 } ];
  assert.deepEqual(actual, expected, 'extractor should return array with objects');

  actual = jadeDocParser.extractJadedocBlocks('');
  expected = [];
  assert.deepEqual(actual, expected, 'extractor should return empty array when nothing was passed in');

  actual = jadeDocParser.extractJadedocBlocks('//- @jadedoc');
  expected = [];
  assert.deepEqual(actual, expected, 'extractor should return empty array when only an empty jadedoc was passed');

  assert.end();
});

test('Parser: parse comment', function(assert){

  var actual = jadeDocParser.parseJadedocComment('\nname: foo\ndescription: faa');
  var expected = { name: 'foo', description: 'faa' };
  assert.deepEqual(actual, expected, 'yaml comment should return object');

  actual = jadeDocParser.parseJadedocComment('');
  expected = {};
  assert.deepEqual(actual, expected, 'comment parser should return empty object if no input was given');

  actual = jadeDocParser.parseJadedocComment('//- @jadedoc');
  expected = {};
  assert.deepEqual(actual, expected, 'comment parser should return empty object if no input was given');

  actual = jadeDocParser.parseJadedocComment('//- @jadedoc\n');
  expected = {};
  assert.deepEqual(actual, expected, 'comment parser should return empty object if no input was given');

  assert.end();
});

test('Parser: parse doc', function(assert){
  var src = fs.readFileSync('./test/fixtures/multiple.jade').toString();

  var actual = jadeDocParser.getJadedocDocuments(src, 'test.jade');
  var expected = [ { file: 'test.jade', meta: { name: 'foo' }, output: '
foo
', source: 'p foo' }, { file: 'test.jade', meta: {}, output: '
faa
', source: 'p faa' } ];
  assert.deepEqual(actual, expected, 'document parser should return valid object');

  actual = jadeDocParser.getJadedocDocuments('', 'test.jade');
  expected = {};
  assert.deepEqual(actual, expected, 'document parser should return empty object');

  assert.end();
});

test('Insert into array', function(assert){

  var actual = jadeDocParser.insertIntoArray([], 'foo');
  var expected = ['foo'];
  assert.deepEqual(actual, expected, 'should insert a string');

  actual = jadeDocParser.insertIntoArray([], ['foo', 'faa']);
  expected = ['foo', 'faa'];
  assert.deepEqual(actual, expected, 'should insert an array');

  assert.end();
});

test('Get examples', function(assert){

  var actual = jadeDocParser.getExamples({ example: 'foo' });
  var expected = ['foo'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given example object string');

  actual = jadeDocParser.getExamples({ example: ['foo', 'faa'] });
  expected = ['foo', 'faa'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given example object array');

  actual = jadeDocParser.getExamples({ example: '' });
  expected = [];
  assert.deepEqual(actual, expected, 'should return an empty when given an empty examples string');

  actual = jadeDocParser.getExamples({ examples: 'foo' });
  expected = ['foo'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given examples object string');

  actual = jadeDocParser.getExamples({ examples: ['foo', 'faa'] });
  expected = ['foo', 'faa'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given examples object array');

  actual = jadeDocParser.getExamples({ examples: '' });
  expected = [];
  assert.deepEqual(actual, expected, 'should return an empty when given an empty examples string');

  actual = jadeDocParser.getExamples({ example: 'bar', examples: ['foo', 'faa'] });
  expected = ['bar', 'foo', 'faa'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given examples object array and example string');

  actual = jadeDocParser.getExamples({ example: '', examples: ['foo', 'faa'] });
  expected = ['foo', 'faa'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given examples object array');

  actual = jadeDocParser.getExamples({ example: [], examples: [] });
  expected = [];
  assert.deepEqual(actual, expected, 'should return an empty array of examples when given empty examples object array');

  assert.end();
});<commit_msg>fix quotes<commit_after>'use strict';
/* global require */

var test = require('tape');
var fs = require('fs');
var jadeDoc = require('../');
var jadeDocParser = require('../lib/parser');

/**
 * Simple Jade tag
 */

test('tag', function(assert){

  var stream = jadeDoc({
    input: ['./test/fixtures/tag.jade']
  });

  stream.on('data', function(data){

    var actual = data.meta.name;
    var expected = 'some-tag';
    assert.equal(actual, expected, 'Name should match name inside YAML data');

    actual = data.file;
    expected = 'test/fixtures/tag.jade';
    assert.equal(actual, expected, 'Filename should match the jade file');

    actual = data.source;
    expected = 'div.some-tag\n  | this is some tag #{foo}';
    assert.equal(actual, expected, 'Source code block should be correct');

    actual = data.output;
    expected = '
this is some tag foo
';
    assert.equal(actual, expected, 'Its html output should be correct');

    assert.end();
  });
});

/**
 * Mixins
 */

test('mixins', function(assert){

  var stream = jadeDoc({
    input: ['./test/fixtures/mixins.jade']
  });

  stream.on('data', function(data){

    var actual = data.meta.name;
    var expected = 'mixin';
    assert.equal(actual, expected, 'Name should match name inside YAML data');

    actual = data.meta.description;
    expected = 'this is jade mixin documentation';
    assert.equal(actual, expected, 'Description should match description inside YAML data');

    actual = data.file;
    expected = 'test/fixtures/mixins.jade';
    assert.equal(actual, expected, 'Filename should match the jade file');

    actual = Array.isArray(data.meta.arguments);
    expected = true;
    assert.equal(actual, expected, 'Arguments should be an array');

    actual = data.meta.arguments[0].name;
    expected = 'arg1';
    assert.equal(actual, expected, 'Argument 1 name should be arg1');

    actual = data.meta.arguments[0].type;
    expected = 'string';
    assert.equal(actual, expected, 'Argument 1 type should be string');

    actual = data.meta.arguments[0].original;
    expected = '{string} arg1 - this is arg1';
    assert.equal(actual, expected, 'Argument 1 original should be the jsdoc string');

    actual = data.meta.arguments[1].name;
    expected = 'arg2';
    assert.equal(actual, expected, 'Argument 2 name should be arg1');

    actual = data.meta.arguments[1].type;
    expected = 'string';
    assert.equal(actual, expected, 'Argument 2 type should be string');

    actual = data.meta.arguments[1].original;
    expected = '{string} arg2 - this is arg2';
    assert.equal(actual, expected, 'Argument 2 original should be the jsdoc string');

    actual = data.source;
    expected = 'mixin mixin2(arg1, arg2)\n  div this is a mixin #{arg1}\n  div this is the same mixin #{arg2}';
    assert.equal(actual, expected, 'Source should match the complete mixin code block');

    actual = data.output;
    expected = '
this is a mixin foo

this is the same mixin faa

this is a mixin faa

this is the same mixin foo
';
    assert.equal(actual, expected, 'HTML output should be the rendered mixin with passed arguments.');

    actual = data.meta.examples;
    expected = ['+mixin2(\'foo\', \'faa\')', '+mixin2(\'faa\', \'foo\')'];
    assert.deepEqual(actual, expected, 'examples should be an array');

    assert.end();
  });
});

/**
 * Include
 */

test('Include', function(assert){

  var stream = jadeDoc({
    input: ['./test/fixtures/include.jade']
  });

  stream.on('data', function(data){

    var actual = data.meta.name;
    var expected = 'inclusion tag';
    assert.equal(actual, expected, 'Name should match name inside YAML data');

    actual = data.meta.description;
    expected = 'this is an inclusion tag';
    assert.equal(actual, expected, 'Description should match description inside YAML data');

    actual = data.file;
    expected = 'test/fixtures/include.jade';
    assert.equal(actual, expected, 'Filename should match the jade file');

    actual = data.source;
    expected = 'div\n  include mixins.jade\n  +mixin2(\'foo\', \'faa\')';
    assert.equal(actual, expected, 'Source should match the complete mixin code block');

    actual = data.output;
    expected = '

this is a mixin foo

this is the same mixin faa

';
    assert.equal(actual, expected, 'HTML output should be the rendered mixin with passed arguments.');

    assert.end();
  });
});

/**
 * Extends
 */

test('Extends', function(assert){

  var stream = jadeDoc({
    input: ['./test/fixtures/extends.jade']
  });

  stream.on('data', function(data){

    var actual = data.meta.name;
    var expected = 'extends';
    assert.equal(actual, expected, 'Name should match name inside YAML data');

    actual = data.file;
    expected = 'test/fixtures/extends.jade';
    assert.equal(actual, expected, 'Filename should match the jade file');

    actual = data.source;
    expected = 'extends tag.jade';
    assert.equal(actual, expected, 'Source should match the extends tag');

    actual = data.output;
    expected = '
this is some tag foo

this is some other tag
';
    assert.equal(actual, expected, 'Output should match the html compiled from tag.jade');

    assert.end();
  });
});

/**
 * Parser
 */

test('Parser: extract jadedoc', function(assert){
  var src = fs.readFileSync('./test/fixtures/multiple.jade').toString();

  var actual = jadeDocParser.extractJadedocBlocks(src);
  var expected =  [ { code: 'p foo', comment: '//- @jadedoc\n  name: foo', lineNumber: 1 }, { code: 'p faa', comment: '//- @jadedoc', lineNumber: 6 } ];
  assert.deepEqual(actual, expected, 'extractor should return array with objects');

  actual = jadeDocParser.extractJadedocBlocks('//- @jadedoc\nname: foo');
  expected = [ { code: 'name: foo', comment: '//- @jadedoc', lineNumber: 1 } ];
  assert.deepEqual(actual, expected, 'extractor should return array with objects');

  actual = jadeDocParser.extractJadedocBlocks('');
  expected = [];
  assert.deepEqual(actual, expected, 'extractor should return empty array when nothing was passed in');

  actual = jadeDocParser.extractJadedocBlocks('//- @jadedoc');
  expected = [];
  assert.deepEqual(actual, expected, 'extractor should return empty array when only an empty jadedoc was passed');

  assert.end();
});

test('Parser: parse comment', function(assert){

  var actual = jadeDocParser.parseJadedocComment('\nname: foo\ndescription: faa');
  var expected = { name: 'foo', description: 'faa' };
  assert.deepEqual(actual, expected, 'yaml comment should return object');

  actual = jadeDocParser.parseJadedocComment('');
  expected = {};
  assert.deepEqual(actual, expected, 'comment parser should return empty object if no input was given');

  actual = jadeDocParser.parseJadedocComment('//- @jadedoc');
  expected = {};
  assert.deepEqual(actual, expected, 'comment parser should return empty object if no input was given');

  actual = jadeDocParser.parseJadedocComment('//- @jadedoc\n');
  expected = {};
  assert.deepEqual(actual, expected, 'comment parser should return empty object if no input was given');

  assert.end();
});

test('Parser: parse doc', function(assert){
  var src = fs.readFileSync('./test/fixtures/multiple.jade').toString();

  var actual = jadeDocParser.getJadedocDocuments(src, 'test.jade');
  var expected = [ { file: 'test.jade', meta: { name: 'foo' }, output: '
foo
', source: 'p foo' }, { file: 'test.jade', meta: {}, output: '
faa
', source: 'p faa' } ];
  assert.deepEqual(actual, expected, 'document parser should return valid object');

  actual = jadeDocParser.getJadedocDocuments('', 'test.jade');
  expected = {};
  assert.deepEqual(actual, expected, 'document parser should return empty object');

  assert.end();
});

test('Insert into array', function(assert){

  var actual = jadeDocParser.insertIntoArray([], 'foo');
  var expected = ['foo'];
  assert.deepEqual(actual, expected, 'should insert a string');

  actual = jadeDocParser.insertIntoArray([], ['foo', 'faa']);
  expected = ['foo', 'faa'];
  assert.deepEqual(actual, expected, 'should insert an array');

  assert.end();
});

test('Get examples', function(assert){

  var actual = jadeDocParser.getExamples({ example: 'foo' });
  var expected = ['foo'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given example object string');

  actual = jadeDocParser.getExamples({ example: ['foo', 'faa'] });
  expected = ['foo', 'faa'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given example object array');

  actual = jadeDocParser.getExamples({ example: '' });
  expected = [];
  assert.deepEqual(actual, expected, 'should return an empty when given an empty examples string');

  actual = jadeDocParser.getExamples({ examples: 'foo' });
  expected = ['foo'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given examples object string');

  actual = jadeDocParser.getExamples({ examples: ['foo', 'faa'] });
  expected = ['foo', 'faa'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given examples object array');

  actual = jadeDocParser.getExamples({ examples: '' });
  expected = [];
  assert.deepEqual(actual, expected, 'should return an empty when given an empty examples string');

  actual = jadeDocParser.getExamples({ example: 'bar', examples: ['foo', 'faa'] });
  expected = ['bar', 'foo', 'faa'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given examples object array and example string');

  actual = jadeDocParser.getExamples({ example: '', examples: ['foo', 'faa'] });
  expected = ['foo', 'faa'];
  assert.deepEqual(actual, expected, 'should return an array of examples when given examples object array');

  actual = jadeDocParser.getExamples({ example: [], examples: [] });
  expected = [];
  assert.deepEqual(actual, expected, 'should return an empty array of examples when given empty examples object array');

  assert.end();
});<|endoftext|>