<commit_before>import async from '../src/async';
import {
    iterateeDelayWithOrder,
    iterateePromiseWithOrder,
    iterateeNativeWithOrder
} from './helper';

describe('rejectLimit', function() {
    it('does delayed items with single match', function() {
        let order = [];
        const arr = [3, 2, 1];
        const p = async.rejectLimit(arr, 2, iterateeDelayWithOrder(order, (x) => x == 2));

        return Promise.all([
            p.should.eventually.deep.equal([3, 1]),
            p.then(() => arr.should.deep.equal([3, 2, 1])),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([2, 3, 1])),
                5 * 25
            ))
        ]);
    });

    it('does delayed items with multiple match', function() {
        let order = [];
        const arr = [3, 2, 1];
        const p = async.rejectLimit(arr, 2, iterateeDelayWithOrder(order, (x) => x <= 1));

        return Promise.all([
            p.should.eventually.deep.equal([3, 2]),
            p.then(() => arr.should.deep.equal([3, 2, 1])),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([2, 3, 1])),
                5 * 25
            ))
        ]);
    });

    it('does delayed items with multiple equal match', function() {
        let order = [];
        const arr = [3, 2, 1, 2, 2];
        const p = async.rejectLimit(arr, 2, iterateeDelayWithOrder(order, (x) => x == 2));

        return Promise.all([
            p.should.eventually.deep.equal([3, 1]),
            p.then(() => arr.should.deep.equal([3, 2, 1, 2, 2])),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([2, 3, 1, 2, 2])),
                8 * 25
            ))
        ]);
    });

    it('does sync promise items', function() {
        let order = [];
        const arr = [3, 2, 1];
        const p = async.rejectLimit(arr, 2, iterateePromiseWithOrder(order, (x) => x <= 1));
        return Promise.all([
            p.should.eventually.deep.equal([3, 2]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                4 * 25
            ))
        ]);
    });

    it('does sync native items', function() {
        let order = [];
        const arr = [3, 2, 1];
        const p = async.rejectLimit(arr, 2, iterateeNativeWithOrder(order, (x) => x <= 1));
        return Promise.all([
            p.should.eventually.deep.equal([3, 2]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                4 * 25
            ))
        ]);
    });

    it('does mixed (delayed, promise, native) items', function() {
        let order = [];
        const arr = [3, 2, 1, 4, 5, 6, 9, 8, 7];
        const p = async.rejectLimit(arr, 2, value => {
            if (value >= 1 && value <= 3) {
                return new Promise(resolve => setTimeout(
                    () => {
                        order.push(value);
                        resolve(value > 2 && value < 6)
                    },
                    value * 25
                ));
            } else if (value >= 4 && value <= 6) {
                return new Promise(resolve => {
                    order.push(value);
                    resolve(value > 2 && value < 6)
                });
            } else if (value >= 7 && value <= 9) {
                order.push(value);
                return value > 2 && value < 6;
            }
        });

        return Promise.all([
            p.should.eventually.deep.equal([2, 1, 6, 9, 8, 7]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([2, 3, 4, 5, 6, 9, 8, 7, 1])),
                10 * 25
            ))
        ]);
    });

    it('has right arguments', function() {
        const arr = [1, 3, 2];
        return async.rejectLimit(arr, 2, (value, index, collection) => {
            switch (value) {
                case 1:
                    index.should.equal(0, `index is invalid for value ${value}`);
                    break;
                case 2:
                    index.should.equal(2, `index is invalid for value ${value}`);
                    break;
                case 3:
                    index.should.equal(1, `index is invalid for value ${value}`);
                    break;
            }

            collection.should.deep.equal(arr, `arr is not equal for value ${value}`);

            return value;
        });
    });

    it('supports not found', function() {
        const p = async.rejectLimit([1, 2, 3], 2, () => false);

        return Promise.all([
            p.should.eventually.deep.equal([1, 2, 3])
        ]);
    });

    it('supports empty collections', function() {
        const p = async.rejectLimit([], 2, () => assert(false, 'iteratee should not be called'));

        return Promise.all([
            p.should.eventually.deep.equal([])
        ]);
    });

    it('supports limit greater than collection size', function() {
        let order = [];
        const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        const p = async.rejectLimit(arr, 20, iterateeNativeWithOrder(order, x => x <= 2));

        return Promise.all([
            p.should.eventually.deep.equal([3, 4, 5, 6, 7, 8, 9]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                10 * 25
            ))
        ]);
    });

    it('supports limit equal to collection size', function() {
        let order = [];
        const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        const p = async.rejectLimit(arr, 10, iterateeNativeWithOrder(order, x => x <= 2));

        return Promise.all([
            p.should.eventually.deep.equal([3, 4, 5, 6, 7, 8, 9]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                10 * 25
            ))
        ]);
    });

    it('supports external array modification with mixed (delayed, sync promise) items', function() {
        let order = [];
        let arr = [4, 3, 2, 1];
        const p = async.rejectLimit(arr, 2, (value, index, collection) => {
            if (value >= 2 && value <= 3) {
                return new Promise(resolve => {
                    setTimeout(
                        () => {
                            order.push(value);
                            resolve(value <= 1);
                        },
                        value * 25
                    );
                });
            } else {
                order.push(value);
                return Promise.resolve(value <= 1);
            }
        });

        arr.pop();
        arr.shift();

        return Promise.all([
            p.should.eventually.deep.equal([4, 3, 2]),
            p.then(() => arr.should.deep.equal([3, 2])),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([4, 2, 1, 3])),
                5 * 25
            ))
        ]);
    });

    it('rejects with a 0 limit', function() {
        const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        const p = async.rejectLimit(arr, 0, () => assert(false, 'iteratee should not be called'));

        return Promise.all([
            p.should.eventually.be.rejectedWith(Error)
        ]);
    });

    it('rejects using delayed Promise.reject', function() {
        let order = [];
        const arr = [1, 3, 2];
        const p = async.rejectLimit(arr, 2, iterateeDelayWithOrder(
            order,
            (x) => x == 2 ? Promise.reject(new Error('error')) : false
        ));

        return Promise.all([
            p.should.eventually.be.rejectedWith(Error),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([1, 3, 2])),
                4 * 25
            ))
        ]);
    });

    it('rejects using sync Promise.reject', function() {
        let order = [];
        const arr = [1, 3, 2];
        const p = async.rejectLimit(arr, 2, iterateePromiseWithOrder(
            order,
            (x) => x == 3 ? Promise.reject(new Error('error')) : false
        ));

        return Promise.all([
            p.should.eventually.be.rejectedWith(Error),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                25
            ))
        ]);
    });

    it('rejects using sync throw', function() {
        let order = [];
        const arr = [1, 3, 2];
        const p = async.rejectLimit(arr, 2, iterateeNativeWithOrder(
            order,
            (x) => {
                if (x == 3) {
                    throw new Error('error');
                }
                return x;
            }
        ));

        return Promise.all([
            p.should.eventually.be.rejectedWith(Error),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                25
            ))
        ]);
    });
});
<commit_msg>Fix rejectLimit test that was causing a race condition<commit_after>import async from '../src/async';
import {
    iterateeDelayWithOrder,
    iterateePromiseWithOrder,
    iterateeNativeWithOrder
} from './helper';

describe('rejectLimit', function() {
    it('does delayed items with single match', function() {
        let order = [];
        const arr = [3, 2, 1];
        const p = async.rejectLimit(arr, 2, iterateeDelayWithOrder(order, (x) => x == 2));

        return Promise.all([
            p.should.eventually.deep.equal([3, 1]),
            p.then(() => arr.should.deep.equal([3, 2, 1])),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([2, 3, 1])),
                5 * 25
            ))
        ]);
    });

    it('does delayed items with multiple match', function() {
        let order = [];
        const arr = [3, 2, 1];
        const p = async.rejectLimit(arr, 2, iterateeDelayWithOrder(order, (x) => x <= 1));

        return Promise.all([
            p.should.eventually.deep.equal([3, 2]),
            p.then(() => arr.should.deep.equal([3, 2, 1])),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([2, 3, 1])),
                5 * 25
            ))
        ]);
    });

    it('does delayed items with multiple equal match', function() {
        let order = [];
        const arr = [3, 2, 1, 2, 2];
        const p = async.rejectLimit(arr, 2, iterateeDelayWithOrder(order, (x) => x == 2));

        return Promise.all([
            p.should.eventually.deep.equal([3, 1]),
            p.then(() => arr.should.deep.equal([3, 2, 1, 2, 2])),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([2, 3, 1, 2, 2])),
                8 * 25
            ))
        ]);
    });

    it('does sync promise items', function() {
        let order = [];
        const arr = [3, 2, 1];
        const p = async.rejectLimit(arr, 2, iterateePromiseWithOrder(order, (x) => x <= 1));
        return Promise.all([
            p.should.eventually.deep.equal([3, 2]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                4 * 25
            ))
        ]);
    });

    it('does sync native items', function() {
        let order = [];
        const arr = [3, 2, 1];
        const p = async.rejectLimit(arr, 2, iterateeNativeWithOrder(order, (x) => x <= 1));
        return Promise.all([
            p.should.eventually.deep.equal([3, 2]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                4 * 25
            ))
        ]);
    });

    it('does mixed (delayed, promise, native) items', function() {
        let order = [];
        const arr = [3, 2, 1, 4, 5, 6, 9, 8, 7];
        const p = async.rejectLimit(arr, 2, value => {
            if (value >= 1 && value <= 3) {
                return new Promise(resolve => setTimeout(
                    () => {
                        order.push(value);
                        resolve(value > 2 && value < 6)
                    },
                    value * 25
                ));
            } else if (value >= 4 && value <= 6) {
                return new Promise(resolve => {
                    order.push(value);
                    resolve(value > 2 && value < 6)
                });
            } else if (value >= 7 && value <= 9) {
                order.push(value);
                return value > 2 && value < 6;
            }
        });

        return Promise.all([
            p.should.eventually.deep.equal([2, 1, 6, 9, 8, 7]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([2, 3, 4, 5, 6, 9, 8, 7, 1])),
                10 * 25
            ))
        ]);
    });

    it('has right arguments', function() {
        const arr = [1, 3, 2];
        return async.rejectLimit(arr, 2, (value, index, collection) => {
            switch (value) {
                case 1:
                    index.should.equal(0, `index is invalid for value ${value}`);
                    break;
                case 2:
                    index.should.equal(2, `index is invalid for value ${value}`);
                    break;
                case 3:
                    index.should.equal(1, `index is invalid for value ${value}`);
                    break;
            }

            collection.should.deep.equal(arr, `arr is not equal for value ${value}`);

            return value;
        });
    });

    it('supports not found', function() {
        const p = async.rejectLimit([1, 2, 3], 2, () => false);

        return Promise.all([
            p.should.eventually.deep.equal([1, 2, 3])
        ]);
    });

    it('supports empty collections', function() {
        const p = async.rejectLimit([], 2, () => assert(false, 'iteratee should not be called'));

        return Promise.all([
            p.should.eventually.deep.equal([])
        ]);
    });

    it('supports limit greater than collection size', function() {
        let order = [];
        const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        const p = async.rejectLimit(arr, 20, iterateeNativeWithOrder(order, x => x <= 2));

        return Promise.all([
            p.should.eventually.deep.equal([3, 4, 5, 6, 7, 8, 9]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                10 * 25
            ))
        ]);
    });

    it('supports limit equal to collection size', function() {
        let order = [];
        const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        const p = async.rejectLimit(arr, 10, iterateeNativeWithOrder(order, x => x <= 2));

        return Promise.all([
            p.should.eventually.deep.equal([3, 4, 5, 6, 7, 8, 9]),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                10 * 25
            ))
        ]);
    });

    it('supports external array modification with mixed (delayed, sync promise) items', function() {
        let order = [];
        let arr = [4, 3, 2, 1];
        const p = async.rejectLimit(arr, 2, (value, index, collection) => {
            if (value >= 2 && value <= 3) {
                return new Promise(resolve => {
                    setTimeout(
                        () => {
                            order.push(value);
                            resolve(value <= 1);
                        },
                        value * 25
                    );
                });
            } else {
                order.push(value);
                return Promise.resolve(value <= 1);
            }
        });

        arr.pop();
        arr.shift();

        return Promise.all([
            p.should.eventually.deep.equal([4, 3, 2]),
            p.then(() => arr.should.deep.equal([3, 2])),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([4, 2, 1, 3])),
                5 * 25
            ))
        ]);
    });

    it('rejects with a 0 limit', function() {
        const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        const p = async.rejectLimit(arr, 0, () => assert(false, 'iteratee should not be called'));

        return Promise.all([
            p.should.eventually.be.rejectedWith(Error)
        ]);
    });

    it('rejects using delayed Promise.reject', function() {
        let order = [];
        const arr = [1, 4, 2];
        const p = async.rejectLimit(arr, 2, iterateeDelayWithOrder(
            order,
            (x) => x == 2 ? Promise.reject(new Error('error')) : false
        ));

        return Promise.all([
            p.should.eventually.be.rejectedWith(Error),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal([1, 2, 4])),
                5 * 25
            ))
        ]);
    });

    it('rejects using sync Promise.reject', function() {
        let order = [];
        const arr = [1, 3, 2];
        const p = async.rejectLimit(arr, 2, iterateePromiseWithOrder(
            order,
            (x) => x == 3 ? Promise.reject(new Error('error')) : false
        ));

        return Promise.all([
            p.should.eventually.be.rejectedWith(Error),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                25
            ))
        ]);
    });

    it('rejects using sync throw', function() {
        let order = [];
        const arr = [1, 3, 2];
        const p = async.rejectLimit(arr, 2, iterateeNativeWithOrder(
            order,
            (x) => {
                if (x == 3) {
                    throw new Error('error');
                }
                return x;
            }
        ));

        return Promise.all([
            p.should.eventually.be.rejectedWith(Error),
            new Promise(resolve => setTimeout(
                () => resolve(order.should.deep.equal(arr)),
                25
            ))
        ]);
    });
});
<|endoftext|>


<commit_before>var assert = require("assert")
  , config = require("./../config")
  , Sequelize = require("./../../index")
  , sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})

module.exports = {
  'it should correctly determine equal objects': function(exit) {
    var User = sequelize.define('User' + config.rand(), { name: Sequelize.STRING, bio: Sequelize.TEXT })

    User.sync({force: true}).on('success', function() {
      User.create({name: 'hallo', bio: 'welt'}).on('success', function(u) {
        assert.eql(u.equals(u), true)
        exit(function(){})
      })
    })
  },
  'it should correctly work with different primary keys': function(exit) {
    var User = sequelize.define('User' + config.rand(), {
      foo: {type: Sequelize.STRING, primaryKey: true},
      bar: {type: Sequelize.STRING, primaryKey: true},
      name: Sequelize.STRING, bio: Sequelize.TEXT
    })

    User.sync({force: true}).on('success', function() {
      User.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).on('success', function(u) {
        assert.eql(u.equals(u), true)
        exit(function(){})
      })
    })
  },
  'equalsOneOf should work': function(exit) {
    var User = sequelize.define('User' + config.rand(), {
      foo: {type: Sequelize.STRING, primaryKey: true},
      bar: {type: Sequelize.STRING, primaryKey: true},
      name: Sequelize.STRING, bio: Sequelize.TEXT
    })

    User.sync({force: true}).on('success', function() {
      User.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).on('success', function(u) {
        assert.eql(u.equalsOneOf([u, {a:1}]), true)
        assert.eql(u.equalsOneOf([{b:2}, {a:1}]), false)
        exit(function(){})
      })
    })
  }
}<commit_msg>debugging for travis<commit_after>var assert = require("assert")
  , config = require("./../config")
  , Sequelize = require("./../../index")
  , sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})

module.exports = {
  'it should correctly determine equal objects': function(exit) {
    var User = sequelize.define('User' + config.rand(), { name: Sequelize.STRING, bio: Sequelize.TEXT })

    User.sync({force: true}).on('success', function() {
      User.create({name: 'hallo', bio: 'welt'}).on('success', function(u) {
        assert.eql(u.equals(u), true)
        exit(function(){})
      }).on('failure', function(err) { console.log(err) })
    }).on('failure', function(err) { console.log(err) })
  },
  'it should correctly work with different primary keys': function(exit) {
    var User = sequelize.define('User' + config.rand(), {
      foo: {type: Sequelize.STRING, primaryKey: true},
      bar: {type: Sequelize.STRING, primaryKey: true},
      name: Sequelize.STRING, bio: Sequelize.TEXT
    })

    User.sync({force: true}).on('success', function() {
      User.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).on('success', function(u) {
        assert.eql(u.equals(u), true)
        exit(function(){})
      })
    })
  },
  'equalsOneOf should work': function(exit) {
    var User = sequelize.define('User' + config.rand(), {
      foo: {type: Sequelize.STRING, primaryKey: true},
      bar: {type: Sequelize.STRING, primaryKey: true},
      name: Sequelize.STRING, bio: Sequelize.TEXT
    })

    User.sync({force: true}).on('success', function() {
      User.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).on('success', function(u) {
        assert.eql(u.equalsOneOf([u, {a:1}]), true)
        assert.eql(u.equalsOneOf([{b:2}, {a:1}]), false)
        exit(function(){})
      })
    })
  }
}
<|endoftext|>


<commit_before>/* global describe it before */

const assert = require('chai').assert
const path = require('path')
const fs = require('fs')

const surgicalReport = require('../src/index.js').surgicalReport

var inputData = require(path.join(__dirname, 'input-data'))

describe('Surgical Report', function () {
  before(function (done) {
    inputData.build(function (err, data) {
      if (err) return err
      inputData = data
      done()
    })
  })
  /*
  it('Input data tests', function (done) {
    assert.notEqual(inputData, null, 'input data cannot be null')
    assert.isArray(inputData.addresses, 'addresses must be an array')
    done()
  })
  */
  it('Surgical Report Tests', function (done) {
    surgicalReport.build(inputData, function (err, html) {
      if (err) console.log(err)
      assert.isNotNull(html)
      var documentPath = './reports/surgical-report.html'
      fs.writeFile(documentPath, html, function (err) {
        if (err) console.log(err)
        done()
      })
    })
  })
})
<commit_msg>changes to report tests<commit_after>/* global describe it before */

const assert = require('chai').assert
const path = require('path')
const fs = require('fs')

const surgicalReport = require('../src/index.js').surgicalReport

var inputData = require(path.join(__dirname, 'input-data'))

describe('Surgical Report', function () {
  before(function (done) {
    inputData.build(function (err, data) {
      if (err) return err
      inputData = data
      done()
    })
  })
  it('Input data tests', function (done) {
    assert.notEqual(inputData, null, 'input data cannot be null')
    assert.isArray(inputData.addresses, 'addresses must be an array')
    done()
  })
  it('Surgical Report Tests', function (done) {
    surgicalReport.build(inputData, function (err, html) {
      if (err) console.log(err)
      assert.isNotNull(html)
      var documentPath = './reports/surgical-report.html'
      fs.writeFile(documentPath, html, function (err) {
        if (err) console.log(err)
        done()
      })
    })
  })
})
<|endoftext|>


<commit_before>'use strict'

var opbeat = require('../../')

var fs = require('fs')
var path = require('path')
var mkdirp = require('mkdirp')
var inquirer = require('inquirer')
var untildify = require('untildify')

var standardTest = function () {
  console.log('Tracking release...')
  opbeat.trackRelease(function () {
    console.log('The release have been tracked!')

    console.log('Capturing error...')
    opbeat.captureError(new Error('This is an Error object'), function (err, url) {
      if (err) console.log('Something went wrong:', err.message)
      console.log('The error have been logged at:', url)

      console.log('Capturing message...')
      opbeat.captureError('This is a string', function (err, url) {
        if (err) console.log('Something went wrong:', err.message)
        console.log('The message have been logged at:', url)

        console.log('Throwing exception...')
        throw new Error('This Error was thrown')
      })
    })
  })
}

var httpTest = function () {
  var http = require('http')

  var server1 = http.createServer(function (req, res) {
    var err = new Error('This is a request related error')
    opbeat.captureError(err, function (err, url) {
      if (err) console.log('Something went wrong:', err.message)
      console.log('The error have been logged at:', url)
      res.end()

      testServer2()
    })
    res.writeHead(500)
  })

  var server2 = http.createServer()

  server2.on('request', function (req, res) {
    switch (req.url) {
      case '/error':
        var err = new Error('This is a request related error')
        opbeat.captureError(err, function (err, url) {
          if (err) console.log('Something went wrong:', err.message)
          console.log('The error have been logged at:', url)
          res.end()
        })
        res.writeHead(500)
        break
      case '/throw':
        throw new Error('This Error was thrown from wihtin a http server')
    }
  })

  testServer1()

  function testServer1 () {
    server1.listen(function () {
      var port = server1.address().port
      var base = 'http://localhost:' + port
      console.log('Test server running on port', port)

      console.log('Capturing request error...')
      http.get(base + '/error')
    })
  }

  function testServer2 () {
    server2.listen(function () {
      var port = server2.address().port
      var base = 'http://localhost:' + port
      console.log('Test server running on port', port)

      console.log('Capturing request error...')
      http.get(base + '/error', function (res) {
        console.log('Throwing http exception...')
        http.get(base + '/throw')
      })
    })
  }
}

var restifyTest = function () {
  var restify = require('restify')

  var server = restify.createServer({ name: 'foo', version: '1.0.0' })

  server.on('uncaughtException', function (req, res, route, err) {
    opbeat.captureError(err, function (err, url) {
      if (err) console.log('Something went wrong:', err.message)
      console.log('The error have been logged at:', url)
      process.exit()
    })
  })

  server.get('/error', function (req, res, next) {
    var err = new Error('This is a request related error')
    opbeat.captureError(err, function (err, url) {
      if (err) console.log('Something went wrong:', err.message)
      console.log('The error have been logged at:', url)
      res.end()
      next()
    })
    res.writeHead(500)
  })

  server.get('/throw', function (req, res, next) {
    throw new Error('This Error was thrown from wihtin a http server')
  })

  server.listen(function () {
    var port = server.address().port
    var base = 'http://localhost:' + port
    console.log('Test server running on port', port)

    var client = restify.createJsonClient({
      url: base,
      version: '~1.0'
    })

    console.log('Capturing request error...')
    client.get('/error', function (err, req, res, obj) { // eslint-disable-line handle-callback-err
      console.log('Throwing http exception...')
      client.get('/throw', function () {})
    })
  })
}

var connectTest = function () {
  var http = require('http')
  var connect = require('connect')

  var testsLeft = 2
  var app = connect()
  app.use(function (req, res, next) {
    switch (req.url) {
      case '/error':
        res.writeHead(500)
        res.end()
        next(new Error('foobar'))
        break
      case '/throw':
        throw new Error('foobar')
      default:
        res.end()
    }
  })
  app.use(opbeat.middleware.connect())
  app.use(function (err, req, res, next) { // eslint-disable-line handle-callback-err
    if (!--testsLeft) process.exit()
  })

  var server = http.createServer(app)
  server.listen(function () {
    var port = server.address().port
    var base = 'http://localhost:' + port
    console.log('Test server running on port', port)
    console.log('NOTE: No Opbeat error urls will be displayed during this test!')

    console.log('Capturing request error...')
    http.get(base + '/error', function (res) {
      console.log('Throwing http exception...')
      http.get(base + '/throw', function () {})
    })
  })
}

var expressTest = function () {
  var http = require('http')
  var express = require('express')

  var testsLeft = 2
  var app = express()

  app.use(function (req, res, next) {
    if (req.url === '/error') var err = new Error('foobar')
    next(err)
  })
  app.get('/throw', function (req, res) {
    throw new Error('foobar')
  })
  app.use(opbeat.middleware.express())
  app.use(function (err, req, res, next) {
    if (!err) return
    if (!res.headersSent) {
      res.writeHead(500)
      res.end()
    }
    if (!--testsLeft) process.exit()
  })

  var server = app.listen(function () {
    var port = server.address().port
    var base = 'http://localhost:' + port
    console.log('Test server running on port', port)
    console.log('NOTE: No Opbeat error urls will be displayed during this test!')

    console.log('Capturing request error...')
    http.get(base + '/error', function (res) {
      console.log('Throwing http exception...')
      http.get(base + '/throw', function () {})
    })
  })
}

var transactionTest = function () {
  console.log('Tracking transaction...')
  var maxSeconds = 55
  var start = Date.now()

  makeTransaction()

  function makeTransaction () {
    if ((Date.now() - start) / 1000 > maxSeconds) {
      console.log('Done making transactions')
      return
    }

    console.log('Starting new transaction')

    var trans = opbeat.startTransaction('foo', 'bar')
    var t1 = trans.startTrace('sig1', 'foo.bar.baz1')
    var t2 = trans.startTrace('sig2', 'foo.bar.baz1')

    setTimeout(function () {
      var t3 = trans.startTrace('sig3', 'foo.bar.baz2')
      setTimeout(function () {
        var t4 = trans.startTrace('sig4', 'foo.bar.baz3')
        setTimeout(function () {
          t3.end()
          t4.end()
          t1.end()
        }, Math.random() * 100 + 50)
      }, Math.random() * 100 + 50)
    }, Math.random() * 100 + 25)

    setTimeout(function () {
      var t5 = trans.startTrace('sig5', 'foo.bar.baz2')
      setTimeout(function () {
        var t6 = trans.startTrace('sig6', 'foo.bar.baz4')
        setTimeout(function () {
          t6.end()
          t5.end()
          t2.end()
        }, Math.random() * 100 + 50)
      }, Math.random() * 100 + 50)
    }, Math.random() * 100 + 50)

    setTimeout(function () {
      trans.result = Math.round(Math.random() * 350 + 200)
      trans.result = 204

      console.log('Ending transaction')
      trans.end()
    }, 500)

    setTimeout(makeTransaction, Math.random() * 300 + 200)
  }
}

var test = function (suite, opts) {
  opts.env = 'production'
  opts.logLevel = 'fatal'
  opts.captureExceptions = false
  opbeat.start(opts)

  opbeat.handleUncaughtExceptions(function (err, url) { // eslint-disable-line handle-callback-err
    console.log('The uncaught exception have been logged at:', url)
    process.exit()
  })

  opbeat.on('error', function (err) {
    console.log(err.stack)
  })

  switch (suite) {
    case 'standard': return standardTest()
    case 'http': return httpTest()
    case 'restify': return restifyTest()
    case 'connect': return connectTest()
    case 'express': return expressTest()
    case 'transaction': return transactionTest()
    default: console.log('Unknown test suite selected:', suite)
  }
}

var loadConf = function (cb) {
  var file = untildify('~/.config/opbeat.json')
  fs.exists(file, function (exists) {
    if (!exists) return cb({})
    fs.readFile(file, function (err, data) {
      if (err) throw err
      cb(JSON.parse(data))
    })
  })
}

var saveConf = function (conf, cb) {
  var dir = untildify('~/.config')
  mkdirp(dir, '0755', function (err) {
    if (err) throw err
    var file = path.join(dir, 'opbeat.json')
    fs.writeFile(file, JSON.stringify(conf), function (err) {
      if (err) throw err
      console.log('Saved config:', file)
      cb()
    })
  })
}

loadConf(function (conf) {
  var questions = [
    { name: 'appId', message: 'App ID', 'default': conf.appId },
    { name: 'organizationId', message: 'Organization ID', 'default': conf.organizationId },
    { name: 'secretToken', message: 'Secret token', 'default': conf.secretToken },
    { name: 'suite', message: 'Test suite', type: 'list', choices: ['standard', 'http', 'restify', 'connect', 'express', 'transaction'] },
    { name: 'save', message: 'Save answers?', type: 'confirm' }
  ]

  inquirer.prompt(questions, function (answers) {
    var suite = answers.suite
    var save = answers.save
    delete answers.suite
    delete answers.save

    if (save) saveConf(answers, test.bind(null, suite, answers))
    else process.nextTick(test.bind(null, suite, answers)) // inquirer gives quite a long stack-trace, so let's do this async
  })
})
<commit_msg>Update 'npm run test-cli' to use new transaction API<commit_after>'use strict'

var opbeat = require('../../')

var fs = require('fs')
var path = require('path')
var mkdirp = require('mkdirp')
var inquirer = require('inquirer')
var untildify = require('untildify')

var standardTest = function () {
  console.log('Tracking release...')
  opbeat.trackRelease(function () {
    console.log('The release have been tracked!')

    console.log('Capturing error...')
    opbeat.captureError(new Error('This is an Error object'), function (err, url) {
      if (err) console.log('Something went wrong:', err.message)
      console.log('The error have been logged at:', url)

      console.log('Capturing message...')
      opbeat.captureError('This is a string', function (err, url) {
        if (err) console.log('Something went wrong:', err.message)
        console.log('The message have been logged at:', url)

        console.log('Throwing exception...')
        throw new Error('This Error was thrown')
      })
    })
  })
}

var httpTest = function () {
  var http = require('http')

  var server1 = http.createServer(function (req, res) {
    var err = new Error('This is a request related error')
    opbeat.captureError(err, function (err, url) {
      if (err) console.log('Something went wrong:', err.message)
      console.log('The error have been logged at:', url)
      res.end()

      testServer2()
    })
    res.writeHead(500)
  })

  var server2 = http.createServer()

  server2.on('request', function (req, res) {
    switch (req.url) {
      case '/error':
        var err = new Error('This is a request related error')
        opbeat.captureError(err, function (err, url) {
          if (err) console.log('Something went wrong:', err.message)
          console.log('The error have been logged at:', url)
          res.end()
        })
        res.writeHead(500)
        break
      case '/throw':
        throw new Error('This Error was thrown from wihtin a http server')
    }
  })

  testServer1()

  function testServer1 () {
    server1.listen(function () {
      var port = server1.address().port
      var base = 'http://localhost:' + port
      console.log('Test server running on port', port)

      console.log('Capturing request error...')
      http.get(base + '/error')
    })
  }

  function testServer2 () {
    server2.listen(function () {
      var port = server2.address().port
      var base = 'http://localhost:' + port
      console.log('Test server running on port', port)

      console.log('Capturing request error...')
      http.get(base + '/error', function (res) {
        console.log('Throwing http exception...')
        http.get(base + '/throw')
      })
    })
  }
}

var restifyTest = function () {
  var restify = require('restify')

  var server = restify.createServer({ name: 'foo', version: '1.0.0' })

  server.on('uncaughtException', function (req, res, route, err) {
    opbeat.captureError(err, function (err, url) {
      if (err) console.log('Something went wrong:', err.message)
      console.log('The error have been logged at:', url)
      process.exit()
    })
  })

  server.get('/error', function (req, res, next) {
    var err = new Error('This is a request related error')
    opbeat.captureError(err, function (err, url) {
      if (err) console.log('Something went wrong:', err.message)
      console.log('The error have been logged at:', url)
      res.end()
      next()
    })
    res.writeHead(500)
  })

  server.get('/throw', function (req, res, next) {
    throw new Error('This Error was thrown from wihtin a http server')
  })

  server.listen(function () {
    var port = server.address().port
    var base = 'http://localhost:' + port
    console.log('Test server running on port', port)

    var client = restify.createJsonClient({
      url: base,
      version: '~1.0'
    })

    console.log('Capturing request error...')
    client.get('/error', function (err, req, res, obj) { // eslint-disable-line handle-callback-err
      console.log('Throwing http exception...')
      client.get('/throw', function () {})
    })
  })
}

var connectTest = function () {
  var http = require('http')
  var connect = require('connect')

  var testsLeft = 2
  var app = connect()
  app.use(function (req, res, next) {
    switch (req.url) {
      case '/error':
        res.writeHead(500)
        res.end()
        next(new Error('foobar'))
        break
      case '/throw':
        throw new Error('foobar')
      default:
        res.end()
    }
  })
  app.use(opbeat.middleware.connect())
  app.use(function (err, req, res, next) { // eslint-disable-line handle-callback-err
    if (!--testsLeft) process.exit()
  })

  var server = http.createServer(app)
  server.listen(function () {
    var port = server.address().port
    var base = 'http://localhost:' + port
    console.log('Test server running on port', port)
    console.log('NOTE: No Opbeat error urls will be displayed during this test!')

    console.log('Capturing request error...')
    http.get(base + '/error', function (res) {
      console.log('Throwing http exception...')
      http.get(base + '/throw', function () {})
    })
  })
}

var expressTest = function () {
  var http = require('http')
  var express = require('express')

  var testsLeft = 2
  var app = express()

  app.use(function (req, res, next) {
    if (req.url === '/error') var err = new Error('foobar')
    next(err)
  })
  app.get('/throw', function (req, res) {
    throw new Error('foobar')
  })
  app.use(opbeat.middleware.express())
  app.use(function (err, req, res, next) {
    if (!err) return
    if (!res.headersSent) {
      res.writeHead(500)
      res.end()
    }
    if (!--testsLeft) process.exit()
  })

  var server = app.listen(function () {
    var port = server.address().port
    var base = 'http://localhost:' + port
    console.log('Test server running on port', port)
    console.log('NOTE: No Opbeat error urls will be displayed during this test!')

    console.log('Capturing request error...')
    http.get(base + '/error', function (res) {
      console.log('Throwing http exception...')
      http.get(base + '/throw', function () {})
    })
  })
}

var transactionTest = function () {
  console.log('Tracking transaction...')
  var maxSeconds = 55
  var start = Date.now()

  makeTransaction()

  function makeTransaction () {
    if ((Date.now() - start) / 1000 > maxSeconds) {
      console.log('Done making transactions')
      return
    }

    console.log('Starting new transaction')

    var trans = opbeat.startTransaction('foo', 'bar')
    var t1 = opbeat.buildTrace()
    t1.start('sig1', 'foo.bar.baz1')
    var t2 = opbeat.buildTrace()
    t2.start('sig2', 'foo.bar.baz1')

    setTimeout(function () {
      var t3 = opbeat.buildTrace()
      t3.start('sig3', 'foo.bar.baz2')
      setTimeout(function () {
        var t4 = opbeat.buildTrace()
        t4.start('sig4', 'foo.bar.baz3')
        setTimeout(function () {
          t3.end()
          t4.end()
          t1.end()
        }, Math.random() * 100 + 50)
      }, Math.random() * 100 + 50)
    }, Math.random() * 100 + 25)

    setTimeout(function () {
      var t5 = opbeat.buildTrace()
      t5.start('sig5', 'foo.bar.baz2')
      setTimeout(function () {
        var t6 = opbeat.buildTrace()
        t6.start('sig6', 'foo.bar.baz4')
        setTimeout(function () {
          t6.end()
          t5.end()
          t2.end()
        }, Math.random() * 100 + 50)
      }, Math.random() * 100 + 50)
    }, Math.random() * 100 + 50)

    setTimeout(function () {
      trans.result = Math.round(Math.random() * 350 + 200)
      trans.result = 204

      console.log('Ending transaction')
      trans.end()
    }, 500)

    setTimeout(makeTransaction, Math.random() * 300 + 200)
  }
}

var test = function (suite, opts) {
  opts.env = 'production'
  opts.logLevel = 'fatal'
  opts.captureExceptions = false
  opbeat.start(opts)

  opbeat.handleUncaughtExceptions(function (err, url) { // eslint-disable-line handle-callback-err
    console.log('The uncaught exception have been logged at:', url)
    process.exit()
  })

  opbeat.on('error', function (err) {
    console.log(err.stack)
  })

  switch (suite) {
    case 'standard': return standardTest()
    case 'http': return httpTest()
    case 'restify': return restifyTest()
    case 'connect': return connectTest()
    case 'express': return expressTest()
    case 'transaction': return transactionTest()
    default: console.log('Unknown test suite selected:', suite)
  }
}

var loadConf = function (cb) {
  var file = untildify('~/.config/opbeat.json')
  fs.exists(file, function (exists) {
    if (!exists) return cb({})
    fs.readFile(file, function (err, data) {
      if (err) throw err
      cb(JSON.parse(data))
    })
  })
}

var saveConf = function (conf, cb) {
  var dir = untildify('~/.config')
  mkdirp(dir, '0755', function (err) {
    if (err) throw err
    var file = path.join(dir, 'opbeat.json')
    fs.writeFile(file, JSON.stringify(conf), function (err) {
      if (err) throw err
      console.log('Saved config:', file)
      cb()
    })
  })
}

loadConf(function (conf) {
  var questions = [
    { name: 'appId', message: 'App ID', 'default': conf.appId },
    { name: 'organizationId', message: 'Organization ID', 'default': conf.organizationId },
    { name: 'secretToken', message: 'Secret token', 'default': conf.secretToken },
    { name: 'suite', message: 'Test suite', type: 'list', choices: ['standard', 'http', 'restify', 'connect', 'express', 'transaction'] },
    { name: 'save', message: 'Save answers?', type: 'confirm' }
  ]

  inquirer.prompt(questions, function (answers) {
    var suite = answers.suite
    var save = answers.save
    delete answers.suite
    delete answers.save

    if (save) saveConf(answers, test.bind(null, suite, answers))
    else process.nextTick(test.bind(null, suite, answers)) // inquirer gives quite a long stack-trace, so let's do this async
  })
})
<|endoftext|>


<commit_before>const Discord = require('discord.js');
module.exports = async function (message, hotline){
    let me = message.embeds.shift();
    const embed = new Discord.RichEmbed();
    if(message.webhookID || message.webhookID !=null)
    {
        const webhook = await message.fetchWebhook();
        if(webhook.name && webhook.name!=null)
            embed.setAuthor(webhook.name, webhook.avatar||false)
    }
    else
    {
        embed.setAuthor(message.author.username, message.author.avatarURL)
    }
    if (!hotline)
        embed.setTitle((message.guild)?(message.channel.name + " in " + message.guild.name):(" in a DM with " + message.channel.recipient.tag));
    if (!message.content.trim() == "")
        embed.setDescription(message.cleanContent);
    else
        embed.setDescription("**" + (( me.author && me.author!=null)?(me.author.name+ " : "):"")  + ((me.title && me.title!=null)?me.title:"") + "**\n	" + (me.description || "") + ((me.footer) ? ("\n*At " + me.footer.text + "*") : ""));
    if (!hotline)
        embed.setTimestamp(message.createdAt)
    let color = message.member;
    if (color) {
        color = color.roles.filter((r) => {
            if (r.color !== 0)
                return r;
        }).array().sort((r1, r2) => {
            if (r1.position < r2.position)
                return 1;
        }).shift();
        if (color)
            color = color.color;
    }
    else
        color = 0;
    embed.setColor(color);
    //embed.setTitle("Quote");
    return embed;
}
<commit_msg>just return embed for embed quote<commit_after>const Discord = require('discord.js');
module.exports = async function (message, hotline){
    let me = message.embeds.shift();
    if(me && me!=null)
    {
        return me;
    }
    const embed = new Discord.RichEmbed();
    embed.setAuthor(message.author.username, message.author.avatarURL)
    if (!hotline)
        embed.setTitle((message.guild)?(message.channel.name + " in " + message.guild.name):(" in a DM with " + message.channel.recipient.tag));
    if (!message.content.trim() == "")
        embed.setDescription(message.cleanContent);
    else
        embed.setDescription("**" + (( me.author && me.author!=null)?(me.author.name+ " : "):"")  + ((me.title && me.title!=null)?me.title:"") + "**\n	" + (me.description || "") + ((me.footer) ? ("\n*At " + me.footer.text + "*") : ""));
    if (!hotline)
        embed.setTimestamp(message.createdAt)
    let color = message.member;
    if (color) {
        color = color.roles.filter((r) => {
            if (r.color !== 0)
                return r;
        }).array().sort((r1, r2) => {
            if (r1.position < r2.position)
                return 1;
        }).shift();
        if (color)
            color = color.color;
    }
    else
        color = 0;
    embed.setColor(color);
    //embed.setTitle("Quote");
    return embed;
}
<|endoftext|>


<commit_before>/**
 * This test contains everything related to edge and lambda functions such as
 * functions-manifest.
 */

import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild } from './utils'

export default function (context) {
  it('should not generate functions manifest when filesystem API is not enabled', async () => {
    await nextBuild(context.appDir)
    const functionsManifestPath = join(
      context.distDir,
      'server',
      'functions-manifest.json'
    )
    await fs.remove(join(context.appDir, '.next'))
    expect(fs.existsSync(functionsManifestPath)).toBe(false)
  })
  it('should contain rsc paths in functions manifest', async () => {
    await nextBuild(context.appDir, { env: { ENABLE_FILE_SYSTEM_API: '1' } })
    const functionsManifestPath = join(
      context.distDir,
      'server',
      'functions-manifest.json'
    )
    const content = JSON.parse(fs.readFileSync(functionsManifestPath, 'utf8'))
    const { pages } = content
    const pageNames = Object.keys(pages)

    const paths = ['/', '/next-api/link', '/routes/[dynamic]']
    paths.forEach((path) => {
      const { runtime, files } = pages[path]
      expect(pageNames).toContain(path)
      // Runtime of page `/` is undefined since it's configured as nodejs.
      expect(runtime).toBe(path === '/' ? undefined : 'web')
      expect(files.every((f) => f.startsWith('server/'))).toBe(true)
    })

    expect(content.version).toBe(1)
  })
}
<commit_msg>Fix functions manifest test (#34092)<commit_after>/**
 * This test contains everything related to edge and lambda functions such as
 * functions-manifest.
 */

import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild } from './utils'

export default function (context) {
  it('should not generate functions manifest when filesystem API is not enabled', async () => {
    // Make sure there is no existing functions manifest (caused by failed tests etc).
    await fs.remove(join(context.appDir, '.next'))
    await nextBuild(context.appDir)
    const functionsManifestPath = join(
      context.distDir,
      'server',
      'functions-manifest.json'
    )
    expect(fs.existsSync(functionsManifestPath)).toBe(false)
    await fs.remove(join(context.appDir, '.next'))
  })
  it('should contain rsc paths in functions manifest', async () => {
    await nextBuild(context.appDir, { env: { ENABLE_FILE_SYSTEM_API: '1' } })
    const functionsManifestPath = join(
      context.distDir,
      'server',
      'functions-manifest.json'
    )
    const content = JSON.parse(fs.readFileSync(functionsManifestPath, 'utf8'))
    const { pages } = content
    const pageNames = Object.keys(pages)

    const paths = ['/', '/next-api/link', '/routes/[dynamic]']
    paths.forEach((path) => {
      const { runtime, files } = pages[path]
      expect(pageNames).toContain(path)
      // Runtime of page `/` is undefined since it's configured as nodejs.
      expect(runtime).toBe(path === '/' ? undefined : 'web')
      expect(files.every((f) => f.startsWith('server/'))).toBe(true)
    })

    expect(content.version).toBe(1)
  })
}
<|endoftext|>


<commit_before>var express = require('express')
var hal = require('express-hal');
var app = express()

app.use(hal.middleware);

app.get('/', function (req, res) {
  res.type('application/hal+json').hal({
    links: {
      self: '/'
    }
  });
})

var server = app.listen(3000, function () {

  var host = server.address().address
  var port = server.address().port

  console.log('Example app listening at http://%s:%s', host, port)
})
<commit_msg>Fix style issues w/ spec server.<commit_after>'use strict';

var express = require('express');
var hal = require('express-hal');
var app = express();

app.use(hal.middleware);

app.get('/', function (req, res) {
  res.type('application/hal+json').hal({
    links: {
      self: '/'
    }
  });
});

var server = app.listen(3000, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>var path = require('path'),
    sys = require('sys'),
    assert = require('assert'),
    fs = require('fs');

var mess = require('mess');
var tree = require('mess/tree');
var helper = require('./support/helper');

function cleanupItem(key, value) {
    if (!key) return value.map(function(item) { return item.selector });
    else if (key === 'elements') return value.map(function(item) { return item.value; });
    else if (key === 'filters' && !value.length) return undefined;
    else if (key === 'attachment' && value === '__default__') return undefined;
    else if (key === 'index') return undefined;
    else if (key === 'range') return value.map(function(v) { return 0 + v; }).join('');
    else if (key === 'op') return value.value;
    else if (key === 'val') return value.value;
    else return value;
}

helper.files('specificity', 'mss', function(file) {
    exports['test ' + file] = function(beforeExit) {
        helper.file(file, function(content) {
            new mess.Parser({
                paths: [ path.dirname(file) ],
                filename: file
            }).parse(content, function (err, tree) {
                if (err) throw err;

                var mss = tree.toList();
                mss = helper.makePlain(mss, cleanupItem);

                helper.compareToFile(mss, file, helper.resultFile(file));
            });
        });
    }
});
<commit_msg>pass in an env object<commit_after>var path = require('path'),
    sys = require('sys'),
    assert = require('assert'),
    fs = require('fs');

var mess = require('mess');
var tree = require('mess/tree');
var helper = require('./support/helper');

function cleanupItem(key, value) {
    if (!key) return value.map(function(item) { return item.selector });
    else if (key === 'elements') return value.map(function(item) { return item.value; });
    else if (key === 'filters' && !value.length) return undefined;
    else if (key === 'attachment' && value === '__default__') return undefined;
    else if (key === 'index') return undefined;
    else if (key === 'range') return value.map(function(v) { return 0 + v; }).join('');
    else if (key === 'op') return value.value;
    else if (key === 'val') return value.value;
    else return value;
}

helper.files('specificity', 'mss', function(file) {
    exports['test ' + file] = function(beforeExit) {
        helper.file(file, function(content) {
            new mess.Parser({
                paths: [ path.dirname(file) ],
                filename: file
            }).parse(content, function (err, tree) {
                if (err) throw err;

                var mss = tree.toList({});
                mss = helper.makePlain(mss, cleanupItem);

                helper.compareToFile(mss, file, helper.resultFile(file));
            });
        });
    }
});
<|endoftext|>


<commit_before>var path = require('path'),
    sys = require('sys'),
    assert = require('assert'),
    fs = require('fs');

var mess = require('mess');
var tree = require('mess/tree');
var helper = require('./support/helper');

function cleanupItem(item) {
    // Remove indexes; we don't care about the exact byte number.
    delete item.selector.index;
    for (var i = 0; i < item.selector.filters.length; i++) {
        delete item.selector.filters[i].index;
    }
    // Also flatten the elements array a bit, we only care about
    // the actual selector.
    item.selector.elements = item.selector.elements.map(function(el) {
        return el.value;
    });
    return item.selector.filters.length ? item.selector : item.selector.elements;
}

helper.files('specificity', 'mss', function(file) {
    exports['test ' + file] = function(beforeExit) {
        helper.file(file, function(content) {
            new mess.Parser({
                paths: [ path.dirname(file) ],
                filename: file
            }).parse(content, function (err, tree) {
                if (err) throw err;

                var mss = tree.toMSS();
                mss = mss.map(cleanupItem);
                mss = helper.makePlain(mss);

                helper.compareToFile(mss, file, helper.resultFile(file));
            });
        });
    }
});
<commit_msg>Fixing spec test for toMSS - toList transition<commit_after>var path = require('path'),
    sys = require('sys'),
    assert = require('assert'),
    fs = require('fs');

var mess = require('mess');
var tree = require('mess/tree');
var helper = require('./support/helper');

function cleanupItem(item) {
    // Remove indexes; we don't care about the exact byte number.
    delete item.selector.index;
    for (var i = 0; i < item.selector.filters.length; i++) {
        delete item.selector.filters[i].index;
    }
    // Also flatten the elements array a bit, we only care about
    // the actual selector.
    item.selector.elements = item.selector.elements.map(function(el) {
        return el.value;
    });
    return item.selector.filters.length ? item.selector : item.selector.elements;
}

helper.files('specificity', 'mss', function(file) {
    exports['test ' + file] = function(beforeExit) {
        helper.file(file, function(content) {
            new mess.Parser({
                paths: [ path.dirname(file) ],
                filename: file
            }).parse(content, function (err, tree) {
                if (err) throw err;

                var mss = tree.toList();
                mss = mss.map(cleanupItem);
                mss = helper.makePlain(mss);

                helper.compareToFile(mss, file, helper.resultFile(file));
            });
        });
    }
});
<|endoftext|>


<commit_before>describe("Model", function(){
  var Asset;

  beforeEach(function(){
    Asset = Spine.Model.setup("Asset", ["name"]);
  });

  it("can create records", function(){
    var asset = Asset.create({name: "test.pdf"});
    expect(Asset.first()).toEqual(asset);
  });

  it("can update records", function(){
    var asset = Asset.create({name: "test.pdf"});

    expect(Asset.first().name).toEqual("test.pdf");

    asset.name = "wem.pdf";
    asset.save();

    expect(Asset.first().name).toEqual("wem.pdf");
  });

  it("can destroy records", function(){
    var asset = Asset.create({name: "test.pdf"});

    expect(Asset.first()).toEqual(asset);
    asset.destroy();
    expect(Asset.first()).toBeFalsy();
  });

  it("can find records", function(){
    var asset = Asset.create({name: "test.pdf"});
    expect(Asset.find(asset.id)).toBeTruthy();

    asset.destroy();
    expect(function(){
      Asset.find(asset.id);
    }).toThrow();
  });

  it("can check existence", function(){
    var asset = Asset.create({name: "test.pdf"});

    expect(asset.exists()).toBeTruthy();
    expect(Asset.exists(asset.id)).toBeTruthy();

    asset.destroy();

    expect(asset.exists()).toBeFalsy();
    expect(Asset.exists(asset.id)).toBeFalsy();
  });

  it("can reload", function(){
    var asset = Asset.create({name: "test.pdf"}).dup(false);

    Asset.find(asset.id).updateAttributes({name: "foo.pdf"});

    expect(asset.name).toEqual("test.pdf");
    var original = asset.reload();
    expect(asset.name).toEqual("foo.pdf");

    // Reload should return a clone, more useful that way
    expect(original.__proto__.__proto__).toEqual(Asset.prototype)
  });

  it("can select records", function(){
    var asset1 = Asset.create({name: "test.pdf"});
    var asset2 = Asset.create({name: "foo.pdf"});

    var selected = Asset.select(function(rec){ return rec.name == "foo.pdf" });

    expect(selected).toEqual([asset2]);
  });

  it("can return all records", function(){
    var asset1 = Asset.create({name: "test.pdf"});
    var asset2 = Asset.create({name: "foo.pdf"});

    expect(Asset.all()).toEqual([asset1, asset2]);
  });

  it("can find records by attribute", function(){
    var asset = Asset.create({name: "foo.pdf"});
    Asset.create({name: "test.pdf"});

    var findOne = Asset.findByAttribute("name", "foo.pdf");
    expect(findOne).toEqual(asset);

    var findAll = Asset.findAllByAttribute("name", "foo.pdf");
    expect(findAll).toEqual([asset]);
  });

  it("can find first/last record", function(){
    var first = Asset.create({name: "foo.pdf"});
    Asset.create({name: "test.pdf"});
    var last = Asset.create({name: "wem.pdf"});

    expect(Asset.first()).toEqual(first);
    expect(Asset.last()).toEqual(last);
  });

  it("can destroy all records", function(){
    Asset.create({name: "foo.pdf"});
    Asset.create({name: "foo.pdf"});

    expect(Asset.count()).toEqual(2);
    Asset.destroyAll();
    expect(Asset.count()).toEqual(0);
  });

  it("can delete all records", function(){
    Asset.create({name: "foo.pdf"});
    Asset.create({name: "foo.pdf"});

    expect(Asset.count()).toEqual(2);
    Asset.deleteAll();
    expect(Asset.count()).toEqual(0);
  });

  it("can be serialized into JSON", function(){
    var asset = new Asset({name: "Johnson me!"});

    expect(JSON.stringify(asset)).toEqual('{"name":"Johnson me!"}');
  });

  it("can be deserialized from JSON", function(){
    var asset = Asset.fromJSON('{"name":"Un-Johnson me!"}')
    expect(asset.name).toEqual("Un-Johnson me!");

    var assets = Asset.fromJSON('[{"name":"Un-Johnson me!"}]')
    expect(assets[0] && assets[0].name).toEqual("Un-Johnson me!");
  });

  it("can be instantiated from a form", function(){
    var form = $('<form />');
    form.append('<input name="name" value="bar" />');
    var asset = Asset.fromForm(form);
    expect(asset.name).toEqual("bar");
  });

  it("can validate", function(){
    Asset.include({
      validate: function(){
        if ( !this.name )
          return "Name required";
      }
    });

    expect(Asset.create({name: ""})).toBeFalsy();
    expect(new Asset({name: ""}).isValid()).toBeFalsy();

    expect(Asset.create({name: "Yo big dog"})).toBeTruthy();
    expect(new Asset({name: "Yo big dog"}).isValid()).toBeTruthy();
  });

  it("validation can be disabled", function(){
    Asset.include({
      validate: function(){
        if ( !this.name )
          return "Name required";
      }
    });

    var asset = new Asset;
    expect(asset.save()).toBeFalsy();
    expect(asset.save({validate: false})).toBeTruthy();
  });

  it("has attribute hash", function(){
    var asset = new Asset({name: "wazzzup!"});
    expect(asset.attributes()).toEqual({name: "wazzzup!"});
  });

  it("attributes() should not return undefined atts", function(){
    var asset = new Asset();
    expect(asset.attributes()).toEqual({});
  });

  it("can load attributes()", function(){
    var asset = new Asset();
    var result = asset.load({name: "In da' house"});
    expect(result).toBe(asset);
    expect(asset.name).toEqual("In da' house");
  });

  it("can load() attributes respecting getters/setters", function(){
    Asset.include({
      name: function(value){
        var ref = value.split(' ', 2);
        this.first_name = ref[0];
        this.last_name  = ref[1];
      }
    })

    var asset = new Asset();
    asset.load({name: "Alex MacCaw"});
    expect(asset.first_name).toEqual("Alex");
    expect(asset.last_name).toEqual("MacCaw");
  });

  it("attributes() respecting getters/setters", function(){
    Asset.include({
      name: function(){
        return "Bob";
      }
    })

    var asset = new Asset();
    expect(asset.attributes()).toEqual({name: "Bob"});
  });

  it("can generate ID", function(){
    var asset = Asset.create({name: "who's in the house?"});
    expect(asset.id).toBeTruthy();
  });

  it("can be duplicated", function(){
    var asset = Asset.create({name: "who's your daddy?"});
    expect(asset.dup().__proto__).toBe(Asset.prototype);

    expect(asset.name).toEqual("who's your daddy?");
    asset.name = "I am your father";
    expect(asset.reload().name).toBe("who's your daddy?");

    expect(asset).not.toBe(Asset.records[asset.id]);
  });

  it("can be cloned", function(){
    var asset = Asset.create({name: "what's cooler than cool?"}).dup(false);
    expect(asset.clone().__proto__).not.toBe(Asset.prototype);
    expect(asset.clone().__proto__.__proto__).toBe(Asset.prototype);

    expect(asset.name).toEqual("what's cooler than cool?");
    asset.name = "ice cold";
    expect(asset.reload().name).toBe("what's cooler than cool?");
  });

  it("clones are dynamic", function(){
    var asset = Asset.create({name: "hotel california"});

    // reload reference
    var clone = Asset.find(asset.id);

    asset.name = "checkout anytime";
    asset.save();

    expect(clone.name).toEqual("checkout anytime");
  });

  it("create or save should return a clone", function(){
    var asset = Asset.create({name: "what's cooler than cool?"});
    expect(asset.__proto__).not.toBe(Asset.prototype);
    expect(asset.__proto__.__proto__).toBe(Asset.prototype);
  });

  it("should be able to be subclassed", function(){
    Asset.extend({
      aProperty: true
    });

    var File = Asset.setup("File");

    expect(File.aProperty).toBeTruthy();
    expect(File.className).toBe("File");

    expect(File.attributes).toEqual(Asset.attributes);
  });

  it("dup should take a newRecord argument, which controls if a new record is returned", function(){
    var asset = Asset.create({name: "hotel california"});
    expect(asset.dup().id).toBeUndefined();
    expect(asset.dup().isNew()).toBeTruthy();

    expect(asset.dup(false).id).toBe(asset.id);
    expect(asset.dup(false).newRecord).toBeFalsy();
  });

  it("should be able to change ID", function(){
    var asset = Asset.create({name: "hotel california"});
    expect(asset.id).toBeTruthy();
    asset.changeID("foo");
    expect(asset.id).toBe("foo");

    expect(Asset.exists("foo")).toBeTruthy();
  });

  it("eql should respect ID changes", function(){
    var asset1 = Asset.create({name: "hotel california", id: "bar"});
    var asset2 = asset1.dup(false);

    asset1.changeID("foo");
    expect(asset1.eql(asset2)).toBeTruthy();
  });

  it("new records should not be eql", function(){
    var asset1 = new Asset;
    var asset2 = new Asset;
    expect(asset1.eql(asset2)).not.toBeTruthy();
  });

  it("should generate unique cIDs", function(){
      Asset.refresh({name: "Bob", id: 3});
      Asset.refresh({name: "Bob", id: 2});
      Asset.refresh({name: "Bob", id: 1});
      expect(Asset.find(2).eql(Asset.find(1))).not.toBeTruthy();
  });

  it("should handle more than 10 cIDs correctly", function(){
      for (i=0; i < 12; i++) {
        Asset.refresh({name: "Bob", id: i});
      }
      expect(Asset.idCounter).toEqual(12);
  });

  describe("with spy", function(){
    var spy;

    beforeEach(function(){
      var noop = {spy: function(){}};
      spyOn(noop, "spy");
      spy = noop.spy;
    });

    it("can interate over records", function(){
      var asset1 = Asset.create({name: "test.pdf"});
      var asset2 = Asset.create({name: "foo.pdf"});

      Asset.each(spy);
      expect(spy).toHaveBeenCalledWith(asset1);
      expect(spy).toHaveBeenCalledWith(asset2);
    });

    it("can fire create events", function(){
      Asset.bind("create", spy);
      var asset = Asset.create({name: "cartoon world.png"});
      expect(spy).toHaveBeenCalledWith(asset, {});
    });

    it("can fire save events", function(){
      Asset.bind("save", spy);
      var asset = Asset.create({name: "cartoon world.png"});
      expect(spy).toHaveBeenCalledWith(asset, {});

      asset.save();
      expect(spy).toHaveBeenCalled();
    });

    it("can fire update events", function(){
      Asset.bind("update", spy);

      var asset = Asset.create({name: "cartoon world.png"});
      expect(spy).not.toHaveBeenCalledWith(asset);

      asset.save();
      expect(spy).toHaveBeenCalledWith(asset, {});
    });

    it("can fire destroy events", function(){
      Asset.bind("destroy", spy);
      var asset = Asset.create({name: "cartoon world.png"});
      asset.destroy();
      expect(spy).toHaveBeenCalledWith(asset, {});
    });

    it("can fire events on record", function(){
      var asset = Asset.create({name: "cartoon world.png"});
      asset.bind("save", spy);
      asset.save();
      expect(spy).toHaveBeenCalledWith(asset, {});
    });

    it("can fire change events on record", function(){
      Asset.bind("change", spy);

      var asset = Asset.create({name: "cartoon world.png"});
      expect(spy).toHaveBeenCalledWith(asset, "create", {});

      asset.save();
      expect(spy).toHaveBeenCalledWith(asset, "update", {});

      asset.destroy();
      expect(spy).toHaveBeenCalledWith(asset, "destroy", {});
    });

    it("can fire error events", function(){
      Asset.bind("error", spy);

      Asset.include({
        validate: function(){
          if ( !this.name )
            return "Name required";
        }
      });

      var asset = new Asset({name: ""});
      expect(asset.save()).toBeFalsy();
      expect(spy).toHaveBeenCalledWith(asset, "Name required");
    });

    it("should be able to bind once", function(){
      Asset.one("save", spy);

      var asset = new Asset({name: "cartoon world.png"});
      asset.save();

      expect(spy).toHaveBeenCalledWith(asset, {});
      spy.reset();

      asset.save();
      expect(spy).not.toHaveBeenCalled();
    });

    it("should be able to bind once on instance", function(){
      var asset = Asset.create({name: "cartoon world.png"});

      asset.one("save", spy);
      asset.save();

      expect(spy).toHaveBeenCalledWith(asset, {});
      spy.reset();

      asset.save();
      expect(spy).not.toHaveBeenCalled();
    });

    it("it should pass clones with events", function(){
      Asset.bind("create", function(asset){
        expect(asset.__proto__).not.toBe(Asset.prototype);
        expect(asset.__proto__.__proto__).toBe(Asset.prototype);
      });

      Asset.bind("update", function(asset){
        expect(asset.__proto__).not.toBe(Asset.prototype);
        expect(asset.__proto__.__proto__).toBe(Asset.prototype);
      });
      var asset = Asset.create({name: "cartoon world.png"});
      asset.updateAttributes({name: "lonely heart.png"});
    });

    it("should be able to unbind instance events", function(){
      var asset = Asset.create({name: "cartoon world.png"});

      asset.bind("save", spy);
      asset.unbind();
      asset.save();

      expect(spy).not.toHaveBeenCalled();
    });

    it("should unbind events on instance destroy", function(){
      var asset = Asset.create({name: "cartoon world.png"});

      asset.bind("save", spy);
      asset.destroy();

      asset.trigger("save", asset);
      expect(spy).not.toHaveBeenCalled();
    });

    it("callbacks should still work on ID changes", function(){
      var asset = Asset.create({name: "hotel california", id: "bar"});
      asset.bind("test", spy);
      asset.changeID("foo");

      asset = Asset.find("foo");
      asset.trigger("test", asset);
      expect(spy).toHaveBeenCalled();
    })
  });
});<commit_msg>Test case for #219.<commit_after>describe("Model", function(){
  var Asset;

  beforeEach(function(){
    Asset = Spine.Model.setup("Asset", ["name"]);
  });

  it("can create records", function(){
    var asset = Asset.create({name: "test.pdf"});
    expect(Asset.first()).toEqual(asset);
  });

  it("can update records", function(){
    var asset = Asset.create({name: "test.pdf"});

    expect(Asset.first().name).toEqual("test.pdf");

    asset.name = "wem.pdf";
    asset.save();

    expect(Asset.first().name).toEqual("wem.pdf");
  });

  it("can destroy records", function(){
    var asset = Asset.create({name: "test.pdf"});

    expect(Asset.first()).toEqual(asset);
    asset.destroy();
    expect(Asset.first()).toBeFalsy();
  });

  it("can find records", function(){
    var asset = Asset.create({name: "test.pdf"});
    expect(Asset.find(asset.id)).toBeTruthy();

    asset.destroy();
    expect(function(){
      Asset.find(asset.id);
    }).toThrow();
  });

  it("can check existence", function(){
    var asset = Asset.create({name: "test.pdf"});

    expect(asset.exists()).toBeTruthy();
    expect(Asset.exists(asset.id)).toBeTruthy();

    asset.destroy();

    expect(asset.exists()).toBeFalsy();
    expect(Asset.exists(asset.id)).toBeFalsy();
  });

  it("can reload", function(){
    var asset = Asset.create({name: "test.pdf"}).dup(false);

    Asset.find(asset.id).updateAttributes({name: "foo.pdf"});

    expect(asset.name).toEqual("test.pdf");
    var original = asset.reload();
    expect(asset.name).toEqual("foo.pdf");

    // Reload should return a clone, more useful that way
    expect(original.__proto__.__proto__).toEqual(Asset.prototype)
  });

  it("can select records", function(){
    var asset1 = Asset.create({name: "test.pdf"});
    var asset2 = Asset.create({name: "foo.pdf"});

    var selected = Asset.select(function(rec){ return rec.name == "foo.pdf" });

    expect(selected).toEqual([asset2]);
  });

  it("can return all records", function(){
    var asset1 = Asset.create({name: "test.pdf"});
    var asset2 = Asset.create({name: "foo.pdf"});

    expect(Asset.all()).toEqual([asset1, asset2]);
  });

  it("can find records by attribute", function(){
    var asset = Asset.create({name: "foo.pdf"});
    Asset.create({name: "test.pdf"});

    var findOne = Asset.findByAttribute("name", "foo.pdf");
    expect(findOne).toEqual(asset);

    var findAll = Asset.findAllByAttribute("name", "foo.pdf");
    expect(findAll).toEqual([asset]);
  });

  it("can find first/last record", function(){
    var first = Asset.create({name: "foo.pdf"});
    Asset.create({name: "test.pdf"});
    var last = Asset.create({name: "wem.pdf"});

    expect(Asset.first()).toEqual(first);
    expect(Asset.last()).toEqual(last);
  });

  it("can destroy all records", function(){
    Asset.create({name: "foo.pdf"});
    Asset.create({name: "foo.pdf"});

    expect(Asset.count()).toEqual(2);
    Asset.destroyAll();
    expect(Asset.count()).toEqual(0);
  });

  it("can delete all records", function(){
    Asset.create({name: "foo.pdf"});
    Asset.create({name: "foo.pdf"});

    expect(Asset.count()).toEqual(2);
    Asset.deleteAll();
    expect(Asset.count()).toEqual(0);
  });

  it("can be serialized into JSON", function(){
    var asset = new Asset({name: "Johnson me!"});

    expect(JSON.stringify(asset)).toEqual('{"name":"Johnson me!"}');
  });

  it("can be deserialized from JSON", function(){
    var asset = Asset.fromJSON('{"name":"Un-Johnson me!"}')
    expect(asset.name).toEqual("Un-Johnson me!");

    var assets = Asset.fromJSON('[{"name":"Un-Johnson me!"}]')
    expect(assets[0] && assets[0].name).toEqual("Un-Johnson me!");
  });

  it("can be instantiated from a form", function(){
    var form = $('<form />');
    form.append('<input name="name" value="bar" />');
    var asset = Asset.fromForm(form);
    expect(asset.name).toEqual("bar");
  });

  it("can validate", function(){
    Asset.include({
      validate: function(){
        if ( !this.name )
          return "Name required";
      }
    });

    expect(Asset.create({name: ""})).toBeFalsy();
    expect(new Asset({name: ""}).isValid()).toBeFalsy();

    expect(Asset.create({name: "Yo big dog"})).toBeTruthy();
    expect(new Asset({name: "Yo big dog"}).isValid()).toBeTruthy();
  });

  it("validation can be disabled", function(){
    Asset.include({
      validate: function(){
        if ( !this.name )
          return "Name required";
      }
    });

    var asset = new Asset;
    expect(asset.save()).toBeFalsy();
    expect(asset.save({validate: false})).toBeTruthy();
  });

  it("has attribute hash", function(){
    var asset = new Asset({name: "wazzzup!"});
    expect(asset.attributes()).toEqual({name: "wazzzup!"});
  });

  it("attributes() should not return undefined atts", function(){
    var asset = new Asset();
    expect(asset.attributes()).toEqual({});
  });

  it("can load attributes()", function(){
    var asset = new Asset();
    var result = asset.load({name: "In da' house"});
    expect(result).toBe(asset);
    expect(asset.name).toEqual("In da' house");
  });

  it("can load() attributes respecting getters/setters", function(){
    Asset.include({
      name: function(value){
        var ref = value.split(' ', 2);
        this.first_name = ref[0];
        this.last_name  = ref[1];
      }
    })

    var asset = new Asset();
    asset.load({name: "Alex MacCaw"});
    expect(asset.first_name).toEqual("Alex");
    expect(asset.last_name).toEqual("MacCaw");
  });

  it("attributes() respecting getters/setters", function(){
    Asset.include({
      name: function(){
        return "Bob";
      }
    })

    var asset = new Asset();
    expect(asset.attributes()).toEqual({name: "Bob"});
  });

  it("can generate ID", function(){
    var asset = Asset.create({name: "who's in the house?"});
    expect(asset.id).toBeTruthy();
  });

  it("can be duplicated", function(){
    var asset = Asset.create({name: "who's your daddy?"});
    expect(asset.dup().__proto__).toBe(Asset.prototype);

    expect(asset.name).toEqual("who's your daddy?");
    asset.name = "I am your father";
    expect(asset.reload().name).toBe("who's your daddy?");

    expect(asset).not.toBe(Asset.records[asset.id]);
  });

  it("can be cloned", function(){
    var asset = Asset.create({name: "what's cooler than cool?"}).dup(false);
    expect(asset.clone().__proto__).not.toBe(Asset.prototype);
    expect(asset.clone().__proto__.__proto__).toBe(Asset.prototype);

    expect(asset.name).toEqual("what's cooler than cool?");
    asset.name = "ice cold";
    expect(asset.reload().name).toBe("what's cooler than cool?");
  });

  it("clones are dynamic", function(){
    var asset = Asset.create({name: "hotel california"});

    // reload reference
    var clone = Asset.find(asset.id);

    asset.name = "checkout anytime";
    asset.save();

    expect(clone.name).toEqual("checkout anytime");
  });

  it("create or save should return a clone", function(){
    var asset = Asset.create({name: "what's cooler than cool?"});
    expect(asset.__proto__).not.toBe(Asset.prototype);
    expect(asset.__proto__.__proto__).toBe(Asset.prototype);
  });

  it("should be able to be subclassed", function(){
    Asset.extend({
      aProperty: true
    });

    var File = Asset.setup("File");

    expect(File.aProperty).toBeTruthy();
    expect(File.className).toBe("File");

    expect(File.attributes).toEqual(Asset.attributes);
  });

  it("dup should take a newRecord argument, which controls if a new record is returned", function(){
    var asset = Asset.create({name: "hotel california"});
    expect(asset.dup().id).toBeUndefined();
    expect(asset.dup().isNew()).toBeTruthy();

    expect(asset.dup(false).id).toBe(asset.id);
    expect(asset.dup(false).newRecord).toBeFalsy();
  });

  it("should be able to change ID", function(){
    var asset = Asset.create({name: "hotel california"});
    expect(asset.id).toBeTruthy();
    asset.changeID("foo");
    expect(asset.id).toBe("foo");

    expect(Asset.exists("foo")).toBeTruthy();
  });

  it("eql should respect ID changes", function(){
    var asset1 = Asset.create({name: "hotel california", id: "bar"});
    var asset2 = asset1.dup(false);

    asset1.changeID("foo");
    expect(asset1.eql(asset2)).toBeTruthy();
  });

  it("new records should not be eql", function(){
    var asset1 = new Asset;
    var asset2 = new Asset;
    expect(asset1.eql(asset2)).not.toBeTruthy();
  });

  it("should generate unique cIDs", function(){
      Asset.refresh({name: "Bob", id: 3});
      Asset.refresh({name: "Bob", id: 2});
      Asset.refresh({name: "Bob", id: 1});
      expect(Asset.find(2).eql(Asset.find(1))).not.toBeTruthy();
  });

  it("should handle more than 10 cIDs correctly", function(){
      for (i=0; i < 12; i++) {
        Asset.refresh({name: "Bob", id: i});
      }
      expect(Asset.idCounter).toEqual(12);
  });

  it("should keep model references in sync", function(){
      ref1 = Asset.create({name: "Bob"});
      ref2 = Asset.all()[0]
      ref1.updateAttribute("name", "Jack");
      ref2.updateAttribute("name", "Smith");
      expect(ref2.name).toEqual(ref1.name);
  });

  describe("with spy", function(){
    var spy;

    beforeEach(function(){
      var noop = {spy: function(){}};
      spyOn(noop, "spy");
      spy = noop.spy;
    });

    it("can interate over records", function(){
      var asset1 = Asset.create({name: "test.pdf"});
      var asset2 = Asset.create({name: "foo.pdf"});

      Asset.each(spy);
      expect(spy).toHaveBeenCalledWith(asset1);
      expect(spy).toHaveBeenCalledWith(asset2);
    });

    it("can fire create events", function(){
      Asset.bind("create", spy);
      var asset = Asset.create({name: "cartoon world.png"});
      expect(spy).toHaveBeenCalledWith(asset, {});
    });

    it("can fire save events", function(){
      Asset.bind("save", spy);
      var asset = Asset.create({name: "cartoon world.png"});
      expect(spy).toHaveBeenCalledWith(asset, {});

      asset.save();
      expect(spy).toHaveBeenCalled();
    });

    it("can fire update events", function(){
      Asset.bind("update", spy);

      var asset = Asset.create({name: "cartoon world.png"});
      expect(spy).not.toHaveBeenCalledWith(asset);

      asset.save();
      expect(spy).toHaveBeenCalledWith(asset, {});
    });

    it("can fire destroy events", function(){
      Asset.bind("destroy", spy);
      var asset = Asset.create({name: "cartoon world.png"});
      asset.destroy();
      expect(spy).toHaveBeenCalledWith(asset, {});
    });

    it("can fire events on record", function(){
      var asset = Asset.create({name: "cartoon world.png"});
      asset.bind("save", spy);
      asset.save();
      expect(spy).toHaveBeenCalledWith(asset, {});
    });

    it("can fire change events on record", function(){
      Asset.bind("change", spy);

      var asset = Asset.create({name: "cartoon world.png"});
      expect(spy).toHaveBeenCalledWith(asset, "create", {});

      asset.save();
      expect(spy).toHaveBeenCalledWith(asset, "update", {});

      asset.destroy();
      expect(spy).toHaveBeenCalledWith(asset, "destroy", {});
    });

    it("can fire error events", function(){
      Asset.bind("error", spy);

      Asset.include({
        validate: function(){
          if ( !this.name )
            return "Name required";
        }
      });

      var asset = new Asset({name: ""});
      expect(asset.save()).toBeFalsy();
      expect(spy).toHaveBeenCalledWith(asset, "Name required");
    });

    it("should be able to bind once", function(){
      Asset.one("save", spy);

      var asset = new Asset({name: "cartoon world.png"});
      asset.save();

      expect(spy).toHaveBeenCalledWith(asset, {});
      spy.reset();

      asset.save();
      expect(spy).not.toHaveBeenCalled();
    });

    it("should be able to bind once on instance", function(){
      var asset = Asset.create({name: "cartoon world.png"});

      asset.one("save", spy);
      asset.save();

      expect(spy).toHaveBeenCalledWith(asset, {});
      spy.reset();

      asset.save();
      expect(spy).not.toHaveBeenCalled();
    });

    it("it should pass clones with events", function(){
      Asset.bind("create", function(asset){
        expect(asset.__proto__).not.toBe(Asset.prototype);
        expect(asset.__proto__.__proto__).toBe(Asset.prototype);
      });

      Asset.bind("update", function(asset){
        expect(asset.__proto__).not.toBe(Asset.prototype);
        expect(asset.__proto__.__proto__).toBe(Asset.prototype);
      });
      var asset = Asset.create({name: "cartoon world.png"});
      asset.updateAttributes({name: "lonely heart.png"});
    });

    it("should be able to unbind instance events", function(){
      var asset = Asset.create({name: "cartoon world.png"});

      asset.bind("save", spy);
      asset.unbind();
      asset.save();

      expect(spy).not.toHaveBeenCalled();
    });

    it("should unbind events on instance destroy", function(){
      var asset = Asset.create({name: "cartoon world.png"});

      asset.bind("save", spy);
      asset.destroy();

      asset.trigger("save", asset);
      expect(spy).not.toHaveBeenCalled();
    });

    it("callbacks should still work on ID changes", function(){
      var asset = Asset.create({name: "hotel california", id: "bar"});
      asset.bind("test", spy);
      asset.changeID("foo");

      asset = Asset.find("foo");
      asset.trigger("test", asset);
      expect(spy).toHaveBeenCalled();
    })
  });
});
<|endoftext|>


<commit_before>import test from 'ava'
import StylesLib from '../lib/styles'

const newStyles = () => new StylesLib('../templates')

test('separateStyles', async t => {
  const styles = newStyles()

  styles.css = {
    reset: {
      head: 'h1 { color: red }',
      inline: 'h2 { color: pink }'
    },
    main: {
      head: 'h3 { color: blue }',
      inline: 'h4 { color: purple }'
    }
  }

  const separatedStyles = await styles.separateStyles()

  t.deepEqual(separatedStyles.head, 'h1 { color: red }h3 { color: blue }')
  t.deepEqual(separatedStyles.inline, 'h2 { color: pink }h4 { color: purple }')
})

test('separateHeadStyles', async t => {
  const styles = newStyles()

  const css = `
        @media (max-width: 600px) {
            tr { color: yellow; }
        }
        table { background: orange; }
        @media (max-width: 600px) {
            table { background: magenta; }
        }
        a { text-decoration: none; }
        a:hover { text-decoration: underline; }
    `
  const separatedStyles = await styles.separateHeadStyles(css)

  const expectedStyles = {
    head:
      'a:hover{text-decoration:underline!important}@media (max-width:600px){tr{color:#ff0!important}table{background:#f0f!important}}',
    inline: 'table{background:orange}a{text-decoration:none}'
  }

  t.deepEqual(separatedStyles, expectedStyles)
})
<commit_msg>test: fix styles test<commit_after>import test from 'ava'
import StylesLib from '../lib/styles'

const newStyles = () => new StylesLib('../templates')

test('combineProdStyles', async t => {
  const styles = newStyles()

  styles.css = {
    reset: {
      head: 'h1 { color: red }',
      inline: 'h2 { color: pink }'
    },
    main: {
      head: 'h3 { color: blue }',
      inline: 'h4 { color: purple }'
    }
  }

  const separatedStyles = await styles.combineProdStyles()

  t.deepEqual(separatedStyles.head, 'h1 { color: red }h3 { color: blue }')
  t.deepEqual(separatedStyles.inline, 'h2 { color: pink }h4 { color: purple }')
})

test('separateHeadStyles', async t => {
  const styles = newStyles()

  const css = `
        @media (max-width: 600px) {
            tr { color: yellow; }
        }
        table { background: orange; }
        @media (max-width: 600px) {
            table { background: magenta; }
        }
        a { text-decoration: none; }
        a:hover { text-decoration: underline; }
    `
  const separatedStyles = await styles.separateHeadStyles(css)

  const expectedStyles = {
    head:
      'a:hover{text-decoration:underline!important}@media (max-width:600px){tr{color:#ff0!important}table{background:#f0f!important}}',
    inline: 'table{background:orange}a{text-decoration:none}'
  }

  t.deepEqual(separatedStyles, expectedStyles)
})
<|endoftext|>


<commit_before>var expect = chai.expect;

describe('Sudoku', function(){
  var validSet = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var invalidSet = [1, 2, 3, 5, 6, 7, 8, 13, 9];
  var origonalBoard, testboard, validBoard;
  var origonalRowSets = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
  ] ;
  var origonalColumnSets = [
    [5, 6, 0, 8, 4, 7, 0, 0, 0],
    [3, 0, 9, 0, 0, 0, 6, 0, 0],
    [0, 0, 8, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 8, 0, 0, 4, 0],
    [7, 9, 0, 6, 0, 2, 0, 1, 8],
    [0, 5, 0, 0, 3, 0, 0, 9, 0],
    [0, 0, 0, 0, 0, 0, 2, 0, 0],
    [0, 0, 6, 0, 0, 0, 8, 0, 7],
    [0, 0, 0, 3, 1, 6, 0, 5, 9]
  ];
  var origonalQuadrantSets = [
    [5, 3, 0, 6, 0, 0, 0, 9, 8],
    [0, 6, 0, 8, 0, 3, 0, 2, 0],
    [2, 8, 0, 0, 0, 5, 0, 7, 9],
    [5, 3, 0, 6, 0, 0, 0, 9, 8],
    [0, 6, 0, 8, 0, 3, 0, 2, 0],
    [2, 8, 0, 0, 0, 5, 0, 7, 9],
    [5, 3, 0, 6, 0, 0, 0, 9, 8],
    [0, 6, 0, 8, 0, 3, 0, 2, 0],
    [2, 8, 0, 0, 0, 5, 0, 7, 9]
  ]

  beforeEach(function(done){
    origonalBoard = [ 5, 3, 0, 0, 7, 0, 0, 0, 0, 6, 0, 0, 1, 9, 5, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 6, 0, 8, 0, 0, 0, 6, 0, 0, 0, 3, 4, 0, 0, 8, 0, 3, 0, 0, 1, 7, 0, 0, 0, 2, 0, 0, 0, 6, 0, 6, 0, 0, 0, 0, 2, 8, 0, 0, 0, 0, 4, 1, 9, 0, 0, 5, 0, 0, 0, 0, 8, 0, 0, 7, 9 ];
    validBoard = [ 5, 3, 4, 6, 7, 8, 9, 1, 2, 6, 7, 2, 1, 9, 5, 3, 4, 8, 1, 9, 8, 3, 4, 2, 5, 6, 7, 8, 5, 9, 7, 6, 1, 4, 2, 3, 4, 2, 6, 8, 5, 3, 7, 9, 1, 7, 1, 3, 9, 2, 4, 8, 5, 6, 9, 6, 1, 5, 3, 7, 2, 8, 4, 2, 8, 7, 4, 1, 9, 6, 3, 5, 3, 4, 5, 2, 8, 6, 1, 7, 9];
    testboard = new Sudoku(origonalBoard);
    done();
  });

  describe('isValidSet', function(){
    it('should return false for invalid set', function(){
      expect( testboard.isValidSet(invalidSet) ).to.equal(false);
    });

    it('should return true for valid set', function(){
      expect( testboard.isValidSet(validSet) ).to.equal(true);
    });
  });

  describe('getRowSets', function(){
    it('should return an array of row sets', function(){
      expect( testboard.getRowSets() ).to.deep.equal( origonalRowSets );
    })
  });

  describe('getColumnSets', function(){
    it('should return an array of column sets', function(){
      expect( testboard.getColumnSets() ).to.deep.equal( origonalColumnSets );
    })
  })

  describe('getQuadrantSets', function(){
    it('should return array of quadrant sets', function(){
      console.log(origonalQuadrantSets);
      console.log(testboard.getQuadrantSets());
      expect( testboard.getQuadrantSets() ).to.deep.equal( origonalQuadrantSets);
    });
  });

  describe('resetBoard', function(){
    it('should reset board to original state', function(){
      testboard.resetBoard()
      expect( testboard._board ).to.equal(origonalBoard);
    });
  });

});
<commit_msg>Updates tests for getQuadrantSets<commit_after>var expect = chai.expect;

describe('Sudoku', function(){
  var validSet = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var invalidSet = [1, 2, 3, 5, 6, 7, 8, 13, 9];
  var origonalBoard, testboard, validBoard;
  var origonalRowSets = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
  ] ;
  var origonalColumnSets = [
    [5, 6, 0, 8, 4, 7, 0, 0, 0],
    [3, 0, 9, 0, 0, 0, 6, 0, 0],
    [0, 0, 8, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 8, 0, 0, 4, 0],
    [7, 9, 0, 6, 0, 2, 0, 1, 8],
    [0, 5, 0, 0, 3, 0, 0, 9, 0],
    [0, 0, 0, 0, 0, 0, 2, 0, 0],
    [0, 0, 6, 0, 0, 0, 8, 0, 7],
    [0, 0, 0, 3, 1, 6, 0, 5, 9]
  ];
  var origonalQuadrantSets = [
    [5, 3, 0, 6, 0, 0, 0, 9, 8],
    [0, 7, 0, 1, 9, 5, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 4, 0, 0, 7, 0, 0],
    [0, 6, 0, 8, 0, 3, 0, 2, 0],
    [0, 0, 3, 0, 0, 1, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 4, 1, 9, 0, 8, 0],
    [2, 8, 0, 0, 0, 5, 0, 7, 9]
  ]

  beforeEach(function(done){
    origonalBoard = [ 5, 3, 0, 0, 7, 0, 0, 0, 0, 6, 0, 0, 1, 9, 5, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 6, 0, 8, 0, 0, 0, 6, 0, 0, 0, 3, 4, 0, 0, 8, 0, 3, 0, 0, 1, 7, 0, 0, 0, 2, 0, 0, 0, 6, 0, 6, 0, 0, 0, 0, 2, 8, 0, 0, 0, 0, 4, 1, 9, 0, 0, 5, 0, 0, 0, 0, 8, 0, 0, 7, 9 ];
    validBoard = [ 5, 3, 4, 6, 7, 8, 9, 1, 2, 6, 7, 2, 1, 9, 5, 3, 4, 8, 1, 9, 8, 3, 4, 2, 5, 6, 7, 8, 5, 9, 7, 6, 1, 4, 2, 3, 4, 2, 6, 8, 5, 3, 7, 9, 1, 7, 1, 3, 9, 2, 4, 8, 5, 6, 9, 6, 1, 5, 3, 7, 2, 8, 4, 2, 8, 7, 4, 1, 9, 6, 3, 5, 3, 4, 5, 2, 8, 6, 1, 7, 9];
    testboard = new Sudoku(origonalBoard);
    done();
  });

  describe('isValidSet', function(){
    it('should return false for invalid set', function(){
      expect( testboard.isValidSet(invalidSet) ).to.equal(false);
    });

    it('should return true for valid set', function(){
      expect( testboard.isValidSet(validSet) ).to.equal(true);
    });
  });

  describe('getRowSets', function(){
    it('should return an array of row sets', function(){
      expect( testboard.getRowSets() ).to.deep.equal( origonalRowSets );
    })
  });

  describe('getColumnSets', function(){
    it('should return an array of column sets', function(){
      expect( testboard.getColumnSets() ).to.deep.equal( origonalColumnSets );
    })
  })

  describe('getQuadrantSets', function(){
    it('should return array of quadrant sets', function(){
      console.log(origonalQuadrantSets);
      console.log(testboard.getQuadrantSets());
      expect( testboard.getQuadrantSets() ).to.deep.equal( origonalQuadrantSets);
    });
  });

  describe('resetBoard', function(){
    it('should reset board to original state', function(){
      testboard.resetBoard()
      expect( testboard._board ).to.equal(origonalBoard);
    });
  });

});
<|endoftext|>


<commit_before>var expect, base62;

if (typeof module !== 'undefined') {
  expect = require('expect.js');
  base62 = require('../');
} else {
  expect = this.expect;
  base62 = this.base62;
}

describe('base62', function() {

  describe('#decode()', function() {

    it('should throw error if parameter is not a integer', function() {
      function f(v) {
        return function() {
          base62.decode(v);
        };
      }

      function fn(e) {
        expect(e).to.be.a(Error);
      }

      expect(f('')).to.throwError(fn);
      expect(f('-')).to.throwError(fn);
      expect(f('0.1')).to.throwError(fn);
    });

    it('should throw error if parameter type is not a string', function() {
      function f(v) {
        return function() {
          base62.decode(v);
        };
      }

      function fn(e) {
        expect(e).to.be.a(TypeError);
      }

      expect(f(1)).to.throwError(fn);
      expect(f(true)).to.throwError(fn);
      expect(f(null)).to.throwError(fn);
      expect(f(void 0)).to.throwError(fn);
      expect(f(function() {})).to.throwError(fn);
    });

    it('should convert to integer from base62 string', function() {
      expect(base62.decode('0')).to.be(0);
      expect(base62.decode('Z')).to.be(61);
      expect(base62.decode('10')).to.be(62);
      expect(base62.decode('-0')).to.be(0);
      expect(base62.decode('-Z')).to.be(-61);
      expect(base62.decode('-10')).to.be(-62);
      expect(base62.decode('2lkCB1')).to.be(2147483647);
      expect(base62.decode('-2lkCB2')).to.be(-2147483647);
    });

  });

  describe('#encode()', function() {

    it('should throw error if parameter is not a integer', function() {
      function f(v) {
        return function() {
          base62.encode(v);
        };
      }

      function fn(e) {
        expect(e).to.be.a(Error);
      }

      expect(f(0.1)).to.throwError(fn);
      expect(f(NaN)).to.throwError(fn);
      expect(f(Infinity)).to.throwError(fn);
      expect(f(-Infinity)).to.throwError(fn);
    });

    it('should throw error if parameter type is not a number', function() {
      function f(v) {
        return function() {
          base62.encode(v);
        };
      }

      function fn(e) {
        expect(e).to.be.a(TypeError);
      }

      expect(f('a')).to.throwError(fn);
      expect(f(true)).to.throwError(fn);
      expect(f(null)).to.throwError(fn);
      expect(f(void 0)).to.throwError(fn);
      expect(f(function() {})).to.throwError(fn);
    });

    it('should convert to base62 string from integer', function() {
      expect(base62.encode(0)).to.be('0');
      expect(base62.encode(61)).to.be('Z');
      expect(base62.encode(62)).to.be('10');
      expect(base62.encode(-0)).to.be('0');
      expect(base62.encode(-61)).to.be('-Z');
      expect(base62.encode(-62)).to.be('-10');
      expect(base62.encode(2147483647)).to.be('2lkCB1');
      expect(base62.encode(-2147483647)).to.be('-2lkCB2');
    });

  });

});
<commit_msg>fixed test<commit_after>var expect, base62;

if (typeof module !== 'undefined') {
  expect = require('expect.js');
  base62 = require('../');
} else {
  expect = this.expect;
  base62 = this.base62;
}

describe('base62', function() {

  describe('#decode()', function() {

    it('should throw error if parameter is not a integer', function() {
      function f(v) {
        return function() {
          base62.decode(v);
        };
      }

      function fn(e) {
        expect(e).to.be.a(Error);
      }

      expect(f('')).to.throwError(fn);
      expect(f('-')).to.throwError(fn);
      expect(f('0.1')).to.throwError(fn);
    });

    it('should throw error if parameter type is not a string', function() {
      function f(v) {
        return function() {
          base62.decode(v);
        };
      }

      function fn(e) {
        expect(e).to.be.a(TypeError);
      }

      expect(f(1)).to.throwError(fn);
      expect(f(true)).to.throwError(fn);
      expect(f(null)).to.throwError(fn);
      expect(f(void 0)).to.throwError(fn);
      expect(f(function() {})).to.throwError(fn);
    });

    it('should convert to integer from base62 string', function() {
      expect(base62.decode('0')).to.be(0);
      expect(base62.decode('Z')).to.be(61);
      expect(base62.decode('10')).to.be(62);
      expect(base62.decode('-0')).to.be(0);
      expect(base62.decode('-Z')).to.be(-61);
      expect(base62.decode('-10')).to.be(-62);
      expect(base62.decode('2lkCB1')).to.be(2147483647);
      expect(base62.decode('-2lkCB2')).to.be(-2147483648);
    });

  });

  describe('#encode()', function() {

    it('should throw error if parameter is not a integer', function() {
      function f(v) {
        return function() {
          base62.encode(v);
        };
      }

      function fn(e) {
        expect(e).to.be.a(Error);
      }

      expect(f(0.1)).to.throwError(fn);
      expect(f(NaN)).to.throwError(fn);
      expect(f(Infinity)).to.throwError(fn);
      expect(f(-Infinity)).to.throwError(fn);
    });

    it('should throw error if parameter type is not a number', function() {
      function f(v) {
        return function() {
          base62.encode(v);
        };
      }

      function fn(e) {
        expect(e).to.be.a(TypeError);
      }

      expect(f('a')).to.throwError(fn);
      expect(f(true)).to.throwError(fn);
      expect(f(null)).to.throwError(fn);
      expect(f(void 0)).to.throwError(fn);
      expect(f(function() {})).to.throwError(fn);
    });

    it('should convert to base62 string from integer', function() {
      expect(base62.encode(0)).to.be('0');
      expect(base62.encode(61)).to.be('Z');
      expect(base62.encode(62)).to.be('10');
      expect(base62.encode(-0)).to.be('0');
      expect(base62.encode(-61)).to.be('-Z');
      expect(base62.encode(-62)).to.be('-10');
      expect(base62.encode(2147483647)).to.be('2lkCB1');
      expect(base62.encode(-2147483648)).to.be('-2lkCB2');
    });

  });

});
<|endoftext|>