<commit_before>import React      from 'react'
import ReactDOM   from 'react-dom'
import { expect } from 'chai'
import A11y       from '../src/a11y'
import rules      from '../src/rules'

describe('rules', () => {
  Object.keys(rules).forEach(function (rule) {
    describe(rule, () => {
      const {
        'default': defn
      , pass = []
      , fail = []
      } = require('../src/rules/' + rule)

      // get all messages
      const msgs = defn.reduce((acc, def) => acc.concat(def.msg), [])

      pass.forEach(function (ok) {
        it(`doesn't warn when ${ok.when}`, done => {
          const a11y = new A11y(React, ReactDOM, {
            reporter (info) {
              const {
                msg
              } = info
              expect(msgs.indexOf(msg) >= 0).to.be.true
            }
          , rules: {
              [rule]: 'warn'
            }
          })

          // force a11y into sync mode for test
          a11y.__forceSync(true)

          // create the el
          ok.render()

          // restore and finish
          a11y.restoreAll()
          done()
        })
      })

      fail.forEach(function (bad) {
        it(`warns when ${bad.when}`, done => {
          let called = false
          const a11y = new A11y(React, ReactDOM, {
            reporter (info) {
              called = true
              const {
                msg
              } = info
              expect(msgs.indexOf(msg) >= 0).to.be.true
            }
          , rules: {
              [rule]: 'warn'
            }
          })

          // force a11y into sync mode for test
          a11y.__forceSync(true)

          // create the el
          bad.render()

          // make sure error was presented
          expect(called).to.be.true

          a11y.restoreAll()
          done()
        })
      })
    })
  })
})
<commit_msg>inject react in tests so pass an fail exports can use them<commit_after>import React      from 'react'
import ReactDOM   from 'react-dom'
import { expect } from 'chai'
import A11y       from '../src/a11y'
import rules      from '../src/rules'

describe('rules', () => {
  Object.keys(rules).forEach(function (rule) {
    describe(rule, () => {
      const {
        'default': defn
      , pass = []
      , fail = []
      } = require('../src/rules/' + rule)

      // get all messages
      const msgs = defn.reduce((acc, def) => acc.concat(def.msg), [])

      pass.forEach(function (ok) {
        it(`doesn't warn when ${ok.when}`, done => {
          const a11y = new A11y(React, ReactDOM, {
            reporter (info) {
              const {
                msg
              } = info
              expect(msgs.indexOf(msg) >= 0).to.be.true
            }
          , rules: {
              [rule]: 'warn'
            }
          })

          // force a11y into sync mode for test
          a11y.__forceSync(true)

          // create the el
          ok.render(React)

          // restore and finish
          a11y.restoreAll()
          done()
        })
      })

      fail.forEach(function (bad) {
        it(`warns when ${bad.when}`, done => {
          let called = false
          const a11y = new A11y(React, ReactDOM, {
            reporter (info) {
              called = true
              const {
                msg
              } = info
              expect(msgs.indexOf(msg) >= 0).to.be.true
            }
          , rules: {
              [rule]: 'warn'
            }
          })

          // force a11y into sync mode for test
          a11y.__forceSync(true)

          // create the el
          bad.render(React)

          // make sure error was presented
          expect(called).to.be.true

          a11y.restoreAll()
          done()
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

const expect = require('chai').expect;
const Reminisce = require('../');

describe('plugin', () => {
  const memories = [
    { key: 'test1', val: 1, ttl: 10000 },
    { key: 'test2', val: 2 }
  ];
  let cache;

  beforeEach(() => {
    cache = new Reminisce({
      memories,
      options: { ttl: 60000, interval: 30000 }
    });
  });

  describe('constructor', () => {
    it('should initialize with a single memory', () => {
      cache = new Reminisce({ memories: memories[0] });

      expect(cache).to.be.an('object');
    });

    it('should initialize with memories', () => {
      cache = new Reminisce({ memories });

      expect(cache).to.be.an('object');
    });

    it('should initialize without memories', () => {
      cache = new Reminisce();

      expect(cache).to.be.an('object');
    });

    it('should take options', () => {
      cache = new Reminisce({
        options: { ttl: 10000, interval: 60000 }
      });

      expect(cache).to.be.an('object');
    });
  });

  describe('get memories function', () => {
    it('get a single memory', () => {
      return cache.get('test1')
        .spread((m) => {
          expect(m).to.have.property('key', 'test1');
          expect(m).to.have.property('val', 1);
          expect(m).to.have.property('ttl', 10000);
          expect(m).to.have.property('expires');
        });
    });

    it('get multiple memories', () => {
      return cache.get([ 'test1', 'test2' ])
        .then((m) => {
          expect(m).to.have.lengthOf(2);
          expect(m).to.have.deep.property('[0].key', 'test1');
          expect(m).to.have.deep.property('[0].val', 1);
          expect(m).to.have.deep.property('[0].ttl', 10000);
          expect(m).to.have.deep.property('[0].expires');
          expect(m).to.have.deep.property('[1].key', 'test2');
          expect(m).to.have.deep.property('[1].val', 2);
          expect(m).to.have.deep.property('[1].ttl', 60000);
          expect(m).to.have.deep.property('[1].expires');
        });
    });

    it('return undefined if memory does not exist', () => {
      return cache.get('forgot')
        .spread((m) => expect(m).to.be.undefined);
    });
  });

  describe('set memories function', () => {
    it('set a single memory', () => {
      const mem = { key: 'setTest', val: 1, ttl: 10000 };

      return cache.set(mem)
        .spread((m) => {
          expect(m).to.have.property('key', mem.key);
          expect(m).to.have.property('val', mem.val);
          expect(m).to.have.property('ttl', mem.ttl);
          expect(m).to.have.property('expires');
        });
    });

    it('set multiple memories', () => {
      const setMemories = [
        { key: 'setTest1', val: 1, ttl: 10000 },
        { key: 'setTest2', val: 2 }
      ];

      return cache.set(setMemories)
        .then((m) => {
          expect(m).to.have.lengthOf(2);
          expect(m).to.have.deep.property('[0].key', 'setTest1');
          expect(m).to.have.deep.property('[0].val', 1);
          expect(m).to.have.deep.property('[0].ttl', 10000);
          expect(m).to.have.deep.property('[0].expires');
          expect(m).to.have.deep.property('[1].key', 'setTest2');
          expect(m).to.have.deep.property('[1].val', 2);
          expect(m).to.have.deep.property('[1].ttl', 60000);
          expect(m).to.have.deep.property('[1].expires');
        });
    });

    it('override a memory', () => {
      const mem = { key: 'test2', val: 1, ttl: 10000 };

      return cache.set(mem)
        .spread((m) => {
          expect(m).to.have.property('val', mem.val);
          expect(m).to.have.property('ttl', mem.ttl);
          expect(m).to.have.property('expires');
        });
    });
  });

  describe('delete memories function', () => {
    it('should delete a single memory', () => {
      return cache.delete('test2')
        .spread((result) => expect(result).to.be.true);
    });

    it('should delete multiple memories', () => {
      return cache.delete([ 'test1', 'test2' ])
        .then((results) => {
          expect(results).to.have.lengthOf(2);

          results.forEach((result) => expect(result).to.be.true);
        });
    });

    it('should return true even when deleting non-existing memory', () => {
      return cache.delete('forgot')
        .spread((result) => expect(result).to.be.true);
    });
  });
});
<commit_msg>Reword constructor unit tests.<commit_after>'use strict';

const expect = require('chai').expect;
const Reminisce = require('../');

describe('plugin', () => {
  const memories = [
    { key: 'test1', val: 1, ttl: 10000 },
    { key: 'test2', val: 2 }
  ];
  let cache;

  beforeEach(() => {
    cache = new Reminisce({
      memories,
      options: { ttl: 60000, interval: 30000 }
    });
  });

  describe('constructor', () => {
    it('should initialize with a single memory', () => {
      cache = new Reminisce({ memories: memories[0] });

      expect(cache).to.be.an('object');
    });

    it('should initialize with multiple memories', () => {
      cache = new Reminisce({ memories });

      expect(cache).to.be.an('object');
    });

    it('should initialize with options', () => {
      cache = new Reminisce({
        options: { ttl: 10000, interval: 60000 }
      });

      expect(cache).to.be.an('object');
    });

    it('should initialize without memories or options', () => {
      cache = new Reminisce();

      expect(cache).to.be.an('object');
    });
  });

  describe('get memories function', () => {
    it('get a single memory', () => {
      return cache.get('test1')
        .spread((m) => {
          expect(m).to.have.property('key', 'test1');
          expect(m).to.have.property('val', 1);
          expect(m).to.have.property('ttl', 10000);
          expect(m).to.have.property('expires');
        });
    });

    it('get multiple memories', () => {
      return cache.get([ 'test1', 'test2' ])
        .then((m) => {
          expect(m).to.have.lengthOf(2);
          expect(m).to.have.deep.property('[0].key', 'test1');
          expect(m).to.have.deep.property('[0].val', 1);
          expect(m).to.have.deep.property('[0].ttl', 10000);
          expect(m).to.have.deep.property('[0].expires');
          expect(m).to.have.deep.property('[1].key', 'test2');
          expect(m).to.have.deep.property('[1].val', 2);
          expect(m).to.have.deep.property('[1].ttl', 60000);
          expect(m).to.have.deep.property('[1].expires');
        });
    });

    it('return undefined if memory does not exist', () => {
      return cache.get('forgot')
        .spread((m) => expect(m).to.be.undefined);
    });
  });

  describe('set memories function', () => {
    it('set a single memory', () => {
      const mem = { key: 'setTest', val: 1, ttl: 10000 };

      return cache.set(mem)
        .spread((m) => {
          expect(m).to.have.property('key', mem.key);
          expect(m).to.have.property('val', mem.val);
          expect(m).to.have.property('ttl', mem.ttl);
          expect(m).to.have.property('expires');
        });
    });

    it('set multiple memories', () => {
      const setMemories = [
        { key: 'setTest1', val: 1, ttl: 10000 },
        { key: 'setTest2', val: 2 }
      ];

      return cache.set(setMemories)
        .then((m) => {
          expect(m).to.have.lengthOf(2);
          expect(m).to.have.deep.property('[0].key', 'setTest1');
          expect(m).to.have.deep.property('[0].val', 1);
          expect(m).to.have.deep.property('[0].ttl', 10000);
          expect(m).to.have.deep.property('[0].expires');
          expect(m).to.have.deep.property('[1].key', 'setTest2');
          expect(m).to.have.deep.property('[1].val', 2);
          expect(m).to.have.deep.property('[1].ttl', 60000);
          expect(m).to.have.deep.property('[1].expires');
        });
    });

    it('override a memory', () => {
      const mem = { key: 'test2', val: 1, ttl: 10000 };

      return cache.set(mem)
        .spread((m) => {
          expect(m).to.have.property('val', mem.val);
          expect(m).to.have.property('ttl', mem.ttl);
          expect(m).to.have.property('expires');
        });
    });
  });

  describe('delete memories function', () => {
    it('should delete a single memory', () => {
      return cache.delete('test2')
        .spread((result) => expect(result).to.be.true);
    });

    it('should delete multiple memories', () => {
      return cache.delete([ 'test1', 'test2' ])
        .then((results) => {
          expect(results).to.have.lengthOf(2);

          results.forEach((result) => expect(result).to.be.true);
        });
    });

    it('should return true even when deleting non-existing memory', () => {
      return cache.delete('forgot')
        .spread((result) => expect(result).to.be.true);
    });
  });
});
<|endoftext|>


<commit_before>
var tape = require('tape')

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

var a = util.table(17)

var g = util.prefixes(a, 0)

//console.log(JSON.stringify(g, null, 2))
<commit_msg>update to new names<commit_after>
var tape = require('tape')

var util = require('../util')
var tree = require('../slow')
var Merkle = require('../')
tree = Merkle.tree

function count (tree) {
  var s = 0
  if('string' === typeof tree)
    return 1
  else
    for (var k in tree.tree) {
      s += count(tree.tree[k])
    }
  return s + 1
}

console.log('i, N, t, t/N, t/(N*log(N)), _t/t, H')
var _t =  0.0001
for(var i = 1; i <= 20; i++) {

  var a = util.table(i, 'binary')
  var start = Date.now()
  var g = tree(a)
  var t = Date.now() - start || 0.0001
  var N = 1 << i
  console.log([i, N, t, t/N, t / (N*Math.log(N)), _t/t, count(g)].join(', '))
//  console.log(JSON.stringify(g, null, 2))
  _t = t
}
//console.log(JSON.stringify(g, null, 2))
<|endoftext|>


<commit_before>'use strict';

var test = require('tape');

var isError = require('../index.js');

test('isError is a function', function t(assert) {
    assert.equal(typeof isError, 'function');
    assert.end();
});

test('returns true for error', function t(assert) {
    assert.equal(isError(new Error('foo')), true);
    assert.equal(isError(Error('foo')), true);
    assert.end();
});

test('returns false for non-error', function t(assert) {
    assert.equal(isError(null), false);
    assert.equal(isError(undefined), false);
    assert.equal(isError({message: 'hi'}), false);
    assert.end();
});
<commit_msg>Add breaking tests for foreign/inherited errors<commit_after>'use strict';

var test = require('tape');
var vm = require('vm');

var isError = require('../index.js');

test('isError is a function', function t(assert) {
    assert.equal(typeof isError, 'function');
    assert.end();
});

test('returns true for error', function t(assert) {
    assert.equal(isError(new Error('foo')), true);
    assert.equal(isError(Error('foo')), true);
    assert.end();
});

test('returns false for non-error', function t(assert) {
    assert.equal(isError(null), false);
    assert.equal(isError(undefined), false);
    assert.equal(isError({message: 'hi'}), false);
    assert.end();
});

test('errors that inherit from Error', function t(assert) {
    var error = Object.create(new Error());
    assert.equal(isError(error), true);
    assert.end();
});

test('errors from other contexts', function t(assert) {
    var error = vm.runInNewContext('new Error()');
    assert.equal(isError(error), true);
    assert.end();
});

test('errors that inherit from Error in another context', function t(assert) {
    var error = vm.runInNewContext('Object.create(new Error())');
    assert.equal(isError(error), true);
    assert.end();
});
<|endoftext|>


<commit_before>'use strict';

require('chai').should();
const Hexo = require('hexo');
const cheerio = require('cheerio');

describe('Sitemap generator', () => {
  const hexo = new Hexo(__dirname, {silent: true});
  hexo.config.sitemap = {
    path: 'sitemap.xml'
  };
  const Post = hexo.model('Post');
  const generator = require('../lib/generator').bind(hexo);
  const sitemapTmpl = require('../lib/template')(hexo.config);
  let posts = {};
  let locals = {};

  before(() => {
    return hexo.init().then(() => {
      return Post.insert([
        {source: 'foo', slug: 'foo', updated: 1e8},
        {source: 'bar', slug: 'bar', updated: 1e8 + 1},
        {source: 'baz', slug: 'baz', updated: 1e8 - 1}
      ]).then(data => {
        posts = data.sort((a, b) => b.updated - a.updated);
        locals = hexo.locals.toObject();
      });
    });
  });

  it('default', () => {
    const result = generator(locals);

    result.path.should.eql('sitemap.xml');
    result.data.should.eql(sitemapTmpl.render({
      config: hexo.config,
      posts: posts
    }));

    const $ = cheerio.load(result.data);

    $('url').each((index, element) => {
      $(element).children('loc').text().should.eql(posts[index].permalink);
      $(element).children('lastmod').text().should.eql(posts[index].updated.toISOString());
    });
  });

  describe('skip_render', () => {
    it('array', () => {
      hexo.config.skip_render = ['foo'];

      const result = generator(locals);
      result.data.should.not.contain('foo');
    });

    it('string', () => {
      hexo.config.skip_render = 'bar';

      const result = generator(locals);
      result.data.should.not.contain('bar');
    });

    it('off', () => {
      hexo.config.skip_render = null;

      const result = generator(locals);
      result.should.be.ok;
    });
  });
});
<commit_msg>test: add test for pages<commit_after>'use strict';

require('chai').should();
const Hexo = require('hexo');
const cheerio = require('cheerio');

describe('Sitemap generator', () => {
  const hexo = new Hexo(__dirname, {silent: true});
  hexo.config.sitemap = {
    path: 'sitemap.xml'
  };
  const Post = hexo.model('Post');
  const Page = hexo.model('Page');
  const generator = require('../lib/generator').bind(hexo);
  const sitemapTmpl = require('../lib/template')(hexo.config);
  let posts = {};
  let pages = {};
  let locals = {};

  before(() => {
    return hexo.init().then(() => {
      return Post.insert([
        {source: 'foo', slug: 'foo', updated: 1e8},
        {source: 'bar', slug: 'bar', updated: 1e8 + 1},
        {source: 'baz', slug: 'baz', updated: 1e8 - 1}
      ]).then(data => {
        posts = data.sort((a, b) => b.updated - a.updated);
      }).then(() => {
        return Page.insert([
          {source: 'bio/index.md', path: 'bio/', updated: 1e8 - 3},
          {source: 'about/index.md', path: 'about/', updated: 1e8 - 4}
        ]);
      }).then(data => {
        posts = Post.sort('-updated');
        pages = Page.sort('-update');
        locals = hexo.locals.toObject();
      });
    });
  });

  it('default', () => {
    const result = generator(locals);

    result.path.should.eql('sitemap.xml');
    result.data.should.eql(sitemapTmpl.render({
      config: hexo.config,
      posts: posts.toArray().concat(pages.toArray())
    }));

    const $ = cheerio.load(result.data);
    const allPosts = Object.assign({}, posts.data.concat(pages.data));

    $('url').each((index, element) => {
      $(element).children('loc').text().should.eql(allPosts[index].permalink);
      $(element).children('lastmod').text().should.eql(allPosts[index].updated.toISOString());
    });
  });

  describe('skip_render', () => {
    it('array', () => {
      hexo.config.skip_render = ['foo'];

      const result = generator(locals);
      result.data.should.not.contain('foo');
    });

    it('string', () => {
      hexo.config.skip_render = 'bar';

      const result = generator(locals);
      result.data.should.not.contain('bar');
    });

    it('off', () => {
      hexo.config.skip_render = null;

      const result = generator(locals);
      result.should.be.ok;
    });
  });
});
<|endoftext|>


<commit_before>require.config( {
  baseUrl : '../src',
  paths: {
      lib: '../lib'
  }
} );

function assert( outcome, description, target, object ) {
    var div = document.createElement( 'div' );
    div.className = outcome ? 'pass' : 'fail';
    div.appendChild( document.createTextNode( description ) );

    document.getElementById( target ).appendChild( div );

    if( object ) {
      console.log( description, object );
    }
};
<commit_msg>renaming parameter on unit test setup.js<commit_after>require.config( {
  baseUrl : '../src',
  paths: {
      lib: '../lib'
  }
} );

function assert( outcome, description, package, object ) {
    var div = document.createElement( 'div' );
    div.className = outcome ? 'pass' : 'fail';
    div.appendChild( document.createTextNode( description ) );

    document.getElementById( package ).appendChild( div );

    if( object ) {
      console.log( package, description, object );
    }
};
<|endoftext|>


<commit_before>'use strict';

var chalk     = require('chalk');
var purdy     = require('purdy');
var mongoose  = require('mongoose');
var mockgoose = require('mockgoose');
var supertest = require('supertest');

// Set the 'NODE_ENV' for this process as 'test'. This will disable
// 'development' level logging, making test output more readable.
process.env.NODE_ENV = 'test';

var config = require('../config');

// Wrap Mongoose with Mockgoose
// mockgoose(mongoose);

/**
 * Setup 'supertest'. Declare 'demousers'. Establish mongoose connection.
 */
before(function(done) {
	console.log(chalk.dim('Initializing...'));

	var server = require('../server');
	this.app   = supertest(server.app);

	console.log(chalk.dim('Using MongDB configuration:\n'));
	purdy(config.mongo);

	mongoose.connect(config.mongo.url, config.mongo.options, done);
});

// Throw in a newline for clarity.
before(console.log.bind(console, ''));

/**
 * A basic 'user' workflow.
 */
describe('Basic API usage', function() {

	var context = { }

	describe('Signing up',
		require('./spec/signing-up')(context));

	describe('Logging in',
		require('./spec/signing-in')(context));

	describe('Creating a board',
		require('./spec/creating-a-board')(context));

	describe('Updating a board',
		require('./spec/updating-a-board')(context));

	describe('Creating a ticket',
		require('./spec/creating-a-ticket')(context));

	describe('Updating a ticket',
		require('./spec/updating-a-ticket')(context));

	describe('Granting guest access',
		require('./spec/granting-guest-access')(context));

	describe('Using guest token',
		require('./spec/using-guest-token')(context));

	describe('Revoking guest access',
		require('./spec/revoking-guest-access')(context));
});
<commit_msg>Re-enable 'mockgoose'.<commit_after>'use strict';

var chalk     = require('chalk');
var purdy     = require('purdy');
var mongoose  = require('mongoose');
var mockgoose = require('mockgoose');
var supertest = require('supertest');

// Set the 'NODE_ENV' for this process as 'test'. This will disable
// 'development' level logging, making test output more readable.
process.env.NODE_ENV = 'test';

var config = require('../config');

// Wrap Mongoose with Mockgoose
mockgoose(mongoose);

/**
 * Setup 'supertest'. Declare 'demousers'. Establish mongoose connection.
 */
before(function(done) {
	console.log(chalk.dim('Initializing...'));

	var server = require('../server');
	this.app   = supertest(server.app);

	console.log(chalk.dim('Using MongDB configuration:\n'));
	purdy(config.mongo);

	mongoose.connect(config.mongo.url, config.mongo.options, done);
});

// Throw in a newline for clarity.
before(console.log.bind(console, ''));

/**
 * A basic 'user' workflow.
 */
describe('Basic API usage', function() {

	var context = { }

	describe('Signing up',
		require('./spec/signing-up')(context));

	describe('Logging in',
		require('./spec/signing-in')(context));

	describe('Creating a board',
		require('./spec/creating-a-board')(context));

	describe('Updating a board',
		require('./spec/updating-a-board')(context));

	describe('Creating a ticket',
		require('./spec/creating-a-ticket')(context));

	describe('Updating a ticket',
		require('./spec/updating-a-ticket')(context));

	describe('Granting guest access',
		require('./spec/granting-guest-access')(context));

	describe('Using guest token',
		require('./spec/using-guest-token')(context));

	describe('Revoking guest access',
		require('./spec/revoking-guest-access')(context));
});
<|endoftext|>


<commit_before>process.env.NODE_ENV = 'test'

var skiff = require('../lib/skiff')
var chai = require('chai')
var fs = require('fs')
var path = require('path')
var Promise = require('bluebird')
var root = require('root-path')

chai.use(require('chai-spies'))
chai.use(require('chai-as-promised'))

global.spy = chai.spy
global.expect = chai.expect

require('mock-kue')

var TestSetup = function () {
  this.tables = []
}

var setup = new TestSetup()

before(function (done) {
  this.timeout(30000)

  var i18n = require('i18n')
  i18n.configure(require(root('config/i18n')))
  global.sails = skiff.sails

  skiff.lift({
    log: {level: process.env.LOG_LEVEL || 'warn'},
    silent: true,
    start: function () {
      // add controllers to the global namespace; they would otherwise be excluded
      // since the sails "http" module is not being loaded in the test env
      _.each(fs.readdirSync(root('api/controllers')), function (filename) {
        if (path.extname(filename) === '.js') {
          var modelName = path.basename(filename, '.js')
          global[modelName] = require(root('api/controllers/' + modelName))
        }
      })

      setup.createSchema()
      .then(() => done())
      .catch(done)
    }
  })
})

TestSetup.prototype.createSchema = function () {
  return bookshelf.transaction(trx => {
    return bookshelf.knex.raw('drop schema public cascade').transacting(trx)
    .then(() => bookshelf.knex.raw('create schema public').transacting(trx))
    .then(() => {
      var script = fs.readFileSync(root('migrations/schema.sql')).toString()
      return script.split(/\n/)
      .filter(line => !line.startsWith('--'))
      .join('')
      .replace(/\s+/g, ' ')
      .split(/;\s?/)
      .filter(line => line !== '')
    })
    .each(command => {
      if (command.startsWith('CREATE TABLE')) {
        this.tables.push(command.split(' ')[2])
      }
      return bookshelf.knex.raw(command).transacting(trx)
    })
  }) // transaction
}

TestSetup.prototype.clearDb = function () {
  return bookshelf.knex.transaction(trx => trx.raw('set constraints all deferred')
  .then(() => Promise.map(this.tables, table => trx.raw('delete from ' + table))))
}

module.exports = setup
<commit_msg>fix schema generation code in test suite<commit_after>process.env.NODE_ENV = 'test'

var skiff = require('../lib/skiff')
var chai = require('chai')
var fs = require('fs')
var path = require('path')
var Promise = require('bluebird')
var root = require('root-path')

chai.use(require('chai-spies'))
chai.use(require('chai-as-promised'))

global.spy = chai.spy
global.expect = chai.expect

require('mock-kue')

var TestSetup = function () {
  this.tables = []
}

var setup = new TestSetup()

before(function (done) {
  this.timeout(30000)

  var i18n = require('i18n')
  i18n.configure(require(root('config/i18n')))
  global.sails = skiff.sails

  skiff.lift({
    log: {level: process.env.LOG_LEVEL || 'warn'},
    silent: true,
    start: function () {
      // add controllers to the global namespace; they would otherwise be excluded
      // since the sails "http" module is not being loaded in the test env
      _.each(fs.readdirSync(root('api/controllers')), function (filename) {
        if (path.extname(filename) === '.js') {
          var modelName = path.basename(filename, '.js')
          global[modelName] = require(root('api/controllers/' + modelName))
        }
      })

      setup.createSchema()
      .then(() => done())
      .catch(done)
    }
  })
})

TestSetup.prototype.createSchema = function () {
  return bookshelf.transaction(trx => {
    return bookshelf.knex.raw('drop schema public cascade').transacting(trx)
    .then(() => bookshelf.knex.raw('create schema public').transacting(trx))
    .then(() => {
      var script = fs.readFileSync(root('migrations/schema.sql')).toString()
      return script.split(/\n/)
      .filter(line => !line.startsWith('--'))
      .join(' ')
      .replace(/\s+/g, ' ')
      .split(/;\s?/)
      .map(line => line.trim())
      .filter(line => line !== '')
    })
    .each(command => {
      if (command.startsWith('CREATE TABLE')) {
        this.tables.push(command.split(' ')[2])
      }
      return bookshelf.knex.raw(command).transacting(trx)
    })
  }) // transaction
}

TestSetup.prototype.clearDb = function () {
  return bookshelf.knex.transaction(trx => trx.raw('set constraints all deferred')
  .then(() => Promise.map(this.tables, table => trx.raw('delete from ' + table))))
}

module.exports = setup
<|endoftext|>


<commit_before>'use strict';
// Load modules

const Glue = require('..');
const Lab = require('lab');
const Hoek = require('hoek');

// Declare internals

const internals = {};

// Test shortcuts

const { describe, expect, it } = exports.lab = Lab.script();

describe('compose()', () => {

    it('composes a server with an empty manifest', async () => {

        const manifest = {};
        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('throws an error', async () => {

        const manifest = {
            register: {
                plugins: ['invalidplugin']
            }
        };

        await expect(Glue.compose(manifest)).to.reject(Error, /Cannot find module/);
    });

    it('composes a server with server.cache as a string', async () => {

        const manifest = {
            server: {
                cache: '../node_modules/catbox-memory'
            }
        };

        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server with server.cache as an array', async () => {

        const manifest = {
            server: {
                cache: ['../node_modules/catbox-memory']
            }
        };

        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server with server.cache.engine as a string', async () => {

        const manifest = {
            server: {
                cache: {
                    engine: '../node_modules/catbox-memory'
                }
            }
        };

        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server with server.cache.engine as a function', async () => {

        const manifest = {
            server: {
                cache: [{
                    engine: require('catbox-memory')
                }]
            }
        };

        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server with server.cache.engine resolved using options.relativeTo', async () => {

        const manifest = {
            server: {
                cache: '../../node_modules/catbox-memory'
            }
        };

        const server = await Glue.compose(manifest, { relativeTo: __dirname + '/plugins' });
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server without modifying the manifest', async () => {

        const manifest = {
            register: {
                plugins: [
                    {
                        plugin: '../test/plugins/helloworld.js'
                    }
                ]
            }
        };
        const clone = Hoek.clone(manifest);

        const server = await Glue.compose(manifest);
        expect(server.plugins.helloworld).to.exist();
        expect(Hoek.deepEqual(manifest, clone)).to.equal(true);
    });

    describe('composes a server\'s registrations', () => {

        it('has no registrations', async () => {

            const manifest = {
                register: {
                    plugins: []
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins).length(0);
        });

        it('has a registration with a plugin path only', async () => {

            const manifest = {
                register: {
                    plugins: ['../test/plugins/helloworld.js']
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello).to.equal('world');
        });

        it('has a registration with plugin object instead of path to be required', async () => {

            const manifest = {
                register: {
                    plugins: [{
                        plugin: require('./plugins/helloworld')
                    }]
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello).to.equal('world');
        });

        it('passes through original plugin options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/helloworld.js',
                            options: {
                                who: { i: 'am not a clone' }
                            }
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello === manifest.register.plugins[0].options.who).to.be.equal(true);
        });

        it('has a registration with no plugin options and no register options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/helloworld.js'
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello).to.equal('world');
        });

        it('has a registration with plugin options and no register options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/helloworld.js',
                            options: { who: 'earth' }
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello).to.equal('earth');
        });

        it('has a registration with register options and no plugin options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/route.js'
                        }
                    ],
                    options: {
                        routes: { prefix: '/test/' }
                    }
                }
            };

            const server = await Glue.compose(manifest);
            const response = await server.inject('/test/plugin');
            expect(response.statusCode).to.equal(200);
        });

        it('has a registration with register options in the plugin', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/route.js',
                            routes: { prefix: '/test/' }
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest);
            const response = await server.inject('/test/plugin');
            expect(response.statusCode).to.equal(200);
        });

        it('has a registration with the plugin resolved using options.relativeTo', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: './helloworld.js'
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest, { relativeTo: __dirname + '/plugins' });
            expect(server.plugins.helloworld.hello).to.equal('world');
        });

        it('has a registration with different plugin syntax, some plugin options, main registration options, and plugin-level registration options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        '../test/plugins/helloworld.js',
                        {
                            plugin : '../test/plugins/second.js',
                            options: {
                                value: 'second'
                            }
                        },
                        {
                            plugin: require('./plugins/route'),
                            routes: { prefix: '/test/' }
                        }
                    ],
                    options: {
                        routes: { prefix: '/override/me/' }
                    }
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld.hello).to.equal('world');
            const response = await server.inject('/test/plugin');
            expect(response.statusCode).to.equal(200);
            const secondResponse = await server.inject('/override/me/second');
            expect(secondResponse.statusCode).to.equal(200);
            expect(secondResponse.payload).to.equal('second');
        });
    });

    it('composes a server with a preRegister handler', async () => {

        let count = 0;
        const manifest = {};
        const options = {
            preRegister: function (server) {

                ++count;
            }
        };

        await Glue.compose(manifest, options);
        expect(count).to.equal(1);
    });

    it('errors on failed pre handler', async () => {

        const manifest = {};
        const options = {
            preRegister: function (server, callback) {

                callback({ error: 'failed' });
            }
        };

        await expect(Glue.compose(manifest, options)).to.reject();
    });

    it('throws on bogus options.relativeTo path (server.cache)', async () => {

        const manifest = {
            server: {
                cache: './catbox-memory'
            }
        };

        await expect(Glue.compose(manifest, { relativeTo: __dirname + '/badpath' })).to.reject(Error, /Cannot find module/);
    });

    it('throws on bogus options.relativeTo path (plugins)', async () => {

        const manifest = {
            register: {
                plugins: [
                    {
                        plugin: './helloworld.js'
                    }
                ]
            }
        };

        await expect(Glue.compose(manifest, { relativeTo: __dirname + '/badpath' })).to.reject(Error, /Cannot find module/);
    });

    it('throws on options not an object', async () => {

        const manifest = {};

        await expect(Glue.compose(manifest, 'hello')).to.reject(Error, /Invalid options/);
    });

    it('throws on invalid options (preConnections present)', async () => {

        const options = {
            preConnections: false
        };

        await expect(Glue.compose({}, options)).to.reject(Error, /Invalid options/);
    });

    it('throws on invalid manifest (not an object)', async () => {

        const manifest = 'hello';

        await expect(Glue.compose(manifest)).to.reject(Error, /Invalid manifest/);
    });

    it('throws on invalid manifest (server not an object)', async () => {

        const manifest = {
            server: 'hello'
        };

        await expect(Glue.compose(manifest)).to.reject(Error, /Invalid manifest/);
    });

    it('throws on invalid manifest (connections present)', async () => {

        const manifest = {
            connections: [
                {}
            ]
        };

        await expect(Glue.compose(manifest)).to.reject(Error, /Invalid manifest/);
    });

    it('throws on invalid manifest (register not an object)', async () => {

        const manifest = {
            register: 'hello'
        };

        await expect(Glue.compose(manifest)).to.reject(Error, /Invalid manifest/);
    });
});
<commit_msg>Correct preRegister error handling test.<commit_after>'use strict';
// Load modules

const Glue = require('..');
const Lab = require('lab');
const Hoek = require('hoek');

// Declare internals

const internals = {};

// Test shortcuts

const { describe, expect, it } = exports.lab = Lab.script();

describe('compose()', () => {

    it('composes a server with an empty manifest', async () => {

        const manifest = {};
        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('throws an error', async () => {

        const manifest = {
            register: {
                plugins: ['invalidplugin']
            }
        };

        await expect(Glue.compose(manifest)).to.reject(Error, /Cannot find module/);
    });

    it('composes a server with server.cache as a string', async () => {

        const manifest = {
            server: {
                cache: '../node_modules/catbox-memory'
            }
        };

        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server with server.cache as an array', async () => {

        const manifest = {
            server: {
                cache: ['../node_modules/catbox-memory']
            }
        };

        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server with server.cache.engine as a string', async () => {

        const manifest = {
            server: {
                cache: {
                    engine: '../node_modules/catbox-memory'
                }
            }
        };

        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server with server.cache.engine as a function', async () => {

        const manifest = {
            server: {
                cache: [{
                    engine: require('catbox-memory')
                }]
            }
        };

        const server = await Glue.compose(manifest);
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server with server.cache.engine resolved using options.relativeTo', async () => {

        const manifest = {
            server: {
                cache: '../../node_modules/catbox-memory'
            }
        };

        const server = await Glue.compose(manifest, { relativeTo: __dirname + '/plugins' });
        expect(server.info).to.be.an.object();
        expect(server.info.port).to.equal(0);
    });

    it('composes a server without modifying the manifest', async () => {

        const manifest = {
            register: {
                plugins: [
                    {
                        plugin: '../test/plugins/helloworld.js'
                    }
                ]
            }
        };
        const clone = Hoek.clone(manifest);

        const server = await Glue.compose(manifest);
        expect(server.plugins.helloworld).to.exist();
        expect(Hoek.deepEqual(manifest, clone)).to.equal(true);
    });

    describe('composes a server\'s registrations', () => {

        it('has no registrations', async () => {

            const manifest = {
                register: {
                    plugins: []
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins).length(0);
        });

        it('has a registration with a plugin path only', async () => {

            const manifest = {
                register: {
                    plugins: ['../test/plugins/helloworld.js']
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello).to.equal('world');
        });

        it('has a registration with plugin object instead of path to be required', async () => {

            const manifest = {
                register: {
                    plugins: [{
                        plugin: require('./plugins/helloworld')
                    }]
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello).to.equal('world');
        });

        it('passes through original plugin options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/helloworld.js',
                            options: {
                                who: { i: 'am not a clone' }
                            }
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello === manifest.register.plugins[0].options.who).to.be.equal(true);
        });

        it('has a registration with no plugin options and no register options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/helloworld.js'
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello).to.equal('world');
        });

        it('has a registration with plugin options and no register options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/helloworld.js',
                            options: { who: 'earth' }
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld).to.exist();
            expect(server.plugins.helloworld.hello).to.equal('earth');
        });

        it('has a registration with register options and no plugin options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/route.js'
                        }
                    ],
                    options: {
                        routes: { prefix: '/test/' }
                    }
                }
            };

            const server = await Glue.compose(manifest);
            const response = await server.inject('/test/plugin');
            expect(response.statusCode).to.equal(200);
        });

        it('has a registration with register options in the plugin', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: '../test/plugins/route.js',
                            routes: { prefix: '/test/' }
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest);
            const response = await server.inject('/test/plugin');
            expect(response.statusCode).to.equal(200);
        });

        it('has a registration with the plugin resolved using options.relativeTo', async () => {

            const manifest = {
                register: {
                    plugins: [
                        {
                            plugin: './helloworld.js'
                        }
                    ]
                }
            };

            const server = await Glue.compose(manifest, { relativeTo: __dirname + '/plugins' });
            expect(server.plugins.helloworld.hello).to.equal('world');
        });

        it('has a registration with different plugin syntax, some plugin options, main registration options, and plugin-level registration options', async () => {

            const manifest = {
                register: {
                    plugins: [
                        '../test/plugins/helloworld.js',
                        {
                            plugin : '../test/plugins/second.js',
                            options: {
                                value: 'second'
                            }
                        },
                        {
                            plugin: require('./plugins/route'),
                            routes: { prefix: '/test/' }
                        }
                    ],
                    options: {
                        routes: { prefix: '/override/me/' }
                    }
                }
            };

            const server = await Glue.compose(manifest);
            expect(server.plugins.helloworld.hello).to.equal('world');
            const response = await server.inject('/test/plugin');
            expect(response.statusCode).to.equal(200);
            const secondResponse = await server.inject('/override/me/second');
            expect(secondResponse.statusCode).to.equal(200);
            expect(secondResponse.payload).to.equal('second');
        });
    });

    it('composes a server with a preRegister handler', async () => {

        let count = 0;
        const manifest = {};
        const options = {
            preRegister: function (server) {

                ++count;
            }
        };

        await Glue.compose(manifest, options);
        expect(count).to.equal(1);
    });

    it('errors on failed pre handler', async () => {

        const manifest = {};
        const options = {
            preRegister: (server) => {

                throw new Error('preRegister failed');
            }
        };

        await expect(Glue.compose(manifest, options)).to.reject(Error, /preRegister failed/);
    });

    it('throws on bogus options.relativeTo path (server.cache)', async () => {

        const manifest = {
            server: {
                cache: './catbox-memory'
            }
        };

        await expect(Glue.compose(manifest, { relativeTo: __dirname + '/badpath' })).to.reject(Error, /Cannot find module/);
    });

    it('throws on bogus options.relativeTo path (plugins)', async () => {

        const manifest = {
            register: {
                plugins: [
                    {
                        plugin: './helloworld.js'
                    }
                ]
            }
        };

        await expect(Glue.compose(manifest, { relativeTo: __dirname + '/badpath' })).to.reject(Error, /Cannot find module/);
    });

    it('throws on options not an object', async () => {

        const manifest = {};

        await expect(Glue.compose(manifest, 'hello')).to.reject(Error, /Invalid options/);
    });

    it('throws on invalid options (preConnections present)', async () => {

        const options = {
            preConnections: false
        };

        await expect(Glue.compose({}, options)).to.reject(Error, /Invalid options/);
    });

    it('throws on invalid manifest (not an object)', async () => {

        const manifest = 'hello';

        await expect(Glue.compose(manifest)).to.reject(Error, /Invalid manifest/);
    });

    it('throws on invalid manifest (server not an object)', async () => {

        const manifest = {
            server: 'hello'
        };

        await expect(Glue.compose(manifest)).to.reject(Error, /Invalid manifest/);
    });

    it('throws on invalid manifest (connections present)', async () => {

        const manifest = {
            connections: [
                {}
            ]
        };

        await expect(Glue.compose(manifest)).to.reject(Error, /Invalid manifest/);
    });

    it('throws on invalid manifest (register not an object)', async () => {

        const manifest = {
            register: 'hello'
        };

        await expect(Glue.compose(manifest)).to.reject(Error, /Invalid manifest/);
    });
});
<|endoftext|>


<commit_before>'use strict'

;['master', 'worker', 'utils', 'marshaller', 'types/error'].forEach((file) => {
  require(`./${file}`)
})
<commit_msg>Include env test<commit_after>'use strict'

;['env',
  'master',
  'worker',
  'utils',
  'marshaller',
  'types/error'].forEach((file) => {
  require(`./${file}`)
})
<|endoftext|>


<commit_before>import {test} from "tape";
import {default as split, splitChars} from "../src/split.js";

test("split", (assert) => {

  for (let i = 0; i < splitChars.length; i++) {
    let char = splitChars[i];
    if (char.startsWith("u")) char = String.fromCharCode(`0x${char.slice(1)}`);
    const sentence = `test${char}test`;
    const arr = split(sentence);
    const first = char === " " ? "test" : `test${char}`;
    assert.true(arr[0] === first && arr[1] === "test", `split using "${char}"`);
  }

  assert.end();

});
<commit_msg>adds tests for no-space languages<commit_after>import {test} from "tape";
import {default as split, splitChars} from "../src/split.js";

test("split", (assert) => {

  for (let i = 0; i < splitChars.length; i++) {
    let char = splitChars[i];
    if (char.startsWith("u")) char = String.fromCharCode(`0x${char.slice(1)}`);
    const sentence = `test${char}test`;
    const arr = split(sentence);
    const first = char === " " ? "test" : `test${char}`;
    assert.true(arr[0] === first && arr[1] === "test", `using "${char}"`);
  }

  const chinese = split("里句。");
  assert.true(chinese[0] === "里" && chinese[1] === "句。", "simplified chinese");

  const burmese = split("ကြောယ်။");
  assert.true(burmese[0] === "ကြော" && burmese[1] === "ယ်။", "burmese");

  const lao = split("ຕໍ່ດ້.");
  assert.true(lao[0] === "ຕໍ່" && lao[1] === "ດ້.", "lao");

  assert.end();

});
<|endoftext|>


<commit_before>var test = require('tape');
var hash = require('../index');
var validSha1 = /^[0-9a-f]{40}$/i;

test('throws when nothing to hash', function (assert) {
  assert.plan(2);
  assert.throws(hash, 'no arguments');
  assert.throws(function(){
    hash(undefined, {algorithm: 'md5'});
  }, 'undefined');
});

test('throws when passed an invalid options', function(assert){
  assert.plan(2);
  assert.throws(function(){
    hash({foo: 'bar'}, {algorithm: 'shalala'});
  }, 'bad algorithm');
  assert.throws(function(){
    hash({foo: 'bar'}, {encoding: 'base16'});
  }, 'bad encoding');
});

test('hashes non-object types', function(assert){
  assert.plan(4);
  var func = function(a){ return a + 1; };
  assert.ok(validSha1.test(hash('Shazbot!')), 'hash string');
  assert.ok(validSha1.test(hash(42)), 'hash number');
  assert.ok(validSha1.test(hash(true)), 'hash bool');
  assert.ok(validSha1.test(hash(func)), 'hash function');
});

test('hashes special object types', function(assert){
  assert.plan(8);
  var dt = new Date();
  dt.setDate(dt.getDate() + 1);

  assert.ok(validSha1.test(hash([1,2,3,4])), 'hash array');
  assert.notEqual(hash([1,2,3,4]), hash([4,3,2,1]), 'different arrays not equal');
  assert.ok(validSha1.test(hash(new Date())), 'hash date');
  assert.notEqual(hash(new Date()), hash(dt), 'different dates not equal');
  assert.ok(validSha1.test(hash(null)), 'hash Null');
  assert.ok(validSha1.test(hash(Number.NaN)), 'hash NaN');
  assert.ok(validSha1.test(hash({ foo: undefined })), 'hash Undefined value');
  assert.ok(validSha1.test(hash(new RegExp())), 'hash regex');
});

test('hashes a simple object', function(assert){
  assert.plan(1);
  assert.ok(validSha1.test(hash({foo: 'bar', bar: 'baz'})), 'hash object');
});

test('hashes identical objects with different key ordering', function(assert){
  assert.plan(2);
  var hash1 = hash({foo: 'bar', bar: 'baz'});
  var hash2 = hash({bar: 'baz', foo: 'bar'});
  var hash3 = hash({bar: 'foo', foo: 'baz'});
  assert.equal(hash1, hash2, 'hashes are equal');
  assert.notEqual(hash1, hash3, 'different objects not equal');
});

test('only hashes object keys when excludeValues option is set', function(assert){
  assert.plan(2);
  var hash1 = hash({foo: false, bar: 'OK'}, { excludeValues: true });
  var hash2 = hash({foo: true, bar: 'NO'}, { excludeValues: true });
  var hash3 = hash({foo: true, bar: 'OK', baz: false}, { excludeValues: true });
  assert.equal(hash1, hash2, 'values not in hash digest');
  assert.notEqual(hash1, hash3, 'different keys not equal');
});

test('array values are hashed', function(assert){
  assert.plan(1);
  var hash1 = hash({foo: ['bar', 'baz'], bax: true });
  var hash2 = hash({foo: ['baz', 'bar'], bax: true });
  assert.notEqual(hash1, hash2, 'different array orders are unique');
});

test('nested object values are hashed', function(assert){
  assert.plan(2);
  var hash1 = hash({foo: {bar: true, bax: 1}});
  var hash2 = hash({foo: {bar: true, bax: 1}});
  var hash3 = hash({foo: {bar: false, bax: 1}});
  assert.equal(hash1, hash2, 'hashes are equal');
  assert.notEqual(hash1, hash3, 'different objects not equal');
});

test('sugar methods should be equivalent', function(assert){
  assert.plan(3);
  var obj = {foo: 'bar', baz: true};
  assert.equal(hash.keys(obj), hash(obj, {excludeValues: true}), 'keys');
  assert.equal(hash.MD5(obj), hash(obj, {algorithm: 'md5'}), 'md5');
  assert.equal(hash.keysMD5(obj),
    hash(obj, {algorithm: 'md5', excludeValues: true}), 'keys md5');
});

test('array of nested object values are hashed', function(assert){
  assert.plan(2);
  var hash1 = hash({foo: [ {bar: true, bax: 1}, {bar: false, bax: 2} ] });
  var hash2 = hash({foo: [ {bar: true, bax: 1}, {bar: false, bax: 2} ] });
  var hash3 = hash({foo: [ {bar: false, bax: 2} ] });
  assert.equal(hash1, hash2, 'hashes are equal');
  assert.notEqual(hash1, hash3, 'different objects not equal');
});

test("recursive objects don't blow up stack", function(assert) {
  assert.plan(1);
  var hash1 = {foo: 'bar'};
  hash1.recursive = hash1;
  assert.doesNotThrow(function(){hash(hash1);}, /Maximum call stack size exceeded/, 'Should not throw an stack size exceeded exception');
});

test("recursive arrays don't blow up stack", function(assert) {
  assert.plan(1);
  var hash1 = ['foo', 'bar'];
  hash1.push(hash1);
  assert.doesNotThrow(function(){hash(hash1);}, /Maximum call stack size exceeded/, 'Should not throw an stack size exceeded exception');
});

test("recursive handling tracks identity", function(assert) {
  assert.plan(1);
  var hash1 = {k1: {k: 'v'}, k2: {k: 'k2'}};
  hash1.k1.r1 = hash1.k1;
  hash1.k2.r2 = hash1.k2;
  var hash2 = {k1: {k: 'v'}, k2: {k: 'k2'}};
  hash2.k1.r1 = hash2.k2;
  hash2.k2.r2 = hash2.k1;
  assert.notEqual(hash(hash1), hash(hash2), "order of recursive objects should matter");
});
<commit_msg>Clarify excludeValues test message<commit_after>var test = require('tape');
var hash = require('../index');
var validSha1 = /^[0-9a-f]{40}$/i;

test('throws when nothing to hash', function (assert) {
  assert.plan(2);
  assert.throws(hash, 'no arguments');
  assert.throws(function(){
    hash(undefined, {algorithm: 'md5'});
  }, 'undefined');
});

test('throws when passed an invalid options', function(assert){
  assert.plan(2);
  assert.throws(function(){
    hash({foo: 'bar'}, {algorithm: 'shalala'});
  }, 'bad algorithm');
  assert.throws(function(){
    hash({foo: 'bar'}, {encoding: 'base16'});
  }, 'bad encoding');
});

test('hashes non-object types', function(assert){
  assert.plan(4);
  var func = function(a){ return a + 1; };
  assert.ok(validSha1.test(hash('Shazbot!')), 'hash string');
  assert.ok(validSha1.test(hash(42)), 'hash number');
  assert.ok(validSha1.test(hash(true)), 'hash bool');
  assert.ok(validSha1.test(hash(func)), 'hash function');
});

test('hashes special object types', function(assert){
  assert.plan(8);
  var dt = new Date();
  dt.setDate(dt.getDate() + 1);

  assert.ok(validSha1.test(hash([1,2,3,4])), 'hash array');
  assert.notEqual(hash([1,2,3,4]), hash([4,3,2,1]), 'different arrays not equal');
  assert.ok(validSha1.test(hash(new Date())), 'hash date');
  assert.notEqual(hash(new Date()), hash(dt), 'different dates not equal');
  assert.ok(validSha1.test(hash(null)), 'hash Null');
  assert.ok(validSha1.test(hash(Number.NaN)), 'hash NaN');
  assert.ok(validSha1.test(hash({ foo: undefined })), 'hash Undefined value');
  assert.ok(validSha1.test(hash(new RegExp())), 'hash regex');
});

test('hashes a simple object', function(assert){
  assert.plan(1);
  assert.ok(validSha1.test(hash({foo: 'bar', bar: 'baz'})), 'hash object');
});

test('hashes identical objects with different key ordering', function(assert){
  assert.plan(2);
  var hash1 = hash({foo: 'bar', bar: 'baz'});
  var hash2 = hash({bar: 'baz', foo: 'bar'});
  var hash3 = hash({bar: 'foo', foo: 'baz'});
  assert.equal(hash1, hash2, 'hashes are equal');
  assert.notEqual(hash1, hash3, 'different objects not equal');
});

test('hashes only object keys when excludeValues option is set', function(assert){
  assert.plan(2);
  var hash1 = hash({foo: false, bar: 'OK'}, { excludeValues: true });
  var hash2 = hash({foo: true, bar: 'NO'}, { excludeValues: true });
  var hash3 = hash({foo: true, bar: 'OK', baz: false}, { excludeValues: true });
  assert.equal(hash1, hash2, 'values not in hash digest');
  assert.notEqual(hash1, hash3, 'different keys not equal');
});

test('array values are hashed', function(assert){
  assert.plan(1);
  var hash1 = hash({foo: ['bar', 'baz'], bax: true });
  var hash2 = hash({foo: ['baz', 'bar'], bax: true });
  assert.notEqual(hash1, hash2, 'different array orders are unique');
});

test('nested object values are hashed', function(assert){
  assert.plan(2);
  var hash1 = hash({foo: {bar: true, bax: 1}});
  var hash2 = hash({foo: {bar: true, bax: 1}});
  var hash3 = hash({foo: {bar: false, bax: 1}});
  assert.equal(hash1, hash2, 'hashes are equal');
  assert.notEqual(hash1, hash3, 'different objects not equal');
});

test('sugar methods should be equivalent', function(assert){
  assert.plan(3);
  var obj = {foo: 'bar', baz: true};
  assert.equal(hash.keys(obj), hash(obj, {excludeValues: true}), 'keys');
  assert.equal(hash.MD5(obj), hash(obj, {algorithm: 'md5'}), 'md5');
  assert.equal(hash.keysMD5(obj),
    hash(obj, {algorithm: 'md5', excludeValues: true}), 'keys md5');
});

test('array of nested object values are hashed', function(assert){
  assert.plan(2);
  var hash1 = hash({foo: [ {bar: true, bax: 1}, {bar: false, bax: 2} ] });
  var hash2 = hash({foo: [ {bar: true, bax: 1}, {bar: false, bax: 2} ] });
  var hash3 = hash({foo: [ {bar: false, bax: 2} ] });
  assert.equal(hash1, hash2, 'hashes are equal');
  assert.notEqual(hash1, hash3, 'different objects not equal');
});

test("recursive objects don't blow up stack", function(assert) {
  assert.plan(1);
  var hash1 = {foo: 'bar'};
  hash1.recursive = hash1;
  assert.doesNotThrow(function(){hash(hash1);}, /Maximum call stack size exceeded/, 'Should not throw an stack size exceeded exception');
});

test("recursive arrays don't blow up stack", function(assert) {
  assert.plan(1);
  var hash1 = ['foo', 'bar'];
  hash1.push(hash1);
  assert.doesNotThrow(function(){hash(hash1);}, /Maximum call stack size exceeded/, 'Should not throw an stack size exceeded exception');
});

test("recursive handling tracks identity", function(assert) {
  assert.plan(1);
  var hash1 = {k1: {k: 'v'}, k2: {k: 'k2'}};
  hash1.k1.r1 = hash1.k1;
  hash1.k2.r2 = hash1.k2;
  var hash2 = {k1: {k: 'v'}, k2: {k: 'k2'}};
  hash2.k1.r1 = hash2.k2;
  hash2.k2.r2 = hash2.k1;
  assert.notEqual(hash(hash1), hash(hash2), "order of recursive objects should matter");
});
<|endoftext|>


<commit_before>import {test} from "tape";
import {default as split, splitChars} from "../src/split.js";

test("split", (assert) => {

  for (let i = 0; i < splitChars.length; i++) {
    const char = splitChars[i];
    const arr = split(`test${char}test`);
    const first = char === " " ? "test" : `test${char}`;
    assert.true(arr[0] === first && arr[1] === "test", `split using "${char}"`);
  }

  assert.end();

});
<commit_msg>fixes unicode usage in split tests<commit_after>import {test} from "tape";
import {default as split, splitChars} from "../src/split.js";

test("split", (assert) => {

  for (let i = 0; i < splitChars.length; i++) {
    let char = splitChars[i];
    if (char.startsWith("u")) char = String.fromCharCode(`0x${char.slice(1)}`);
    const sentence = `test${char}test`;
    const arr = split(sentence);
    const first = char === " " ? "test" : `test${char}`;
    assert.true(arr[0] === first && arr[1] === "test", `split using "${char}"`);
  }

  assert.end();

});
<|endoftext|>


<commit_before>var test = require("tape")

var mercury = require("../index")

test("mercury is a object", function (assert) {
    assert.equal(typeof mercury, "object")
    assert.end()
})

require("./synthetic-events.js")
require("./count.js")
<commit_msg>run test on thingy<commit_after>var test = require("tape")

var mercury = require("../index")

test("mercury is a object", function (assert) {
    assert.equal(typeof mercury, "object")
    assert.end()
})

require("./synthetic-events.js")
require("./count.js")
require("./shared-state.js")
<|endoftext|>


<commit_before>//
// test/dork.js
//
// Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com>
// MIT Licensed
//
/*jshint asi: true, laxcomma: true*/
var should = require('should')

// These are here so my IDE will shut the hell up.
var before = global.before
  , before_each = global.beforeEach
  , describe = global.describe
  , it = global.it

describe('suite', function () {
  var suite_lib = require('../lib/suite')

  describe('#()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should return a suite object instance', function () {
      // To assert it's identity we're just going to make sure
      // some basic dork functions exist.
      should.exist(suite.add_suite)
      should.exist(suite.add_test)
      should.exist(suite.add_before)
      should.exist(suite.add_after_each)
    })

    it('should be a unique object each execution', function () {
      var new_suite = suite_lib()
        , old_suite = suite

      old_suite.foo = 'bar'
      should.not.exist(new_suite.foo)
    })

    it('should support a single description', function () {
      var description = 'foo'
        , suite = suite_lib(description)

      suite.description.should.equal(description)
      should.not.exist(suite.location)
    })

    it('should support a description and a location', function () {
      var description = 'foo'
        , location = 'bar'
        , suite = suite_lib(description, location)

      suite.description.should.equal(description)
      suite.location.should.equal(location)
    })
  })

  describe('#add_suite()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the suite to the stack', function (done) {
      var new_suite = suite_lib('foo', 'bar')
      suite.add_suite(new_suite)
      suite.stack.should.equal([new_suite])
    })
  })

  describe('#add_test()', function () {
    var test_lib = require('../lib/test')
      , suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the test to the stack', function (done) {
      var test = test_lib('foo', 'bar')
      suite.add_test(test)
      suite.stack.should.equal([test])
    })
  })

  describe('#add_before()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the given function to the before stack', function (done) {
      var fn = function () {}
      suite.add_before(fn)
      suite.before_stack.should.equal([fn])
    })
  })

  describe('#add_before_each()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the given function to the before each stack',
    function (done) {
      var fn = function () {}
      suite.add_before_each(fn)
      suite.before_each_stack.should.equal([fn])
    })
  })

  describe('#add_after()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the given function to the after stack', function (done) {
      var fn = function () {}
      suite.add_after(fn)
      suite.after_stack.should.equal([fn])
    })
  })

  describe('#add_after_each()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the given function to the after stack', function (done) {
      var fn = function () {}
      suite.add_after_each(fn)
      suite.after_each_stack.should.equal([fn])
    })
  })

  describe('#run()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })
  })
})<commit_msg>Removed a bunch of accidental async calls.<commit_after>//
// test/dork.js
//
// Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com>
// MIT Licensed
//
/*jshint asi: true, laxcomma: true*/
var should = require('should')

// These are here so my IDE will shut the hell up.
var before = global.before
  , before_each = global.beforeEach
  , describe = global.describe
  , it = global.it

describe('suite', function () {
  var suite_lib = require('../lib/suite')

  describe('#()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should return a suite object instance', function () {
      // To assert it's identity we're just going to make sure
      // some basic dork functions exist.
      should.exist(suite.add_suite)
      should.exist(suite.add_test)
      should.exist(suite.add_before)
      should.exist(suite.add_after_each)
    })

    it('should be a unique object each execution', function () {
      var new_suite = suite_lib()
        , old_suite = suite

      old_suite.foo = 'bar'
      should.not.exist(new_suite.foo)
    })

    it('should support a single description', function () {
      var description = 'foo'
        , suite = suite_lib(description)

      suite.description.should.equal(description)
      should.not.exist(suite.location)
    })

    it('should support a description and a location', function () {
      var description = 'foo'
        , location = 'bar'
        , suite = suite_lib(description, location)

      suite.description.should.equal(description)
      suite.location.should.equal(location)
    })
  })

  describe('#add_suite()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the suite to the stack', function () {
      var new_suite = suite_lib('foo', 'bar')
      suite.add_suite(new_suite)
      suite.stack.should.equal([new_suite])
    })
  })

  describe('#add_test()', function () {
    var test_lib = require('../lib/test')
      , suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the test to the stack', function () {
      var test = test_lib('foo', 'bar')
      suite.add_test(test)
      suite.stack.should.equal([test])
    })
  })

  describe('#add_before()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the given function to the before stack', function () {
      var fn = function () {}
      suite.add_before(fn)
      suite.before_stack.should.equal([fn])
    })
  })

  describe('#add_before_each()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the given function to the before each stack',
    function () {
      var fn = function () {}
      suite.add_before_each(fn)
      suite.before_each_stack.should.equal([fn])
    })
  })

  describe('#add_after()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the given function to the after stack', function () {
      var fn = function () {}
      suite.add_after(fn)
      suite.after_stack.should.equal([fn])
    })
  })

  describe('#add_after_each()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })

    it('should append the given function to the after stack', function () {
      var fn = function () {}
      suite.add_after_each(fn)
      suite.after_each_stack.should.equal([fn])
    })
  })

  describe('#run()', function () {
    var suite

    before_each(function () {
      suite = suite_lib()
    })
  })
})<|endoftext|>


<commit_before>var test = require('tape');

var JSONFile = require('../');

test('write', function (t) {
  t.plan(1);

  var obj = {"n":8,"msg":"Hello World 7bc59b8e-8a3f-2d04-62eb-8c9f5c39606f","tmx":1388775322979};

  JSONFile.writeFile(obj, 'test/write.json', {encoding: 'ascii'}, function (err) {
    if (err) t.error(err, 'write json to file');

    t.pass('write json object to file.');
  });

});

test('write sync', function (t) {
  t.plan(1);

  var obj = {"n":8,"msg":"Hello World 7bc59b8e-8a3f-2d04-62eb-8c9f5c39606f","tmx":1388775322979};

  try {
    JSONFile.writeFileSync(obj, 'test/write_sync.json', {encoding: 'ascii'});
    t.pass('write sync json object to file.');
  } catch (err) {
    t.error(err);
  }

});

test('read', function (t) {
  t.plan(1);

  JSONFile.readFile('test/write.json', function (err, data) {
    if (err) t.error(err, 'write json to file');

    t.deepEqual(typeof data, 'object', JSON.stringify(data));
  });

});

test('read sync', function (t) {
  t.plan(1);

  try {
    var data = JSONFile.readFileSync('test/write_sync.json');
    t.deepEqual(typeof data, 'object', JSON.stringify(data));
  } catch (err) {
    t.error(err);
  }

});<commit_msg>Update unit test<commit_after>var test = require('tape');

var JSONFile = require('../');

test('write', function (t) {
  t.plan(1);

  var obj = {"n":8,"msg":"Hello World 7bc59b8e-8a3f-2d04-62eb-8c9f5c39606f","tmx":1388775322979};

  JSONFile.writeFile(obj, 'test/write.json', {encoding: 'ascii'}, function (err) {
    if (err) t.error(err, 'write json to file');

    t.pass('write json object to file.');
  });
});

test('write sync', function (t) {
  t.plan(1);

  var obj = {"n":8,"msg":"Hello World 7bc59b8e-8a3f-2d04-62eb-8c9f5c39606f","tmx":1388775322979};

  try {
    JSONFile.writeFileSync(obj, 'test/write_sync.json', {encoding: 'ascii'});
    t.pass('write sync json object to file.');
  } catch (err) {
    t.error(err);
  }
});

test('read', function (t) {
  t.plan(1);

  JSONFile.readFile('test/write.json', function (err, data) {
    if (err) t.error(err, 'write json to file');

    t.deepEqual(typeof data, 'object', JSON.stringify(data));
  });
});

test('read sync', function (t) {
  t.plan(1);

  try {
    var data = JSONFile.readFileSync('test/write_sync.json');
    t.deepEqual(typeof data, 'object', JSON.stringify(data));
  } catch (err) {
    t.error(err);
  }
});<|endoftext|>


<commit_before>var expect = require('chai').expect;
var util = require('util');

var testData = require('./data')

describe('Agent loader outside of known PaaS env', function () {
    this.timeout(15000);

    it('should return with _rx.cfg set', function (done) {
        require('../index')({
                server: testData.server,
                tenant: testData.environmentid,
                tenanttoken: testData.tenanttoken
            }
        );

        expect(process.env.RUXIT_HOST_ID).to.not.be.defined;
        expect(process.env.RUXIT_CLUSTER_ID).to.not.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.not.be.defined;
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.not.be.defined;
        expect(global._rx_cfg).to.be.defined;

        done();
    });

    it('should throw with no credentials given', function (done) {

        expect(function () {
            require('../index')()
        }).to.throw(Error);
        done();
    });
});

describe('Agent loader outside of known PaaS env using apitoken', function () {
    this.timeout(15000);

    it('should return with _rx.cfg set', function (done) {
        require('../index')({
                server: testData.server,
                tenant: testData.environmentid,
                apitoken: testData.apitoken
            }
        );

        expect(process.env.RUXIT_HOST_ID).to.not.be.defined;
        expect(process.env.RUXIT_CLUSTER_ID).to.not.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.not.be.defined;
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.not.be.defined;
        expect(global._rx_cfg).to.be.defined;

        done();
    });

    it('should throw with no credentials given', function (done) {

        expect(function () {
            require('../index')()
        }).to.throw(Error);
        done();
    });
});

describe("Agent loader within Cloud Foundry VCAP_SERVICES['ruxit'] set", function () {
    this.timeout(15000);

    it("should set global and environment variables", function (done) {
        var vcapServices = {
            'ruxit-service': [{
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "tenanttoken": testData.tenanttoken
                    },
                    "label": "ruxit",
                    "name": "test-1",
                    "plan": 'someplan',
                    "tags": [
                        "ruxit",
                        "performance",
                        "monitoring",
                        "apm",
                        "analytics"
                    ]
                }
            ]
        };

        var vcapApplication = {
            "application_name" : "test-1"
        };

        process.env.VCAP_APPLICATION = JSON.stringify(vcapApplication);

        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);
        process.env.CF_INSTANCE_INDEX = 1;

        require('../index')();

        expect(process.env.RUXIT_HOST_ID).to.be.defined;
        // expect(process.env.RUXIT_CLUSTER_ID).to.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.equal('test-1');
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.be.defined;

        expect(global._rx_cfg).to.be.defined;
        done();
    });
});

describe("Agent loader within Cloud Foundry VCAP_SERVICES['dynatrace-service'] set using apitoken", function () {
    this.timeout(15000);

    it("should set global and environment variables", function (done) {
        var vcapServices = {
            'dynatrace-service': [{
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "apitoken": testData.apitoken
                    },
                    "label": "ruxit",
                    "name": "test-1",
                    "plan": 'someplan',
                    "tags": [
                        "ruxit",
                        "performance",
                        "monitoring",
                        "apm",
                        "analytics"
                    ]
                }
            ]
        };

        var vcapApplication = {
            "application_name" : "test-1"
        };

        process.env.VCAP_APPLICATION = JSON.stringify(vcapApplication);

        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);
        process.env.CF_INSTANCE_INDEX = 1;

        require('../index')();

        expect(process.env.RUXIT_HOST_ID).to.be.defined;
        // expect(process.env.RUXIT_CLUSTER_ID).to.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.equal('test-1');
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.be.defined;

        expect(global._rx_cfg).to.be.defined;
        done();
    });
});

describe("Agent loader within Cloud Foundry VCAP_SERVICES['user-provided'] set", function () {
    this.timeout(15000);

    it("should set global and environment variables", function (done) {

        var vcapServices = {
            'user-provided': [
                {
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "tenanttoken": testData.tenanttoken
                    },
                    "label": "user-provided",
                    "name": "test-2",
                    "syslog_drain_url": "",
                    "tags": []
                },
                {
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "tenanttoken": testData.tenanttoken
                    },
                    "label": "dynatrace-service",
                    "name": "test-3",
                    "syslog_drain_url": "",
                    "tags": []
                }
            ]
        };

        var vcapApplication = {
            "application_name" : "test-3"
        };
        process.env.VCAP_APPLICATION = JSON.stringify(vcapApplication);

        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);
        process.env.CF_INSTANCE_INDEX = 2;
        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);

        require('../index')();

        expect(process.env.RUXIT_HOST_ID).to.be.defined;
        expect(process.env.RUXIT_CLUSTER_ID).to.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.equal('test-3');
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.be.defined;

        expect(global._rx_cfg).to.be.defined;
        done();
    });
});

describe("Agent loader within Cloud Foundry VCAP_SERVICES['user-provided'] set using apitoken and tags", function () {
    this.timeout(15000);

    it("should set global and environment variables", function (done) {

        var vcapServices = {
            'user-provided': [
                {
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "tenanttoken": testData.tenanttoken
                    },
                    "label": "user-provided",
                    "name": "test-2",
                    "syslog_drain_url": "",
                    "tags": []
                },
                {
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "aüitoken": testData.apitoken
                    },
                    "label": "some-service",
                    "name": "test-3",
                    "syslog_drain_url": "",
                    "tags": ['foo', 'bar', 'dynatrace']
                }
            ]
        };

        var vcapApplication = {
            "application_name" : "test-3"
        };
        process.env.VCAP_APPLICATION = JSON.stringify(vcapApplication);

        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);
        process.env.CF_INSTANCE_INDEX = 2;
        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);

        require('../index')();

        expect(process.env.RUXIT_HOST_ID).to.be.defined;
        expect(process.env.RUXIT_CLUSTER_ID).to.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.equal('test-3');
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.be.defined;

        expect(global._rx_cfg).to.be.defined;
        done();
    });

});<commit_msg>Added test for apiurl<commit_after>var expect = require('chai').expect;
var util = require('util');

var testData = require('./data')

describe('Agent loader outside of known PaaS env', function () {
    this.timeout(15000);

    it('should return with _rx.cfg set', function (done) {
        require('../index')({
                server: testData.server,
                tenant: testData.environmentid,
                tenanttoken: testData.tenanttoken
            }
        );

        expect(process.env.RUXIT_HOST_ID).to.not.be.defined;
        expect(process.env.RUXIT_CLUSTER_ID).to.not.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.not.be.defined;
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.not.be.defined;
        expect(global._rx_cfg).to.be.defined;

        done();
    });

    it('should throw with no credentials given', function (done) {

        expect(function () {
            require('../index')()
        }).to.throw(Error);
        done();
    });
});

describe('Agent loader outside of known PaaS env using apitoken', function () {
    this.timeout(15000);

    it('should return with _rx.cfg set', function (done) {
        require('../index')({
                server: testData.server,
                tenant: testData.environmentid,
                apitoken: testData.apitoken
            }
        );

        expect(process.env.RUXIT_HOST_ID).to.not.be.defined;
        expect(process.env.RUXIT_CLUSTER_ID).to.not.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.not.be.defined;
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.not.be.defined;
        expect(global._rx_cfg).to.be.defined;

        done();
    });

    it('should throw with no credentials given', function (done) {

        expect(function () {
            require('../index')()
        }).to.throw(Error);
        done();
    });
});

describe("Agent loader within Cloud Foundry VCAP_SERVICES['ruxit'] set", function () {
    this.timeout(15000);

    it("should set global and environment variables", function (done) {
        var vcapServices = {
            'ruxit-service': [{
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "tenanttoken": testData.tenanttoken
                    },
                    "label": "ruxit",
                    "name": "test-1",
                    "plan": 'someplan',
                    "tags": [
                        "ruxit",
                        "performance",
                        "monitoring",
                        "apm",
                        "analytics"
                    ]
                }
            ]
        };

        var vcapApplication = {
            "application_name" : "test-1"
        };

        process.env.VCAP_APPLICATION = JSON.stringify(vcapApplication);

        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);
        process.env.CF_INSTANCE_INDEX = 1;

        require('../index')();

        expect(process.env.RUXIT_HOST_ID).to.be.defined;
        // expect(process.env.RUXIT_CLUSTER_ID).to.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.equal('test-1');
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.be.defined;

        expect(global._rx_cfg).to.be.defined;
        done();
    });
});

describe("Agent loader within Cloud Foundry VCAP_SERVICES['dynatrace-service'] set using apitoken", function () {
    this.timeout(15000);

    it("should set global and environment variables", function (done) {
        var vcapServices = {
            'dynatrace-service': [{
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "apitoken": testData.apitoken
                    },
                    "label": "ruxit",
                    "name": "test-1",
                    "plan": 'someplan',
                    "tags": [
                        "ruxit",
                        "performance",
                        "monitoring",
                        "apm",
                        "analytics"
                    ]
                }
            ]
        };

        var vcapApplication = {
            "application_name" : "test-1"
        };

        process.env.VCAP_APPLICATION = JSON.stringify(vcapApplication);

        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);
        process.env.CF_INSTANCE_INDEX = 1;

        require('../index')();

        expect(process.env.RUXIT_HOST_ID).to.be.defined;
        // expect(process.env.RUXIT_CLUSTER_ID).to.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.equal('test-1');
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.be.defined;

        expect(global._rx_cfg).to.be.defined;
        done();
    });
});

describe("Agent loader within Cloud Foundry VCAP_SERVICES['dynatrace-service'] set using apitoken and apiurl", function () {
    this.timeout(15000);

    it("should set global and environment variables", function (done) {
        var vcapServices = {
            'dynatrace-service': [{
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "apitoken": testData.apitoken,
                        "apiurl": testData.apiurl,
                    },
                    "label": "ruxit",
                    "name": "test-1",
                    "plan": 'someplan',
                    "tags": [
                        "ruxit",
                        "performance",
                        "monitoring",
                        "apm",
                        "analytics"
                    ]
                }
            ]
        };

        var vcapApplication = {
            "application_name" : "test-1"
        };

        process.env.VCAP_APPLICATION = JSON.stringify(vcapApplication);

        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);
        process.env.CF_INSTANCE_INDEX = 1;

        require('../index')();

        expect(process.env.RUXIT_HOST_ID).to.be.defined;
        // expect(process.env.RUXIT_CLUSTER_ID).to.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.equal('test-1');
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.be.defined;

        expect(global._rx_cfg).to.be.defined;
        done();
    });
});

describe("Agent loader within Cloud Foundry VCAP_SERVICES['user-provided'] set", function () {
    this.timeout(15000);

    it("should set global and environment variables", function (done) {

        var vcapServices = {
            'user-provided': [
                {
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "tenanttoken": testData.tenanttoken
                    },
                    "label": "user-provided",
                    "name": "test-2",
                    "syslog_drain_url": "",
                    "tags": []
                },
                {
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "tenanttoken": testData.tenanttoken
                    },
                    "label": "dynatrace-service",
                    "name": "test-3",
                    "syslog_drain_url": "",
                    "tags": []
                }
            ]
        };

        var vcapApplication = {
            "application_name" : "test-3"
        };
        process.env.VCAP_APPLICATION = JSON.stringify(vcapApplication);

        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);
        process.env.CF_INSTANCE_INDEX = 2;
        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);

        require('../index')();

        expect(process.env.RUXIT_HOST_ID).to.be.defined;
        expect(process.env.RUXIT_CLUSTER_ID).to.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.equal('test-3');
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.be.defined;

        expect(global._rx_cfg).to.be.defined;
        done();
    });
});

describe("Agent loader within Cloud Foundry VCAP_SERVICES['user-provided'] set using apitoken and tags", function () {
    this.timeout(15000);

    it("should set global and environment variables", function (done) {

        var vcapServices = {
            'user-provided': [
                {
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "tenanttoken": testData.tenanttoken
                    },
                    "label": "user-provided",
                    "name": "test-2",
                    "syslog_drain_url": "",
                    "tags": []
                },
                {
                    "credentials": {
                        "server": testData.server,
                        "tenant": testData.environmentid,
                        "aüitoken": testData.apitoken
                    },
                    "label": "some-service",
                    "name": "test-3",
                    "syslog_drain_url": "",
                    "tags": ['foo', 'bar', 'dynatrace']
                }
            ]
        };

        var vcapApplication = {
            "application_name" : "test-3"
        };
        process.env.VCAP_APPLICATION = JSON.stringify(vcapApplication);

        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);
        process.env.CF_INSTANCE_INDEX = 2;
        process.env.VCAP_SERVICES = JSON.stringify(vcapServices);

        require('../index')();

        expect(process.env.RUXIT_HOST_ID).to.be.defined;
        expect(process.env.RUXIT_CLUSTER_ID).to.be.defined;
        expect(process.env.RUXIT_APPLICATIONID).to.equal('test-3');
        expect(process.env.RUXIT_IGNOREDYNAMICPORT).to.be.defined;

        expect(global._rx_cfg).to.be.defined;
        done();
    });

});<|endoftext|>