<commit_before>import test from 'ava'
import mongoose, { Schema as MongooseSchema } from 'mongoose'
import Model from './Model'
import Schema, { pre, post } from './Schema'

mongoose.Promise = Promise

// Mock saves, for testing hooks.
mongoose.Model.prototype.save = function (cb) {
  setTimeout(() => cb(null, this), 1)
}

@Schema
class PersonSchema {
  static schema = {
    name: String,
    age: Number
  };

  static randomPerson () {
    return new this({
      name: 'Random Person',
      age: Math.floor(Math.random() * 100)
    })
  }

  static get count () {
    return 10
  }

  incrementAge () {
    this.age = this.nextAge
  }

  get nextAge () {
    return this.age + 1
  }
  set nextAge (age) {
    this.age = age - 1
  }
}

let modelN = 0
function modelify (schema) {
  return mongoose.model(`Model_${modelN++}`, schema)
}

test('@Schema converts an ES2016 class to a mongoose.Schema', (t) => {
  const schema = new PersonSchema()
  t.truthy(schema !== null)
  t.truthy(schema instanceof MongooseSchema)
})

test('@Schema keeps instance methods', (t) => {
  const schema = new PersonSchema()
  t.is(typeof schema.methods.incrementAge, 'function')

  const Person = modelify(schema)
  const person = new Person({ name: 'Instance methods', age: 12 })
  t.is(person.age, 12)
  person.incrementAge()
  t.is(person.age, 13)
})

test('@Schema adds virtuals for instance getters and setters', (t) => {
  const schema = new PersonSchema()
  t.is(typeof schema.virtuals.nextAge, 'object')
  t.is(schema.virtuals.nextAge.getters.length, 1)
  t.is(schema.virtuals.nextAge.setters.length, 1)

  const Person = modelify(schema)
  const person = new Person({ name: 'Virtual Types', age: 19 })
  t.is(person.nextAge, 20)
  person.nextAge = 25
  t.is(person.age, 24)
})

test('@Schema keeps static methods', (t) => {
  const schema = new PersonSchema()
  t.is(typeof modelify(schema).randomPerson, 'function')
})

test('@Schema supports static property getter/setters', (t) => {
  const Person = modelify(new PersonSchema())
  t.is(Person.count, 10)
})

test('`this` in static methods passed to @Schema binds to the generated Model class', (t) => {
  const Person = modelify(new PersonSchema())
  t.truthy(Person.randomPerson() instanceof Person)
})

test('Schema options can be defined as static class properties', (t) => {
  const schema = new (
    @Schema
    class {
      static typeKey = 'anotherType';
    }
  )()

  t.is(schema.options.typeKey, 'anotherType')
})

test('Schema options passed to @Schema override options defined in the class body', (t) => {
  const schema = new (
    @Schema({ typeKey: 'definedInDecorator' })
    class {
      static typeKey = 'definedInClass';
      static versionKey = 'alsoDefinedInClass';
    }
  )()

  t.is(schema.options.typeKey, 'definedInDecorator')
  t.is(schema.options.versionKey, 'alsoDefinedInClass')
})

test('@Model(className) registers a new model with mongoose', (t) => {
  @Model('ModelTest0')
  class Anon { // eslint-disable-line no-unused-vars
    static schema = { value: String };
  }
  t.truthy(mongoose.modelNames().indexOf('ModelTest0') !== -1)
})

test('@Model and @Model() infer the model name from the decorated class', (t) => {
  @Model
  class ModelTest1 { // eslint-disable-line no-unused-vars
    static schema = { a: String };
  }
  t.truthy(mongoose.modelNames().indexOf('ModelTest1') !== -1)

  @Model()
  class ModelTest2 { // eslint-disable-line no-unused-vars
    static schema = { b: String };
  }
  t.truthy(mongoose.modelNames().indexOf('ModelTest2') !== -1)
})

test('@Model(options) are passed to the schema constructor', (t) => {
  @Model({ typeKey: 'tests!' })
  class ModelTestWithOptions { // eslint-disable-line no-unused-vars
    static schema = { c: String };
  }

  const retrievedOptions = mongoose.modelSchemas.ModelTestWithOptions.options
  t.is(retrievedOptions.typeKey, 'tests!')
})

test('@Model({ connection }) registers the model on a non-default connection', (t) => {
  const testConnection = mongoose.createConnection()
  @Model({ connection: testConnection })
  class CustomConnection {
    static schema = { d: String };
  }

  t.is(testConnection.model('CustomConnection'), CustomConnection)
  t.not(mongoose.model('CustomConnection'), CustomConnection)
})

test('@Model uses "connection" option from static key', (t) => {
  const testConnection = mongoose.createConnection()
  @Model
  class CustomConnection {
    static connection = testConnection;
    static schema = { e: String };
  }

  t.is(testConnection.model('CustomConnection'), CustomConnection)
  t.not(mongoose.model('CustomConnection'), CustomConnection)
})

test('instanceof works with @Model classes', (t) => {
  @Model
  class User {
    static schema = { name: String };
  }
  t.truthy(new User() instanceof User)
})

test('@pre(\'method\') adds a hook to "method"', (t) => {
  let hookRan = false
  @Schema
  class TestSchema {
    @pre('save')
    logSave () {
      hookRan = true
    }
  }

  const TestModel = modelify(new TestSchema())
  t.is(hookRan, false)
  return new TestModel().save()
    .then(() => t.is(hookRan, true))
})

test('@pre(\'method\') hooks that do not call `next()` have the correct `this`', (t) => {
  let hookModel = null
  @Schema
  class TestSchema {
    @pre('save')
    logSave () {
      hookModel = this
    }
  }

  const model = new (
    modelify(new TestSchema())
  )()
  t.is(hookModel, null)
  return model.save()
    .then(() => t.is(hookModel, model))
})

test('@post(\'validate\') should not call `next()`', (t) => {
  let hookModel = null
  @Schema
  class TestSchema {
    @post('validate')
    logValidate () {
      hookModel = this
    }
  }

  const model = new (
    modelify(new TestSchema())
  )()
  t.is(hookModel, null)
  t.notThrows(model.save)
})

test('@post(\'validate\') have the correct `this`', (t) => {
  let hookModel = null
  @Schema
  class TestSchema {
    @post('validate')
    logValidate () {
      hookModel = this
    }
  }

  const model = new (
    modelify(new TestSchema())
  )()
  t.is(hookModel, null)
  return model.save()
    .then(() => t.is(hookModel, model))
})
<commit_msg>Fix `this` binding in test.<commit_after>import test from 'ava'
import mongoose, { Schema as MongooseSchema } from 'mongoose'
import Model from './Model'
import Schema, { pre, post } from './Schema'

mongoose.Promise = Promise

// Mock saves, for testing hooks.
mongoose.Model.prototype.save = function (cb) {
  setTimeout(() => cb(null, this), 1)
}

@Schema
class PersonSchema {
  static schema = {
    name: String,
    age: Number
  };

  static randomPerson () {
    return new this({
      name: 'Random Person',
      age: Math.floor(Math.random() * 100)
    })
  }

  static get count () {
    return 10
  }

  incrementAge () {
    this.age = this.nextAge
  }

  get nextAge () {
    return this.age + 1
  }
  set nextAge (age) {
    this.age = age - 1
  }
}

let modelN = 0
function modelify (schema) {
  return mongoose.model(`Model_${modelN++}`, schema)
}

test('@Schema converts an ES2016 class to a mongoose.Schema', (t) => {
  const schema = new PersonSchema()
  t.truthy(schema !== null)
  t.truthy(schema instanceof MongooseSchema)
})

test('@Schema keeps instance methods', (t) => {
  const schema = new PersonSchema()
  t.is(typeof schema.methods.incrementAge, 'function')

  const Person = modelify(schema)
  const person = new Person({ name: 'Instance methods', age: 12 })
  t.is(person.age, 12)
  person.incrementAge()
  t.is(person.age, 13)
})

test('@Schema adds virtuals for instance getters and setters', (t) => {
  const schema = new PersonSchema()
  t.is(typeof schema.virtuals.nextAge, 'object')
  t.is(schema.virtuals.nextAge.getters.length, 1)
  t.is(schema.virtuals.nextAge.setters.length, 1)

  const Person = modelify(schema)
  const person = new Person({ name: 'Virtual Types', age: 19 })
  t.is(person.nextAge, 20)
  person.nextAge = 25
  t.is(person.age, 24)
})

test('@Schema keeps static methods', (t) => {
  const schema = new PersonSchema()
  t.is(typeof modelify(schema).randomPerson, 'function')
})

test('@Schema supports static property getter/setters', (t) => {
  const Person = modelify(new PersonSchema())
  t.is(Person.count, 10)
})

test('`this` in static methods passed to @Schema binds to the generated Model class', (t) => {
  const Person = modelify(new PersonSchema())
  t.truthy(Person.randomPerson() instanceof Person)
})

test('Schema options can be defined as static class properties', (t) => {
  const schema = new (
    @Schema
    class {
      static typeKey = 'anotherType';
    }
  )()

  t.is(schema.options.typeKey, 'anotherType')
})

test('Schema options passed to @Schema override options defined in the class body', (t) => {
  const schema = new (
    @Schema({ typeKey: 'definedInDecorator' })
    class {
      static typeKey = 'definedInClass';
      static versionKey = 'alsoDefinedInClass';
    }
  )()

  t.is(schema.options.typeKey, 'definedInDecorator')
  t.is(schema.options.versionKey, 'alsoDefinedInClass')
})

test('@Model(className) registers a new model with mongoose', (t) => {
  @Model('ModelTest0')
  class Anon { // eslint-disable-line no-unused-vars
    static schema = { value: String };
  }
  t.truthy(mongoose.modelNames().indexOf('ModelTest0') !== -1)
})

test('@Model and @Model() infer the model name from the decorated class', (t) => {
  @Model
  class ModelTest1 { // eslint-disable-line no-unused-vars
    static schema = { a: String };
  }
  t.truthy(mongoose.modelNames().indexOf('ModelTest1') !== -1)

  @Model()
  class ModelTest2 { // eslint-disable-line no-unused-vars
    static schema = { b: String };
  }
  t.truthy(mongoose.modelNames().indexOf('ModelTest2') !== -1)
})

test('@Model(options) are passed to the schema constructor', (t) => {
  @Model({ typeKey: 'tests!' })
  class ModelTestWithOptions { // eslint-disable-line no-unused-vars
    static schema = { c: String };
  }

  const retrievedOptions = mongoose.modelSchemas.ModelTestWithOptions.options
  t.is(retrievedOptions.typeKey, 'tests!')
})

test('@Model({ connection }) registers the model on a non-default connection', (t) => {
  const testConnection = mongoose.createConnection()
  @Model({ connection: testConnection })
  class CustomConnection {
    static schema = { d: String };
  }

  t.is(testConnection.model('CustomConnection'), CustomConnection)
  t.not(mongoose.model('CustomConnection'), CustomConnection)
})

test('@Model uses "connection" option from static key', (t) => {
  const testConnection = mongoose.createConnection()
  @Model
  class CustomConnection {
    static connection = testConnection;
    static schema = { e: String };
  }

  t.is(testConnection.model('CustomConnection'), CustomConnection)
  t.not(mongoose.model('CustomConnection'), CustomConnection)
})

test('instanceof works with @Model classes', (t) => {
  @Model
  class User {
    static schema = { name: String };
  }
  t.truthy(new User() instanceof User)
})

test('@pre(\'method\') adds a hook to "method"', (t) => {
  let hookRan = false
  @Schema
  class TestSchema {
    @pre('save')
    logSave () {
      hookRan = true
    }
  }

  const TestModel = modelify(new TestSchema())
  t.is(hookRan, false)
  return new TestModel().save()
    .then(() => t.is(hookRan, true))
})

test('@pre(\'method\') hooks that do not call `next()` have the correct `this`', (t) => {
  let hookModel = null
  @Schema
  class TestSchema {
    @pre('save')
    logSave () {
      hookModel = this
    }
  }

  const model = new (
    modelify(new TestSchema())
  )()
  t.is(hookModel, null)
  return model.save()
    .then(() => t.is(hookModel, model))
})

test('@post(\'validate\') should not call `next()`', (t) => {
  let hookModel = null
  @Schema
  class TestSchema {
    @post('validate')
    logValidate () {
      hookModel = this
    }
  }

  const model = new (
    modelify(new TestSchema())
  )()
  t.is(hookModel, null)
  t.notThrows(model.save.bind(model))
})

test('@post(\'validate\') have the correct `this`', (t) => {
  let hookModel = null
  @Schema
  class TestSchema {
    @post('validate')
    logValidate () {
      hookModel = this
    }
  }

  const model = new (
    modelify(new TestSchema())
  )()
  t.is(hookModel, null)
  return model.save()
    .then(() => t.is(hookModel, model))
})
<|endoftext|>


<commit_before>'use strict';
var globby = require('globby');
console.log(globby.sync(['./docs/**/*']));<commit_msg>chore(test): remove useless test script<commit_after><|endoftext|>


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

const testPaths = [
  './test/parallel/test-assert-async.js',
  './test/parallel/test-assert-checktag.js',
  './test/parallel/test-assert-deep.js',
  './test/parallel/test-assert-fail-deprecation.js',
  './test/parallel/test-assert-fail.js',
  './test/parallel/test-assert-if-error.js',
  './test/parallel/test-assert-typedarray-deepequal.js',
  './test/parallel/test-assert.js',
  './test/pseudo-tty/test-assert-colors.js',
  './test/pseudo-tty/test-assert-no-color.js',
  './test/pseudo-tty/test-assert-position-indicator.js'
];

testPaths.forEach(testPath => {
  test(testPath, t => {
    t.plan(2)
    let result;
    t.doesNotThrow(() => {
      result = require(testPath);
    });
    Promise.resolve(result)
      .then(() => false)
      .catch(error => error)
      .then(resolved => t.error(resolved, 'should not resolve to rejected Promise'));
  });
});
<commit_msg>Create require wrapper so browserify can resolve test files<commit_after>const test = require('tape');

const testPaths = [
  ['test-assert-async.js', () => require('./test/parallel/test-assert-async.js')],
  ['test-assert-checktag.js', () => require('./test/parallel/test-assert-checktag.js')],
  ['test-assert-deep.js', () => require('./test/parallel/test-assert-deep.js')],
  ['test-assert-fail-deprecation.js', () => require('./test/parallel/test-assert-fail-deprecation.js')],
  ['test-assert-fail.js', () => require('./test/parallel/test-assert-fail.js')],
  ['test-assert-if-error.js', () => require('./test/parallel/test-assert-if-error.js')],
  ['test-assert-typedarray-deepequal.js', () => require('./test/parallel/test-assert-typedarray-deepequal.js')],
  ['test-assert.js', () => require('./test/parallel/test-assert.js')],
  ['test-assert-colors.js', () => require('./test/pseudo-tty/test-assert-colors.js')],
  ['test-assert-no-color.js', () => require('./test/pseudo-tty/test-assert-no-color.js')],
  ['test-assert-position-indicator.js', () => require('./test/pseudo-tty/test-assert-position-indicator.js')]
];

testPaths.forEach(([testName, requireTest]) => {
  test(testName, t => {
    t.plan(2)
    let result;
    t.doesNotThrow(() => {
      result = requireTest();
    });
    Promise.resolve(result)
      .then(() => false)
      .catch(error => error)
      .then(resolved => t.error(resolved, 'should not resolve to rejected Promise'));
  });
});
<|endoftext|>


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

var tests = [

	function is_writable_and_readable() {
		var req = new MockRequest();
		assert(req.readable);
		assert(req.writable);

		next();
	},

	function default_options() {
		var req = new MockRequest();

		assert.equal(typeof req.url, 'string');
		assert.equal(req.method, 'GET');
		assert.deepEqual(req.headers, {});
		assert.deepEqual(req.rawHeaders, []);

		next()
	},

	function parses_headers() {
		var req = new MockRequest({
			headers: {
				'Content-Type': 'text/plain',
				'Content-Length': 10
			}
		});

		assert.equal(req.headers['content-type'], 'text/plain');
		assert.equal(req.headers['content-length'], '10');
		assert.deepEqual(req.rawHeaders, [
			'Content-Type',
			'text/plain',
			'Content-Length',
			'10'
		]);

		next()
	},

	function automatically_ends_for_bodiless() {
		var ends = {
			GET: true,
			HEAD: true,
			DELETE: true,
			POST: false,
			PUT: false,
			WHATEVS: false
		};

		Object.keys(ends).forEach(function(method) {
			var req = new MockRequest({
				method: method
			});

			assert.equal(req._writableState.ended, ends[method], method);
		});

		next();
	},

	function string_body() {
		var req = new MockRequest({
			method: 'POST'
		});

		req.write('hello', 'utf8');
		req.end();

		req.setEncoding('utf8');
		req.once('readable', function() {
			var d = this.read();
			assert.equal(d, 'hello');
			next();
		});
	},

	function json_body() {
		var req = new MockRequest({
			method: 'POST'
		});

		req.write({
			hello: 3
		});
		req.end();

		req.setEncoding('utf8');
		req.once('readable', function() {
			var d = this.read();
			assert.deepEqual(d, '{"hello":3}');
			next();
		});
	},

	function buffer_body() {
		var req = new MockRequest({
			method: 'POST'
		});

		var buf = new Buffer('yo', 'utf8');
		req.write(buf);
		req.end();

		req.once('readable', function() {
			var d = this.read();
			assert.equal(d, buf);
			next();
		});
	},

	function fails() {
		var req = new MockRequest({
			method: 'POST'
		});

		var err = new Error('Oops');
		req._fail(err);

		req.on('error', function(err2) {
			assert.equal(err, err2);
			next();
		});

		req.write('yo');
	}

];

var ready = true;

function next() {
	ready = true;
}

setInterval(function() {
	if (!ready) return;
	var test = tests.shift();
	if (!test) {
		console.log('All tests passed');
		return process.exit(0);
	}

	ready = false;
	test();
}, 0);<commit_msg>Improved test function<commit_after>var assert = require('assert'),
	MockRequest = require('./index');

var tests = [

	function is_writable_and_readable(done) {
		var req = new MockRequest();
		assert(req.readable);
		assert(req.writable);

		done();
	},

	function default_options(done) {
		var req = new MockRequest();

		assert.equal(typeof req.url, 'string');
		assert.equal(req.method, 'GET');
		assert.deepEqual(req.headers, {});
		assert.deepEqual(req.rawHeaders, []);

		done()
	},

	function parses_headers(done) {
		var req = new MockRequest({
			headers: {
				'Content-Type': 'text/plain',
				'Content-Length': 10
			}
		});

		assert.equal(req.headers['content-type'], 'text/plain');
		assert.equal(req.headers['content-length'], '10');
		assert.deepEqual(req.rawHeaders, [
			'Content-Type',
			'text/plain',
			'Content-Length',
			'10'
		]);

		done()
	},

	function automatically_ends_for_bodiless(done) {
		var ends = {
			GET: true,
			HEAD: true,
			DELETE: true,
			POST: false,
			PUT: false,
			WHATEVS: false
		};

		Object.keys(ends).forEach(function(method) {
			var req = new MockRequest({
				method: method
			});

			assert.equal(req._writableState.ended, ends[method], method);
		});

		done();
	},

	function string_body(done) {
		var req = new MockRequest({
			method: 'POST'
		});

		req.write('hello', 'utf8');
		req.end();

		req.setEncoding('utf8');
		req.once('readable', function() {
			var d = this.read();
			assert.equal(d, 'hello');
			done();
		});
	},

	function json_body(done) {
		var req = new MockRequest({
			method: 'POST'
		});

		req.write({
			hello: 3
		});
		req.end();

		req.setEncoding('utf8');
		req.once('readable', function() {
			var d = this.read();
			assert.deepEqual(d, '{"hello":3}');
			done();
		});
	},

	function buffer_body(done) {
		var req = new MockRequest({
			method: 'POST'
		});

		var buf = new Buffer('yo', 'utf8');
		req.write(buf);
		req.end();

		req.once('readable', function() {
			var d = this.read();
			assert.equal(d, buf);
			done();
		});
	},

	function fails(done) {
		var req = new MockRequest({
			method: 'POST'
		});

		var err = new Error('Oops');
		req._fail(err);

		req.on('error', function(err2) {
			assert.equal(err, err2);
			done();
		});

		req.write('yo');
	}

];

var doneCount = 0;
tests.forEach(function(test) {
	test(done.bind(null, test.name));
});

function done(name) {
	console.log(name);
	doneCount++;

	if (doneCount === tests.length) {
		console.log('>> All tests passed');
		return process.exit(0);
	}
}<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014, 2016 Tim Kuijsten
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

'use strict';

var assert = require('assert');

var escaper = require('./index');

var obj;

/* escape */

/* don't fall over numbers */
obj = 0;
escaper.escape(obj);
assert.deepEqual(obj, 0, 'don\'t fall over numbers');

/* don't fall over strings */
obj = '';
escaper.escape(obj);
assert.deepEqual(obj, '', 'don\'t fall over empty string');

obj = '$set';
escaper.escape(obj);
assert.deepEqual(obj, '$set', 'don\'t fall over string');

obj = {};
escaper.escape(obj);
assert.deepEqual(obj, {}, 'escape empty object');

obj = { $: '$', 'foo.bar': { $: '$' } };
escaper.escape(obj, false);
assert.deepEqual(obj, { '\uFF04': '$', 'foo\uFF0Ebar': { $: '$' } }, 'should not recurse');

obj = { $: '$', 'foo.bar': { $: '$' } };
escaper.escape(obj, false);
escaper.escape(obj, false);
assert.deepEqual(obj, { '\uFF04': '$', 'foo\uFF0Ebar': { $: '$' } }, 'should be idempotent');

obj = { $: '$', foo: { $: '$', bar: { 'some.foo': 'other' } }, a: 'b' };
escaper.escape(obj);
assert.deepEqual(obj, { '\uFF04': '$', foo: { '\uFF04': '$', bar: { 'some\uFF0Efoo': 'other' } }, a: 'b' }, 'should recurse by default');

obj = [ { $: '$', 'foo.bar': { $: '$' } }, { $: [ '$', { 'foo.qux': { $: '$' } } ], 'foo.baz': { $: '$' } } ];
escaper.escape(obj);
assert.deepEqual(obj, [ { '\uFF04': '$', 'foo\uFF0Ebar': { '\uFF04': '$' } }, { '\uFF04': [ '$', { 'foo\uFF0Equx': { '\uFF04': '$' } } ], 'foo\uFF0Ebaz': { '\uFF04': '$' } } ], 'should recurse on array values');

/* unescape */

/* don't fall over strings */
obj = '';
escaper.unescape(obj);
assert.deepEqual(obj, '', 'don\'t fall over empty string');

obj = '$set';
escaper.unescape(obj);
assert.deepEqual(obj, '$set', 'don\'t fall over string');

obj = {};
escaper.unescape(obj);
assert.deepEqual(obj, {}, 'unescape empty object');

obj = { 'a': 'b' };
escaper.escape(obj, true);
assert.deepEqual(obj, { 'a': 'b' }, 'should return original object');

obj = { '\uFF04': '$', 'foo\uFF0Ebar': { $: '$' } };
escaper.unescape(obj, false);
assert.deepEqual(obj, { $: '$', 'foo.bar': { $: '$' } }, 'should not recurse');

obj = { '\uFF04': '$', 'foo\uFF0Ebar': { $: '$' } };
escaper.unescape(obj, false);
escaper.unescape(obj, false);
assert.deepEqual(obj, { $: '$', 'foo.bar': { $: '$' } }, 'should be idempotent');

obj = { '\uFF04': '$', foo: { '\uFF04': '$', bar: { 'some\uFF0Efoo': 'other' } }, a: 'b' };
escaper.unescape(obj);
assert.deepEqual(obj, { $: '$', foo: { $: '$', bar: { 'some.foo': 'other' } }, a: 'b' }, 'should recurse by default');

obj = [ { '\uFF04': '$', 'foo\uFF0Ebar': { '\uFF04': '$' } }, { '\uFF04': [ '$', { 'foo\uFF0Equx': { '\uFF04': '$' } } ], 'foo\uFF0Ebaz': { '\uFF04': '$' } } ];
escaper.unescape(obj);
assert.deepEqual(obj, [ { $: '$', 'foo.bar': { $: '$' } }, { $: [ '$', { 'foo.qux': { $: '$' } } ], 'foo.baz': { $: '$' } } ], 'should recurse on array values');

console.log('ok');
<commit_msg>tests: use strict check for non-object checking<commit_after>/**
 * Copyright (c) 2014, 2016 Tim Kuijsten
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

'use strict';

var assert = require('assert');

var escaper = require('./index');

var obj;

/* escape */

/* don't fall over numbers */
obj = 0;
escaper.escape(obj);
assert.strictEqual(obj, 0, 'don\'t fall over numbers');

/* don't fall over strings */
obj = '';
escaper.escape(obj);
assert.strictEqual(obj, '', 'don\'t fall over empty string');

obj = '$set';
escaper.escape(obj);
assert.strictEqual(obj, '$set', 'don\'t fall over string');

obj = {};
escaper.escape(obj);
assert.deepEqual(obj, {}, 'escape empty object');

obj = { $: '$', 'foo.bar': { $: '$' } };
escaper.escape(obj, false);
assert.deepEqual(obj, { '\uFF04': '$', 'foo\uFF0Ebar': { $: '$' } }, 'should not recurse');

obj = { $: '$', 'foo.bar': { $: '$' } };
escaper.escape(obj, false);
escaper.escape(obj, false);
assert.deepEqual(obj, { '\uFF04': '$', 'foo\uFF0Ebar': { $: '$' } }, 'should be idempotent');

obj = { $: '$', foo: { $: '$', bar: { 'some.foo': 'other' } }, a: 'b' };
escaper.escape(obj);
assert.deepEqual(obj, { '\uFF04': '$', foo: { '\uFF04': '$', bar: { 'some\uFF0Efoo': 'other' } }, a: 'b' }, 'should recurse by default');

obj = [ { $: '$', 'foo.bar': { $: '$' } }, { $: [ '$', { 'foo.qux': { $: '$' } } ], 'foo.baz': { $: '$' } } ];
escaper.escape(obj);
assert.deepEqual(obj, [ { '\uFF04': '$', 'foo\uFF0Ebar': { '\uFF04': '$' } }, { '\uFF04': [ '$', { 'foo\uFF0Equx': { '\uFF04': '$' } } ], 'foo\uFF0Ebaz': { '\uFF04': '$' } } ], 'should recurse on array values');

/* unescape */

/* don't fall over strings */
obj = '';
escaper.unescape(obj);
assert.strictEqual(obj, '', 'don\'t fall over empty string');

obj = '$set';
escaper.unescape(obj);
assert.strictEqual(obj, '$set', 'don\'t fall over string');

obj = {};
escaper.unescape(obj);
assert.deepEqual(obj, {}, 'unescape empty object');

obj = { 'a': 'b' };
escaper.escape(obj, true);
assert.deepEqual(obj, { 'a': 'b' }, 'should return original object');

obj = { '\uFF04': '$', 'foo\uFF0Ebar': { $: '$' } };
escaper.unescape(obj, false);
assert.deepEqual(obj, { $: '$', 'foo.bar': { $: '$' } }, 'should not recurse');

obj = { '\uFF04': '$', 'foo\uFF0Ebar': { $: '$' } };
escaper.unescape(obj, false);
escaper.unescape(obj, false);
assert.deepEqual(obj, { $: '$', 'foo.bar': { $: '$' } }, 'should be idempotent');

obj = { '\uFF04': '$', foo: { '\uFF04': '$', bar: { 'some\uFF0Efoo': 'other' } }, a: 'b' };
escaper.unescape(obj);
assert.deepEqual(obj, { $: '$', foo: { $: '$', bar: { 'some.foo': 'other' } }, a: 'b' }, 'should recurse by default');

obj = [ { '\uFF04': '$', 'foo\uFF0Ebar': { '\uFF04': '$' } }, { '\uFF04': [ '$', { 'foo\uFF0Equx': { '\uFF04': '$' } } ], 'foo\uFF0Ebaz': { '\uFF04': '$' } } ];
escaper.unescape(obj);
assert.deepEqual(obj, [ { $: '$', 'foo.bar': { $: '$' } }, { $: [ '$', { 'foo.qux': { $: '$' } } ], 'foo.baz': { $: '$' } } ], 'should recurse on array values');

console.log('ok');
<|endoftext|>


<commit_before>/*
* script to book car sharing
* set environmental variables
* TP_CARD_NO1
* TP_CARD_NO2
* TP_PASSWORD
* TP_STATION_CODE
* TP_PRIMARY_CAR
* TP_SECONDARY_CAR
*/

var webdriverio = require('webdriverio');
var options = {
    desiredCapabilities: {
        browserName: 'chrome'
    }
};

var client = webdriverio.remote(options);

client
.init()
.url('https://plus.timescar.jp/')
    .getTitle().then(function(title) {
    console.log('Title was: ' + title);
})
.setValue('#cardNo1', process.env.TP_CARD_NO1)
.setValue('#cardNo2', process.env.TP_CARD_NO2)
.setValue('#tpPassword', process.env.TP_PASSWORD)
.click('#tpLogin')
.waitForExist('#yakkan_box', 5000)
.getUrl().then(function(url){
    console.log(url);
})
.click('#yakkan_box .s_agree')
.url('https://plus.timescar.jp/view/reserve/input.jsp?scd='+process.env.TP_STATION_CODE)
.selectByAttribute('#carId', 'value', process.env.TP_PRIMARY_CAR)
.selectByIndex('#dateStart', 22)
.selectByAttribute('#hourStart', 'value', '8')
.selectByIndex('#dateEnd', 22)
.selectByAttribute('#hourEnd', 'value', '20')
.click('#doCheck')
.getUrl().then(function(url) {
    console.log(url);
    if(url.indexOf('confirm')>-1){
        console.log('confirm');
        client.click('#doOnceRegist')
        .getUrl().then(function(cUrl){
            console.log(cUrl);
            if(cUrl.indexOf('complete')>-1){
                console.log('complete');
            }
        });
    }else if(url.indexOf('input')>-1){
        console.log('error');
        console.log(client);
        client
            .selectByAttribute('#carId', 'value', process.env.TP_SECONDARY_CAR)
            .click('#doCheck')
            .click('#doOnceRegist')
            .getUrl().then(function(cUrl){
            console.log(cUrl);
            if(cUrl.indexOf('complete')>-1){
                console.log('complete');
            }
        });
    }
})
//.end();
;
<commit_msg>switch to phantomjs<commit_after>/*
* script to book car sharing
* set environmental variables
* TP_CARD_NO1
* TP_CARD_NO2
* TP_PASSWORD
* TP_STATION_CODE
* TP_PRIMARY_CAR
* TP_SECONDARY_CAR
*/

var webdriverio = require('webdriverio');
var options = {
    desiredCapabilities: {
        browserName: 'phantomjs'
    }
};

var client = webdriverio.remote(options);

client
.init()
.url('https://plus.timescar.jp/')
    .getTitle().then(function(title) {
    console.log('Title was: ' + title);
})
.setValue('#cardNo1', process.env.TP_CARD_NO1)
.setValue('#cardNo2', process.env.TP_CARD_NO2)
.setValue('#tpPassword', process.env.TP_PASSWORD)
.click('#tpLogin')
.waitForExist('#yakkan_box', 5000)
.getUrl().then(function(url){
    console.log(url);
})
.click('#yakkan_box .s_agree')
.url('https://plus.timescar.jp/view/reserve/input.jsp?scd='+process.env.TP_STATION_CODE)
.selectByAttribute('#carId', 'value', process.env.TP_PRIMARY_CAR)
.selectByIndex('#dateStart', 22)
.selectByAttribute('#hourStart', 'value', '8')
.selectByIndex('#dateEnd', 22)
.selectByAttribute('#hourEnd', 'value', '20')
.click('#doCheck')
.getUrl().then(function(url) {
    console.log(url);
    if(url.indexOf('confirm')>-1){
        console.log('confirm');
        client.click('#doOnceRegist')
        .getUrl().then(function(cUrl){
            console.log(cUrl);
            if(cUrl.indexOf('complete')>-1){
                console.log('complete');
            }
        });
    }else if(url.indexOf('input')>-1){
        console.log('error');
        console.log(client);
        client
            .selectByAttribute('#carId', 'value', process.env.TP_SECONDARY_CAR)
            .click('#doCheck')
            .click('#doOnceRegist')
            .getUrl().then(function(cUrl){
            console.log(cUrl);
            if(cUrl.indexOf('complete')>-1){
                console.log('complete');
            }
        });
    }
})
//.end();
;
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-20 10:17:55<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var MetroHash64  = require('./index').MetroHash64;
var MetroHash128 = require('./index').MetroHash128;
var metrohash64  = require('./index').metrohash64;
var metrohash128 = require('./index').metrohash128;
var expect       = require('chai').expect;

const TESTVECTOR_S = '012345678901234567890123456789012345678901234567890123456789012';
const TESTVECTOR_B = new Buffer(TESTVECTOR_S);

const CLS_TESTS = [
  { cls : MetroHash64,            expected : '6b753dae06704bad' },
  { cls : MetroHash64,  seed : 0, expected : '6b753dae06704bad' },
  { cls : MetroHash64,  seed : 1, expected : '3b0d481cf4b9b8df' },
  { cls : MetroHash128,           expected : 'c77ce2bfa4ed9f9b0548b2ac5074a297' },
  { cls : MetroHash128, seed : 0, expected : 'c77ce2bfa4ed9f9b0548b2ac5074a297' },
  { cls : MetroHash128, seed : 1, expected : '45a3cdb838199d7fbdd68d867a14ecef' },
];

const FUN_TESTS = [
  { fn : metrohash64,             expected : '6b753dae06704bad' },
  { fn : metrohash64,  seed : 0,  expected : '6b753dae06704bad' },
  { fn : metrohash64,  seed : 1,  expected : '3b0d481cf4b9b8df' },
  { fn : metrohash128,            expected : 'c77ce2bfa4ed9f9b0548b2ac5074a297' },
  { fn : metrohash128, seed : 0,  expected : 'c77ce2bfa4ed9f9b0548b2ac5074a297' },
  { fn : metrohash128, seed : 1,  expected : '45a3cdb838199d7fbdd68d867a14ecef' },
];

describe('Instantiation and method calling', function() {

  it('new MetroHash64() should work', function() {
    expect(function() { new MetroHash64(); }).to.not.throw();
  });

  it('MetroHash64() should work', function() {
    expect(function() { MetroHash64(); }).to.not.throw();
  });

  it('new MetroHash128() should work', function() {
    expect(function() { new MetroHash128(); }).to.not.throw();
  });

  it('MetroHash128() should work', function() {
    expect(function() { MetroHash128(); }).to.not.throw();
  });

  it('MetroHash64() should allow chaining', function() {
    expect(function() {
      new MetroHash64().update(TESTVECTOR_B).digest();
    }).to.not.throw();
  });

  it('MetroHash128() should allow chaining', function() {
    expect(function() {
      new MetroHash128().update(TESTVECTOR_B).digest();
    }).to.not.throw();
  });

});

describe('Test vectors', function() {

  CLS_TESTS.forEach(function(test) {
    var suffix = test.seed !== undefined ? ', seed = ' + test.seed + ')' : ')';

    it('new ' + test.cls.name + '(String' + suffix, function() {
      var instance = new test.cls(test.seed);
      instance.update(TESTVECTOR_S);
      expect(instance.digest()).to.equal(test.expected);
    });

    it(test.cls.name + '(String' + suffix, function() {
      var instance = test.cls(test.seed);
      instance.update(TESTVECTOR_S);
      expect(instance.digest()).to.equal(test.expected);
    });

    it('new ' + test.cls.name + '(Buffer' + suffix, function() {
      var instance = new test.cls(test.seed);
      instance.update(TESTVECTOR_B);
      expect(instance.digest()).to.equal(test.expected);
    });

    it(test.cls.name + '(Buffer' + suffix, function() {
      var instance = test.cls(test.seed);
      instance.update(TESTVECTOR_B);
      expect(instance.digest()).to.equal(test.expected);
    });

    it(test.cls.name + '(String' + suffix + ' incremental', function() {
      var instance = test.cls(test.seed);
      TESTVECTOR_S.split('').forEach(function(c) {
        instance.update(c);
      });
      expect(instance.digest()).to.equal(test.expected);
    });

    it(test.cls.name + '(Buffer' + suffix + ' incremental', function() {
      var instance = test.cls(test.seed);
      for (var i = 0; i < TESTVECTOR_B.length; i++) {
        instance.update(TESTVECTOR_B.slice(i, i + 1));
      }
      expect(instance.digest()).to.equal(test.expected);
    });
  });

  FUN_TESTS.forEach(function(test) {
    let hasSeed = test.seed !== undefined;
    let suffix  = hasSeed ? ', seed = ' + test.seed + ')' : ')';

    it('Standalone: ' + test.fn.name + '(String' + suffix, function() {
      let result = hasSeed ? test.fn(TESTVECTOR_S, test.seed) : test.fn(TESTVECTOR_S);
      expect(result).to.equal(test.expected);
    });

    it('Standalone: ' + test.fn.name + '(Buffer' + suffix, function() {
      let result = hasSeed ? test.fn(TESTVECTOR_B, test.seed) : test.fn(TESTVECTOR_B);
      expect(result).to.equal(test.expected);
    });

    it('Standalone: ' + test.fn.name + ', handle invalid data', function() {
      expect(function() { test.fn(123) }).to.fail;
    });

    it('Standalone: ' + test.fn.name + ', handle invalid seed', function() {
      expect(function() { test.fn(TESTVECTOR_S, 'foo') }).to.fail;
    });

    it('Standalone: ' + test.fn.name + ', handle invalid data and seed', function() {
      expect(function() { test.fn(123, 'foo') }).to.fail;
    });

  });

});
<commit_msg>Fixed issue with Node v4<commit_after>'use strict';
var MetroHash64  = require('./index').MetroHash64;
var MetroHash128 = require('./index').MetroHash128;
var metrohash64  = require('./index').metrohash64;
var metrohash128 = require('./index').metrohash128;
var expect       = require('chai').expect;

const TESTVECTOR_S = '012345678901234567890123456789012345678901234567890123456789012';
const TESTVECTOR_B = new Buffer(TESTVECTOR_S);

const CLS_TESTS = [
  { cls : MetroHash64,            expected : '6b753dae06704bad' },
  { cls : MetroHash64,  seed : 0, expected : '6b753dae06704bad' },
  { cls : MetroHash64,  seed : 1, expected : '3b0d481cf4b9b8df' },
  { cls : MetroHash128,           expected : 'c77ce2bfa4ed9f9b0548b2ac5074a297' },
  { cls : MetroHash128, seed : 0, expected : 'c77ce2bfa4ed9f9b0548b2ac5074a297' },
  { cls : MetroHash128, seed : 1, expected : '45a3cdb838199d7fbdd68d867a14ecef' },
];

const FUN_TESTS = [
  { fn : metrohash64,             expected : '6b753dae06704bad' },
  { fn : metrohash64,  seed : 0,  expected : '6b753dae06704bad' },
  { fn : metrohash64,  seed : 1,  expected : '3b0d481cf4b9b8df' },
  { fn : metrohash128,            expected : 'c77ce2bfa4ed9f9b0548b2ac5074a297' },
  { fn : metrohash128, seed : 0,  expected : 'c77ce2bfa4ed9f9b0548b2ac5074a297' },
  { fn : metrohash128, seed : 1,  expected : '45a3cdb838199d7fbdd68d867a14ecef' },
];

describe('Instantiation and method calling', function() {

  it('new MetroHash64() should work', function() {
    expect(function() { new MetroHash64(); }).to.not.throw();
  });

  it('MetroHash64() should work', function() {
    expect(function() { MetroHash64(); }).to.not.throw();
  });

  it('new MetroHash128() should work', function() {
    expect(function() { new MetroHash128(); }).to.not.throw();
  });

  it('MetroHash128() should work', function() {
    expect(function() { MetroHash128(); }).to.not.throw();
  });

  it('MetroHash64() should allow chaining', function() {
    expect(function() {
      new MetroHash64().update(TESTVECTOR_B).digest();
    }).to.not.throw();
  });

  it('MetroHash128() should allow chaining', function() {
    expect(function() {
      new MetroHash128().update(TESTVECTOR_B).digest();
    }).to.not.throw();
  });

});

describe('Test vectors', function() {

  CLS_TESTS.forEach(function(test) {
    var suffix = test.seed !== undefined ? ', seed = ' + test.seed + ')' : ')';

    it('new ' + test.cls.name + '(String' + suffix, function() {
      var instance = new test.cls(test.seed);
      instance.update(TESTVECTOR_S);
      expect(instance.digest()).to.equal(test.expected);
    });

    it(test.cls.name + '(String' + suffix, function() {
      var instance = test.cls(test.seed);
      instance.update(TESTVECTOR_S);
      expect(instance.digest()).to.equal(test.expected);
    });

    it('new ' + test.cls.name + '(Buffer' + suffix, function() {
      var instance = new test.cls(test.seed);
      instance.update(TESTVECTOR_B);
      expect(instance.digest()).to.equal(test.expected);
    });

    it(test.cls.name + '(Buffer' + suffix, function() {
      var instance = test.cls(test.seed);
      instance.update(TESTVECTOR_B);
      expect(instance.digest()).to.equal(test.expected);
    });

    it(test.cls.name + '(String' + suffix + ' incremental', function() {
      var instance = test.cls(test.seed);
      TESTVECTOR_S.split('').forEach(function(c) {
        instance.update(c);
      });
      expect(instance.digest()).to.equal(test.expected);
    });

    it(test.cls.name + '(Buffer' + suffix + ' incremental', function() {
      var instance = test.cls(test.seed);
      for (var i = 0; i < TESTVECTOR_B.length; i++) {
        instance.update(TESTVECTOR_B.slice(i, i + 1));
      }
      expect(instance.digest()).to.equal(test.expected);
    });
  });

  FUN_TESTS.forEach(function(test) {
    let hasSeed = test.seed !== undefined;
    let suffix  = hasSeed ? ', seed = ' + test.seed + ')' : ')';

    it('Standalone: ' + test.fn.name + '(String' + suffix, function() {
      let result = hasSeed ? test.fn(TESTVECTOR_S, test.seed) : test.fn(TESTVECTOR_S);
      expect(result).to.equal(test.expected);
    });

    it('Standalone: ' + test.fn.name + '(Buffer' + suffix, function() {
      let result = hasSeed ? test.fn(TESTVECTOR_B, test.seed) : test.fn(TESTVECTOR_B);
      expect(result).to.equal(test.expected);
    });

    it('Standalone: ' + test.fn.name + ', handle invalid data', function() {
      expect(function() { test.fn(123) }).to.fail;
    });

    it('Standalone: ' + test.fn.name + ', handle invalid seed', function() {
      expect(function() { test.fn(TESTVECTOR_S, 'foo') }).to.fail;
    });

    it('Standalone: ' + test.fn.name + ', handle invalid data and seed', function() {
      expect(function() { test.fn(123, 'foo') }).to.fail;
    });

  });

});
<|endoftext|>


<commit_before>QUnit.test( "Test Scitanie", function( assert ) {
   assert.strictEqual(MatematKnih.Scitani(5, 4), 9, '[4 + 5 = 9]  PASS');
   assert.strictEqual(MatematKnih.Scitani(-5, 2), -3, '[-5 + 2 = -3]  PASS');
   assert.strictEqual(MatematKnih.Scitani(2.5, 2), 4.5, '[2.5 + 2 = 4.5]  PASS');
   assert.strictEqual(MatematKnih.Scitani(0, 4), 4, '[0 + 4 = 4]  PASS');
   assert.strictEqual(MatematKnih.Scitani(-5.2584, 2.9826), -2.2758, '[-5.2584 + 2.9826 = -2.2758]  PASS');
});

QUnit.test( "Test Odcitanie", function( assert ) {
   assert.strictEqual(MatematKnih.Odcitani(15, 9), 6, '[15 - 9 = 6]  PASS');
   assert.strictEqual(MatematKnih.Odcitani(22, 21.5), 0.5, '[22 - 21.45 = 0.5]  PASS');
   assert.strictEqual(MatematKnih.Odcitani(-2.5, 2), -4.5, '[-2.5 - 2 = -4.5]  PASS');
   assert.strictEqual(MatematKnih.Odcitani(-90, -10), -80, '[-90 -(-10) = -80]  PASS');
   assert.strictEqual(MatematKnih.Odcitani(5.75, 2.75), 3, '[5.75 - 2.75 = 3]  PASS');
});

QUnit.test( "Test Nasobenie", function( assert ) {
   assert.strictEqual(MatematKnih.Nasobeni(5, 6), 30, '[5 * 6 = 30]  PASS');
   assert.strictEqual(MatematKnih.Nasobeni(10, 0), 0, '[10 * 0 = 0]  PASS');
   assert.strictEqual(MatematKnih.Nasobeni(-5, 3), -15, '[-5 * 3 = -15]  PASS');
   assert.strictEqual(MatematKnih.Nasobeni(-4, -4), 16, '[-4 *(-4) = 16]  PASS');
   assert.strictEqual(MatematKnih.Nasobeni(2.562, 11), 28.182, '[2.5 * 11 = 28.182]  PASS');
});

QUnit.test( "Test Delenie", function( assert ) {
   assert.strictEqual(MatematKnih.Deleni(50, 5), 10, '[50 / 5 = 10]  PASS');
   assert.strictEqual(MatematKnih.Deleni(24, 5), 4.8, '[24 / 5 = 4.8]  PASS');
   assert.strictEqual(MatematKnih.Deleni(-15, 4), -3.75, '[-15 / 4 = -3.75]  PASS');
   assert.strictEqual(MatematKnih.Deleni(-8, -2), 4, '[-8 /(-2) = 4]  PASS');
   assert.strictEqual(MatematKnih.Deleni(0, 10), 0, '[0 / 10 = 0]  PASS');
   assert.strictEqual(MatematKnih.Deleni(15.555, 3), 5.185, '[15.555 / 3 = 5.185]  PASS');
});

QUnit.test( "Test Faktorial", function( assert ) {
   assert.strictEqual(MatematKnih.Faktorial(0), 1, '[0! = 1]  PASS');
   assert.strictEqual(MatematKnih.Faktorial(1), 1, '[1! = 1]  PASS');
   assert.strictEqual(MatematKnih.Faktorial(5), 120, '[5! = 120]  PASS');
   assert.strictEqual(MatematKnih.Faktorial(8), 40320, '[8! = 40320]  PASS');
   assert.strictEqual(MatematKnih.Faktorial(15), 1307674368000, '[15! = 1307674368000]  PASS');
});

QUnit.test( "Test Mocnina", function( assert ) {
   assert.strictEqual(MatematKnih.Mocnina(7, 0), 1, '[7^0 = 1]  PASS');
   assert.strictEqual(MatematKnih.Mocnina(3, 2), 9, '[3^2 = 1]  PASS');
   assert.strictEqual(MatematKnih.Mocnina(-2, 4), -16, '[-2^4 = 16]  PASS');
   assert.strictEqual(MatematKnih.Mocnina(2, -4), 0.0625, '[2^-4 = 0.0625]  PASS');
   assert.strictEqual(MatematKnih.Mocnina(-2, -2), -0.25, '[-2^-2 = -0.25]  PASS');
});<commit_msg>pridane testy pre mocninu a odmocninu<commit_after>QUnit.test( "Test Scitanie", function( assert ) {
   assert.strictEqual(MatematKnih.Scitani(5, 4), 9, '[4 + 5 = 9]  PASS');
   assert.strictEqual(MatematKnih.Scitani(-5, 2), -3, '[-5 + 2 = -3]  PASS');
   assert.strictEqual(MatematKnih.Scitani(2.5, 2), 4.5, '[2.5 + 2 = 4.5]  PASS');
   assert.strictEqual(MatematKnih.Scitani(0, 4), 4, '[0 + 4 = 4]  PASS');
   assert.strictEqual(MatematKnih.Scitani(-5.2584, 2.9826), -2.2758, '[-5.2584 + 2.9826 = -2.2758]  PASS');
});

QUnit.test( "Test Odcitanie", function( assert ) {
   assert.strictEqual(MatematKnih.Odcitani(15, 9), 6, '[15 - 9 = 6]  PASS');
   assert.strictEqual(MatematKnih.Odcitani(22, 21.5), 0.5, '[22 - 21.45 = 0.5]  PASS');
   assert.strictEqual(MatematKnih.Odcitani(-2.5, 2), -4.5, '[-2.5 - 2 = -4.5]  PASS');
   assert.strictEqual(MatematKnih.Odcitani(-90, -10), -80, '[-90 -(-10) = -80]  PASS');
   assert.strictEqual(MatematKnih.Odcitani(5.75, 2.75), 3, '[5.75 - 2.75 = 3]  PASS');
});

QUnit.test( "Test Nasobenie", function( assert ) {
   assert.strictEqual(MatematKnih.Nasobeni(5, 6), 30, '[5 * 6 = 30]  PASS');
   assert.strictEqual(MatematKnih.Nasobeni(10, 0), 0, '[10 * 0 = 0]  PASS');
   assert.strictEqual(MatematKnih.Nasobeni(-5, 3), -15, '[-5 * 3 = -15]  PASS');
   assert.strictEqual(MatematKnih.Nasobeni(-4, -4), 16, '[-4 *(-4) = 16]  PASS');
   assert.strictEqual(MatematKnih.Nasobeni(2.562, 11), 28.182, '[2.5 * 11 = 28.182]  PASS');
});

QUnit.test( "Test Delenie", function( assert ) {
   assert.strictEqual(MatematKnih.Deleni(50, 5), 10, '[50 / 5 = 10]  PASS');
   assert.strictEqual(MatematKnih.Deleni(24, 5), 4.8, '[24 / 5 = 4.8]  PASS');
   assert.strictEqual(MatematKnih.Deleni(-15, 4), -3.75, '[-15 / 4 = -3.75]  PASS');
   assert.strictEqual(MatematKnih.Deleni(-8, -2), 4, '[-8 /(-2) = 4]  PASS');
   assert.strictEqual(MatematKnih.Deleni(0, 10), 0, '[0 / 10 = 0]  PASS');
   assert.strictEqual(MatematKnih.Deleni(15.555, 3), 5.185, '[15.555 / 3 = 5.185]  PASS');
});

QUnit.test( "Test Faktorial", function( assert ) {
   assert.strictEqual(MatematKnih.Faktorial(0), 1, '[0! = 1]  PASS');
   assert.strictEqual(MatematKnih.Faktorial(1), 1, '[1! = 1]  PASS');
   assert.strictEqual(MatematKnih.Faktorial(5), 120, '[5! = 120]  PASS');
   assert.strictEqual(MatematKnih.Faktorial(8), 40320, '[8! = 40320]  PASS');
   assert.strictEqual(MatematKnih.Faktorial(15), 1307674368000, '[15! = 1307674368000]  PASS');
});

QUnit.test( "Test Mocnina", function( assert ) {
   assert.strictEqual(MatematKnih.Mocnina(7, 0), 1, '[7^0 = 1]  PASS');
   assert.strictEqual(MatematKnih.Mocnina(3, 2), 9, '[3^2 = 1]  PASS');
   assert.strictEqual(MatematKnih.Mocnina(-2, 4), -16, '[-2^4 = 16]  PASS');
   assert.strictEqual(MatematKnih.Mocnina(2, -4), 0.0625, '[2^-4 = 0.0625]  PASS');
   assert.strictEqual(MatematKnih.Mocnina(-2, -2), -0.25, '[-2^-2 = -0.25]  PASS');
});

QUnit.test( "Test Odmocnina", function( assert ) {
   assert.strictEqual(MatematKnih.Odmocnina(0), 0, '[sqrt(0) = 0]  PASS');
   assert.strictEqual(MatematKnih.Odmocnina(1), 1, '[sqrt(1) = 1]  PASS');
   assert.strictEqual(MatematKnih.Odmocnina(4), 2, '[sqrt(4) = 4]  PASS');
   assert.strictEqual(MatematKnih.Odmocnina(4900), 70, '[sqrt(4900) = 70]  PASS');
   assert.strictEqual(MatematKnih.Odmocnina(17.4), 4.171330722922842, '[sqrt(17.4) = 4.171330722922842]  PASS');
});<|endoftext|>


<commit_before>import fs from "fs";
import path from "path";

import test from "ava";
import pify from "pify";
import rimraf from "rimraf";
import m from ".";

const tempPath = path.join(__dirname, "temp");

const apiKey = process.env.YOUTUBE_API_KEY;

async function macro(t, url, filenames, opts) {
	await m(url, apiKey, tempPath, opts).then(downloads => Promise.all(downloads));

	const files = await pify(fs.readdir)(tempPath);
	t.deepEqual(files, filenames);

	const stats = await pify(fs.stat)(path.join(tempPath, filenames[0]));

	t.true(stats.isFile());
	t.true(stats.size > 0);
}

test.beforeEach(async () => {
	await pify(fs.mkdir)(tempPath);
});

test.afterEach.always(async () => {
	await pify(rimraf)("temp");
});

test.serial("throw if url is not a string", t => {
	t.throws(() => m(5, "", ""), "Expected `url` to be a `string`, got `number`");
	t.throws(() => m(true, "", ""), "Expected `url` to be a `string`, got `boolean`");
});

test.serial("throw if apiKey is not a string", t => {
	t.throws(() => m("", 5, ""), "Expected `apiKey` to be a `string`, got `number`");
	t.throws(() => m("", true, ""), "Expected `apiKey` to be a `string`, got `boolean`");
});

test.serial("throw if videosPath is not a string", t => {
	t.throws(() => m("", "", 5), "Expected `videosPath` to be a `string`, got `number`");
	t.throws(() => m("", "", true), "Expected `videosPath` to be a `string`, got `boolean`");
});

test.serial("download video", macro, "https://youtu.be/q6EoRBvdVPQ", ["Yee.mp4"]);

test.serial("download playlist from video", macro, "https://youtu.be/q6EoRBvdVPQ?list=PL7XlqX4npddfrdpMCxBnNZXg2GFll7t5y", ["Yee.mp4"], {max: 1});

test.serial("download playlist from page", macro, "https://www.youtube.com/playlist?list=PL7XlqX4npddfrdpMCxBnNZXg2GFll7t5y", ["Yee.mp4"], {max: 1});
<commit_msg>Fix dead url<commit_after>import fs from "fs";
import path from "path";

import test from "ava";
import pify from "pify";
import rimraf from "rimraf";
import m from ".";

const tempPath = path.join(__dirname, "temp");

const apiKey = process.env.YOUTUBE_API_KEY;

async function macro(t, url, filenames, opts) {
	await m(url, apiKey, tempPath, opts).then(downloads => Promise.all(downloads));

	const files = await pify(fs.readdir)(tempPath);
	t.deepEqual(files, filenames);

	const stats = await pify(fs.stat)(path.join(tempPath, filenames[0]));

	t.true(stats.isFile());
	t.true(stats.size > 0);
}

test.beforeEach(async () => {
	await pify(fs.mkdir)(tempPath);
});

test.afterEach.always(async () => {
	await pify(rimraf)("temp");
});

test.serial("throw if url is not a string", t => {
	t.throws(() => m(5, "", ""), "Expected `url` to be a `string`, got `number`");
	t.throws(() => m(true, "", ""), "Expected `url` to be a `string`, got `boolean`");
});

test.serial("throw if apiKey is not a string", t => {
	t.throws(() => m("", 5, ""), "Expected `apiKey` to be a `string`, got `number`");
	t.throws(() => m("", true, ""), "Expected `apiKey` to be a `string`, got `boolean`");
});

test.serial("throw if videosPath is not a string", t => {
	t.throws(() => m("", "", 5), "Expected `videosPath` to be a `string`, got `number`");
	t.throws(() => m("", "", true), "Expected `videosPath` to be a `string`, got `boolean`");
});

test.serial("download video", macro, "https://youtu.be/q6EoRBvdVPQ", ["Yee.mp4"]);

test.serial("download playlist from video", macro, "https://www.youtube.com/watch?v=q6EoRBvdVPQ&index=1&list=PLOy0j9AvlVZPto6IkjKfpu0Scx--7PGTC", ["Yee.mp4"], {max: 1});

test.serial("download playlist from page", macro, "https://www.youtube.com/playlist?list=PLOy0j9AvlVZPto6IkjKfpu0Scx--7PGTC", ["Yee.mp4"], {max: 1});
<|endoftext|>


<commit_before>
const { sortByType, clean, getFolderActions, flattenActions, itemTypes, actionTypes } = require('./')
const { ephemeralFsFromObject } = require('fs-from-object')
const { open, close, stat, utimes } = require('mz/fs')
const cpr = require('recursive-copy')
const { join } = require('path')
const rmfr = require('rmfr')
const test = require('ava')

const setupTree = (task) => {
  const oldFile = { name: 'index-old.txt', contents: 'test', mtime: new Date('06/17/2016') }
  const newFile =  { name: 'index.txt', contents: 'test', mtime: new Date('11/17/2016') }

  const tree = [
    { name: 'basic', contents: [oldFile, newFile] },

    {
      name: 'empty',
      contents: [
        { name: 'empty', contents: [] }
      ]
    },

    {
      name: 'recursive',
      contents: [
        { name: 'sub-folder', contents: [oldFile, newFile] },
        oldFile,
        newFile
      ]
    },

    {
      name: 'empty-after-delete',
      contents: [
        { name: 'sub-folder', contents: [oldFile] }
      ]
    },

    {
      name: 'test-delete',
      contents: [
        { name: 'empty-folder', contents: [] },
        { name: 'sub-folder', contents: [oldFile, newFile] },
        oldFile,
        newFile
      ]
    }
  ]

  return ephemeralFsFromObject(tree, task)
}

test('flat file list', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'basic')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: false,
      maxAge: 90
    })
    t.is(actions[0].actionType, actionTypes.DELETE)
    t.is(actions[1].actionType, actionTypes.RETAIN)
  })
})

test('recursive', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'recursive')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    t.is(actions[0].actionType, actionTypes.DELETE)
    t.is(actions[1].actionType, actionTypes.RETAIN)

    const dir = actions[2]
    t.is(dir.itemType, itemTypes.DIR)
    t.is(dir.actions[0].actionType, actionTypes.DELETE)
    t.is(dir.actions[1].actionType, actionTypes.RETAIN)
  })
})

test('empty folders', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'empty')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    t.is(actions[0].itemType, itemTypes.DIR)
    t.is(actions[0].actionType, actionTypes.DELETE)
  })
})

test('empty folders after delete', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'empty-after-delete')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    t.is(actions[0].actionType, actionTypes.DELETE)
    t.is(actions[0].actions[0].actionType, actionTypes.DELETE)
  })
})

test('flatten actions', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'recursive')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    const actionsf = flattenActions(actions)
    t.is(actionsf.length, 5)
  })
})

test('sort actions by type', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'recursive')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    const sortedActions = sortByType(actions)
    t.is(sortedActions.delete.length, 2)
    t.is(sortedActions.retain.length, 3)
  })
})

const shouldntExist = (t, path, item) => {
  return stat(join(path, item))
    .then(() => t.fail(`old item ${item} exists`))
    .catch(() => t.pass())
}

const shouldExist = (t, path, item) => {
  return stat(join(path, item))
    .then(() => t.pass())
    .catch(() => t.fail(`old item ${item} doesn\'t exist`))
}

test('execute actions', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'test-delete')

    await clean(path, {
      deleteAt: new Date('11/14/2016'),
      deleteEmptyFolders: true,
      recursive: true,
      maxAge: 90
    })

    await Promise.all([
      shouldntExist(t, path, 'index-old.txt'),
      shouldntExist(t, path, 'sub-folder/index-old.txt'),
      shouldntExist(t, path, 'empty-folder'),

      shouldExist(t, path, 'index.txt'),
      shouldExist(t, path, 'sub-folder/index.txt')
    ])
  })
})

test.only('busy files', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'basic')

    const fd = await open(join(path, 'index-old.txt'), 'r+')

    const actions = await clean(path, {
      deleteAt: new Date('11/14/2016'),
      deleteEmptyFolders: true,
      recursive: true,
      maxAge: 90
    })

    console.log(actions)
    await close(fd)
  })
})<commit_msg>skip busy file test<commit_after>
const { sortByType, clean, getFolderActions, flattenActions, itemTypes, actionTypes } = require('./')
const { ephemeralFsFromObject } = require('fs-from-object')
const { open, close, stat, utimes } = require('mz/fs')
const cpr = require('recursive-copy')
const { join } = require('path')
const rmfr = require('rmfr')
const test = require('ava')

const setupTree = (task) => {
  const oldFile = { name: 'index-old.txt', contents: 'test', mtime: new Date('06/17/2016') }
  const newFile =  { name: 'index.txt', contents: 'test', mtime: new Date('11/17/2016') }

  const tree = [
    { name: 'basic', contents: [oldFile, newFile] },

    {
      name: 'empty',
      contents: [
        { name: 'empty', contents: [] }
      ]
    },

    {
      name: 'recursive',
      contents: [
        { name: 'sub-folder', contents: [oldFile, newFile] },
        oldFile,
        newFile
      ]
    },

    {
      name: 'empty-after-delete',
      contents: [
        { name: 'sub-folder', contents: [oldFile] }
      ]
    },

    {
      name: 'test-delete',
      contents: [
        { name: 'empty-folder', contents: [] },
        { name: 'sub-folder', contents: [oldFile, newFile] },
        oldFile,
        newFile
      ]
    }
  ]

  return ephemeralFsFromObject(tree, task)
}

test('flat file list', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'basic')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: false,
      maxAge: 90
    })
    t.is(actions[0].actionType, actionTypes.DELETE)
    t.is(actions[1].actionType, actionTypes.RETAIN)
  })
})

test('recursive', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'recursive')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    t.is(actions[0].actionType, actionTypes.DELETE)
    t.is(actions[1].actionType, actionTypes.RETAIN)

    const dir = actions[2]
    t.is(dir.itemType, itemTypes.DIR)
    t.is(dir.actions[0].actionType, actionTypes.DELETE)
    t.is(dir.actions[1].actionType, actionTypes.RETAIN)
  })
})

test('empty folders', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'empty')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    t.is(actions[0].itemType, itemTypes.DIR)
    t.is(actions[0].actionType, actionTypes.DELETE)
  })
})

test('empty folders after delete', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'empty-after-delete')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    t.is(actions[0].actionType, actionTypes.DELETE)
    t.is(actions[0].actions[0].actionType, actionTypes.DELETE)
  })
})

test('flatten actions', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'recursive')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    const actionsf = flattenActions(actions)
    t.is(actionsf.length, 5)
  })
})

test('sort actions by type', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'recursive')

    const actions = await getFolderActions(path, {
      deleteAt: new Date('11/14/2016'),
      recursive: true,
      maxAge: 90
    })

    const sortedActions = sortByType(actions)
    t.is(sortedActions.delete.length, 2)
    t.is(sortedActions.retain.length, 3)
  })
})

const shouldntExist = (t, path, item) => {
  return stat(join(path, item))
    .then(() => t.fail(`old item ${item} exists`))
    .catch(() => t.pass())
}

const shouldExist = (t, path, item) => {
  return stat(join(path, item))
    .then(() => t.pass())
    .catch(() => t.fail(`old item ${item} doesn\'t exist`))
}

test('execute actions', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'test-delete')

    await clean(path, {
      deleteAt: new Date('11/14/2016'),
      deleteEmptyFolders: true,
      recursive: true,
      maxAge: 90
    })

    await Promise.all([
      shouldntExist(t, path, 'index-old.txt'),
      shouldntExist(t, path, 'sub-folder/index-old.txt'),
      shouldntExist(t, path, 'empty-folder'),

      shouldExist(t, path, 'index.txt'),
      shouldExist(t, path, 'sub-folder/index.txt')
    ])
  })
})

test.skip('busy files', (t) => {
  return setupTree(async (ephemeralPath) => {
    const path = join(ephemeralPath, 'basic')

    const fd = await open(join(path, 'index-old.txt'), 'r+')

    const actions = await clean(path, {
      deleteAt: new Date('11/14/2016'),
      deleteEmptyFolders: true,
      recursive: true,
      maxAge: 90
    })

    console.log(actions)
    await close(fd)
  })
})<|endoftext|>


<commit_before>var five = require("johnny-five");

var board = new five.Board();

board.on("ready", function() {
  var led = new five.Led(13);
  led.blink(1000);
});
<commit_msg>Testing on TW700<commit_after>var five = require("johnny-five");

var board = new five.Board({
  port: "COM3"
});

board.on("ready", function() {
  var led = new five.Led(13);
  led.blink(1000);
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-12-4 01:42:59<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>import {isArray, isObject} from "./util.js";
import {getTransformSources} from "./runtime/transform.js";
import {createHashMap} from "./hashmap.js";

//Create data node
export function createDataNode (context, name, props) {
    //Import data from source
    let node = context.addNode({
        "id": `data:${name}`,
        "type": "data",
        "value": [],
        "targets": createHashMap(),
        "props": {}
    });
    //console.log(node);
    //Check the data props
    if (isArray(props.transform) || isObject(props.transform)) {
        Object.assign(node.props, {
            "transform": props.transform
        });
        //Get transform sources and add this data as a target
        getTransformSources(context, props.transform).forEach(function (source) {
            source.targets.add(node.id, node);
        });
    }
    //Check if this data comes from an input
    if (typeof context.input[name] !== "undefined") {
        Object.assign(node, {
            "source": context.input[name]
        });
        //Add this data as a target
        context.input[name].targets.add(node.id, node);
    }
    //Check if the source is another dataset
    else if (typeof props.source === "string") {
        Object.assign(node, {
            "source": context.data[props.source]
        });
        //Add this data as a target reference of the source data
        context.data[props.source].targets.add(node.id, node);
    }
    else {
        //Other source: throw error
        //TODO
    }
    //Check for transformation to apply to this data
    //updateData(context, data);
    //Save the data to the context object
    context.data[name] = node;
}

//Update data node
export function updateDataNode (context, node) {
    //Check for transforms to this data
    //if (typeof node.props.transform === "object" && node.props.transform !== null) {
    if (typeof node.props.transform !== undefined) {
        Object.assign(node, {
            "value": context.transform(node.source.value, node.props.transform)
        });
    }
    //If no transform to apply:
    else {
        Object.assign(node, {
            "value": node.source.value
        });
    }
}

<commit_msg>data: allow parsing CSV sources (from file or text)<commit_after>import {isArray, isObject} from "./util.js";
import {getTransformSources} from "./runtime/transform.js";
import {createHashMap} from "./hashmap.js";
import {load} from "./load.js";
import {csvParse} from "./dsv.js";

//Data format parsers
let dataParser = {
    "json": function (data, options) {
        //TODO: check for array of values --> convert to array of objects
        return JSON.parse(data); //Parse as json
    },
    "csv": function (data, options) {
        return csvParse(data, options);
    }
};

//Parse data
let parseData = function (data, format) {
    if (typeof format === "undefined" || format === null) {
        return data; //Return data withput format
    }
    //Get format values
    //let parsedData = []; //Parsed data
    if (typeof format === "string" && typeof dataParser[format] !== "undefined") {
        return dataParser[format](data, null); //Return parsed data
    }
    //Check for object and format.type value provided
    else if (isObject(format) && (typeof format.type === "string" && typeof dataParser[format.type] !== "undefined")) {
        return dataParser[format.type](data, format); //Parse and return data
    }
    //Other type --> throw error (TODO)
    return [];
};

//Parse data
export function parseDataSource (props) {
    return parseData(props.value, props.format);
};

//Load and parse a data node
export function loadDataSource (props) {
    return load(props.url).then(function (data) {
        return parseData(data, props.format);
    });
}

//Create data node
export function createDataNode (context, name, props) {
    //Import data from source
    let node = context.addNode({
        "id": `data:${name}`,
        "type": "data",
        "value": [],
        "targets": createHashMap(),
        "props": {}
    });
    //console.log(node);
    //Check the data props
    if (isArray(props.transform) || isObject(props.transform)) {
        Object.assign(node.props, {
            "transform": props.transform
        });
        //Get transform sources and add this data as a target
        getTransformSources(context, props.transform).forEach(function (source) {
            source.targets.add(node.id, node);
        });
    }
    //Check if this data comes from an input
    if (typeof context.input[name] !== "undefined") {
        Object.assign(node, {
            "source": context.input[name]
        });
        //Add this data as a target
        context.input[name].targets.add(node.id, node);
    }
    //Check if the source is another dataset
    else if (typeof props.source === "string") {
        Object.assign(node, {
            "source": context.data[props.source]
        });
        //Add this data as a target reference of the source data
        context.data[props.source].targets.add(node.id, node);
    }
    else {
        //Other source: throw error
        //TODO
    }
    //Check for transformation to apply to this data
    //updateData(context, data);
    //Save the data to the context object
    context.data[name] = node;
}

//Update data node
export function updateDataNode (context, node) {
    //Check for transforms to this data
    //if (typeof node.props.transform === "object" && node.props.transform !== null) {
    if (typeof node.props.transform !== undefined) {
        Object.assign(node, {
            "value": context.transform(node.source.value, node.props.transform)
        });
    }
    //If no transform to apply:
    else {
        Object.assign(node, {
            "value": node.source.value
        });
    }
}

<|endoftext|>


<commit_before>'use strict'

const hasWindow = typeof window === 'object'
const tapdance = require('tapdance')
const router = require('./')

const run = tapdance.run
const comment = tapdance.comment
const ok = tapdance.ok

run(() => {
  comment('router setup')

  let index = 0
  let products = 0
  let productsDetail = 0
  let productPictures = 0
  let picturesDetail = 0

  const go = router.call({ foo: 'bar' }, {
    '': function indexHandler (isEntering) {
      if (isEntering) index++
      else index--
    },
    'products': function productsHandler (isEntering) {
      if (isEntering) products++
      else products--
    },
    'products/*': function productsDetailHandler (isEntering, parameters) {
      if (isEntering) productsDetail++
      else productsDetail--

      if (isEntering) {
        ok(parameters[0] === '123', 'parameter is correct')
      }
    },
    'products/*/pictures':
    function productPicturesHandler (isEntering, parameters, state) {
      if (isEntering) productPictures++
      else productPictures--

      if (isEntering) {
        if (hasWindow) {
          ok(state.baz === 'qux', 'state is passed')
        }

        ok(this.foo === 'baz', 'context is correct')
        ok(parameters[0] === '123', 'parameter is correct')
      }
    },
    'pictures/*': function picturesDetailHandler (isEntering, parameters) {
      if (isEntering) picturesDetail++
      else picturesDetail--

      ok(this.foo === 'bar', 'context is correct')
      if (isEntering) {
        ok(parameters[0] === 'abc', 'parameter is correct')
      }
    }
  }, 'prefix')

  go('products')
  ok(products === 1, 'route handler invoked')

  go('products/123')
  ok(products === 1, 'route handler not invoked')
  ok(productsDetail === 1, 'route handler invoked')

  go.call({ foo: 'baz' }, 'products/123/pictures', { baz: 'qux' })
  ok(products === 1, 'route handler not invoked')
  ok(productsDetail === 1, 'route handler not invoked')
  ok(productPictures === 1, 'route handler invoked')

  go('products/123')
  ok(products === 1, 'route handler not invoked')
  ok(productsDetail === 1, 'route handler not invoked')
  ok(productPictures === 0, 'route handler invoked')

  go('pictures/abc')
  ok(products === 0, 'route handler invoked')
  ok(productsDetail === 0, 'route handler invoked')
  ok(picturesDetail === 1, 'route handler invoked')

  return !hasWindow ? null : new Promise(resolve => {
    comment('browser testing')

    ok(window.history.length === 6, 'history events created')
    ok(window.location.pathname === '/prefix/pictures/abc', 'prefix used')
    window.history.back()

    // The `popstate` event runs on the next tick.
    setTimeout(() => {
      ok(window.location.pathname === '/prefix/products/123', 'correct route')
      ok(products === 1, 'route handler invoked')
      ok(productsDetail === 1, 'route handler invoked')
      ok(productPictures === 0, 'route handler invoked')
      ok(picturesDetail === 0, 'route handler invoked')
      resolve()
    }, 0)
  })
})
<commit_msg>fix stupid test case<commit_after>'use strict'

const hasWindow = typeof window === 'object'
const tapdance = require('tapdance')
const router = require('./')

const run = tapdance.run
const comment = tapdance.comment
const ok = tapdance.ok

run(() => {
  comment('router setup')

  let index = 0
  let products = 0
  let productsDetail = 0
  let productPictures = 0
  let picturesDetail = 0

  const go = router.call({ foo: 'bar' }, {
    '': function indexHandler (isEntering) {
      if (isEntering) index++
      else index--
    },
    'products': function productsHandler (isEntering) {
      if (isEntering) products++
      else products--
    },
    'products/*': function productsDetailHandler (isEntering, parameters) {
      if (isEntering) productsDetail++
      else productsDetail--

      if (isEntering) {
        ok(parameters[0] === '123', 'parameter is correct')
      }
    },
    'products/*/pictures':
    function productPicturesHandler (isEntering, parameters, state) {
      if (isEntering) productPictures++
      else productPictures--

      if (isEntering) {
        if (hasWindow) {
          ok(state.baz === 'qux', 'state is passed')
        }

        ok(this.foo === 'baz', 'context is correct')
        ok(parameters[0] === '123', 'parameter is correct')
      }
    },
    'pictures/*': function picturesDetailHandler (isEntering, parameters) {
      if (isEntering) picturesDetail++
      else picturesDetail--

      ok(this.foo === 'bar', 'context is correct')
      if (isEntering) {
        ok(parameters[0] === 'abc', 'parameter is correct')
      }
    }
  }, 'prefix')

  go('products')
  ok(products === 1, 'route handler invoked')

  go('products/123')
  ok(products === 1, 'route handler not invoked')
  ok(productsDetail === 1, 'route handler invoked')

  go.call({ foo: 'baz' }, 'products/123/pictures', { baz: 'qux' })
  ok(products === 1, 'route handler not invoked')
  ok(productsDetail === 1, 'route handler not invoked')
  ok(productPictures === 1, 'route handler invoked')

  go('products/123')
  ok(products === 1, 'route handler not invoked')
  ok(productsDetail === 1, 'route handler not invoked')
  ok(productPictures === 0, 'route handler invoked')

  go('pictures/abc')
  ok(products === 0, 'route handler invoked')
  ok(productsDetail === 0, 'route handler invoked')
  ok(picturesDetail === 1, 'route handler invoked')

  return !hasWindow ? null : new Promise(resolve => {
    comment('browser testing')

    ok(window.history.length === 6, 'history events created')
    ok(window.location.pathname === '/prefix/pictures/abc', 'prefix used')
    window.history.back()

    // The `popstate` event runs at some arbitrary time in the future,
    // depending on the browser. To be safe, it waits for some time.
    setTimeout(() => {
      ok(window.location.pathname === '/prefix/products/123', 'correct route')
      ok(products === 1, 'route handler invoked')
      ok(productsDetail === 1, 'route handler invoked')
      ok(productPictures === 0, 'route handler invoked')
      ok(picturesDetail === 0, 'route handler invoked')
      resolve()
    }, 100)
  })
})
<|endoftext|>


<commit_before>'use strict';

var graphics;
var sprite, sprite2, sprite3, tile;
var texture;
var input;
var clock;
var fpsUpdate = 0;
var batch;
var sound;

function start() {
	let canvas = document.getElementById('game-canvas');
	graphics = new Graphics();
	if (graphics.initialize(canvas)) {
		graphics.camera.setOrigin(canvas.width / 2, canvas.height / 2);
		input = new Input(document, canvas);
		clock = new Clock();
		texture = graphics.createTexture('img/sheet.png');
		sprite = graphics.createSprite(32, 32, texture);
		sprite.setColor(1.0, 0.0, 0.0, 1.0);
		sprite.setTextureCoordinates(0 + 0.005, 0, 0.5 - 0.005, 1.0);
		sprite.setScale(5.0, 5.0);
		tile = graphics.createSprite(32, 32, texture);
		tile.setTextureCoordinates(0.5, 0, 1.0, 1.0)
		requestAnimationFrame(update);
		batch = new SpriteBatch(graphics.gl, 2048);
		sound = new SoundManager();
		sound.register('chop', 'sound/shop.ogg', 1);
		sound.register('pot', 'sound/metalPot1.ogg', 3);
	}
}

var opressed = false;

function update() {
	requestAnimationFrame(update);
	let deltaTime = clock.restart() / 1000;
	fpsUpdate -= deltaTime;
	if (fpsUpdate < 0) {
		$("#game-fps").text(Math.round(10 / deltaTime) / 10);
		fpsUpdate = 0.1;
	}
	if (input.isKeyPressed(Keys.RIGHT_ARROW)) {
		sprite.move(100 * deltaTime, 50 * deltaTime);
		sprite.rotate(180 * deltaTime);
	}
	if (input.isKeyPressed(Keys.DOWN_ARROW)) {
		graphics.camera.move(30 * deltaTime, 10 * deltaTime);
	}
	if (!opressed && input.isKeyPressed(Keys.O)) {
		console.log('O');
		sound.play('pot');
	}
	opressed = input.isKeyPressed(Keys.O);
	draw();
}

function draw() {
	graphics.clear();
	batch.reset();
	for (let x = 0; x < 48; ++x) {
		for (let y = 0; y < 32; ++y) {
			tile.setPosition(x * 32, y * 32);
			batch.append(tile);
		}
	}
	batch.append(sprite);
	batch.draw(graphics);
}

function resizeCanvas() {
	let canvas = document.getElementById('game-canvas');
	let width = window.innerWidth;
	let height = window.innerHeight;
	if (canvas.width != width || canvas.height != height) {
		canvas.width = width;
		canvas.height = height;
		if (graphics) {
			graphics.camera.setOrthographicProjection(0, canvas.width, 0, canvas.height);
			graphics.camera.setOrigin(canvas.width / 2, canvas.height / 2);
			graphics.setViewport(0, 0, canvas.width, canvas.height);
		}
	}
}

$(function () {
	window.addEventListener('resize', resizeCanvas);
	resizeCanvas();
	start();
});

<commit_msg>Add a Game class<commit_after>'use strict';

var game;
var opressed = false;
var graphics;
var sprite, sprite2, sprite3, tile;
var texture;
var input;
var clock;
var fpsUpdate = 0;
var batch;
var sound;

class Game {
	constructor() {

	}
	start() {
		let canvas = document.getElementById('game-canvas');
		graphics = new Graphics();
		if (graphics.initialize(canvas)) {
			graphics.camera.setOrigin(canvas.width / 2, canvas.height / 2);
			input = new Input(document, canvas);
			clock = new Clock();
			texture = graphics.createTexture('img/sheet.png');
			sprite = graphics.createSprite(32, 32, texture);
			sprite.setColor(1.0, 0.0, 0.0, 1.0);
			sprite.setTextureCoordinates(0 + 0.005, 0, 0.5 - 0.005, 1.0);
			sprite.setScale(5.0, 5.0);
			tile = graphics.createSprite(32, 32, texture);
			tile.setTextureCoordinates(0.5, 0, 1.0, 1.0)
			requestAnimationFrame(() => this.update());
			batch = new SpriteBatch(graphics.gl, 2048);
			sound = new SoundManager();
			sound.register('chop', 'sound/chop.ogg', 1);
			sound.register('pot', 'sound/metalPot1.ogg', 3);
		}
	}
	update() {
		requestAnimationFrame(() => this.update());
		let deltaTime = clock.restart() / 1000;
		fpsUpdate -= deltaTime;
		if (fpsUpdate < 0) {
			$("#game-fps").text(Math.round(10 / deltaTime) / 10);
			fpsUpdate = 0.1;
		}
		if (input.isKeyPressed(Keys.RIGHT_ARROW)) {
			sprite.move(100 * deltaTime, 50 * deltaTime);
			sprite.rotate(180 * deltaTime);
		}
		if (input.isKeyPressed(Keys.DOWN_ARROW)) {
			graphics.camera.move(30 * deltaTime, 10 * deltaTime);
		}
		if (!opressed && input.isKeyPressed(Keys.O)) {
			console.log('O');
			sound.play('pot');
		}
		opressed = input.isKeyPressed(Keys.O);
		this.draw();
	}

	draw() {
		graphics.clear();
		batch.reset();
		for (let x = 0; x < 48; ++x) {
			for (let y = 0; y < 32; ++y) {
				tile.setPosition(x * 32, y * 32);
				batch.append(tile);
			}
		}
		batch.append(sprite);
		batch.draw(graphics);
	}

	resizeCanvas() {
		let canvas = document.getElementById('game-canvas');
		let width = window.innerWidth;
		let height = window.innerHeight;
		if (canvas.width != width || canvas.height != height) {
			canvas.width = width;
			canvas.height = height;
			if (graphics) {
				graphics.camera.setOrthographicProjection(0, canvas.width, 0, canvas.height);
				graphics.camera.setOrigin(canvas.width / 2, canvas.height / 2);
				graphics.setViewport(0, 0, canvas.width, canvas.height);
			}
		}
	}
}

$(function () {
	game = new Game();
	game.start();
	window.addEventListener('resize', game.resizeCanvas);
	game.resizeCanvas();
});

<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-23 23:47:21<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-13 20:53:41<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var nestObject = require('./')
  , assert = require('assert')
  , nested;

nested = nestObject({
  notSplit: true,
  'split.up': true
});

assert.deepEqual(nested, {
  notSplit: true,
  split: { up: true }
});

nested = nestObject({
  'this.is.deeply.nested': true
});

assert.deepEqual(nested, {
  this: {
    is: {
      deeply: {
        nested: true
      }
    }
  }
});

nested = nestObject({
  'too..many.periods': true
});

assert.deepEqual(nested, {
  too: {
    many: {
      periods: true
    }
  }
});

console.log('Success!');
process.exit(0);
<commit_msg>new test<commit_after>var nestObject = require('./')
  , assert = require('assert')
  , nested;

nested = nestObject({
  notSplit: true,
  'split.up': true
});

assert.deepEqual(nested, {
  notSplit: true,
  split: { up: true }
});

nested = nestObject({
  'this.is.deeply.nested': true
});

assert.deepEqual(nested, {
  this: {
    is: {
      deeply: {
        nested: true
      }
    }
  }
});

nested = nestObject({
  'too..many.periods': true
});

assert.deepEqual(nested, {
  too: {
    many: {
      periods: true
    }
  }
});

nested = nestObject({
  should: {
    be: {
      untouched: true
    }
  }
});

assert.deepEqual(nested, {
  should: {
    be: {
      untouched: true
    }
  }
});

console.log('Success!');
process.exit(0);
<|endoftext|>


<commit_before>
   /**
 * hamburger.js
 *
 * Mobile Menu Hamburger
 * =====================
 * A hamburger menu for mobile websites
 *
 * Created by Thomas Zinnbauer YMC AG  |  http://www.ymc.ch
 * Date: 21.05.13
 */

jQuery(document).ready(function () {

    //Open the menu
    jQuery("#hamburger").click(function () {

        jQuery('#content').css('min-height', jQuery(window).height());

        jQuery('nav').css('opacity', 1);

        //set the width of primary content container -> content should not scale while animating
        var contentWidth = jQuery('#content').width();

        //set the content with the width that it has originally
        jQuery('#content').css('width', contentWidth);

        //display a layer to disable clicking and scrolling on the content while menu is shown
        jQuery('#contentLayer').css('display', 'block');

        //disable all scrolling on mobile devices while menu is shown
        jQuery('#container').bind('touchmove', function (e) {
            e.preventDefault()
        });

        //set margin for the whole container with a jquery UI animation
        //use stop(true) to fix jQuery overlapping issue with animation
        //if the first argument is true, removes all animations in the queue
        jQuery("#container").stop(true).animate({"marginLeft": ["70%", 'easeOutExpo']}, {
            duration: 700
        });

    });

    //close the menu
    jQuery("#contentLayer").click(function () {

        //enable all scrolling on mobile devices when menu is closed
        jQuery('#container').unbind('touchmove');

        //set margin for the whole container back to original state with a jquery UI animation
        //use stop(true) to fix jQuery overlapping issue with animation
        //if the first argument is true, removes all animations in the queue
        jQuery("#container").stop(true).animate({"marginLeft": ["-1", 'easeOutExpo']}, {
            duration: 700,
            complete: function () {
                jQuery('#content').css('width', 'auto');
                jQuery('#contentLayer').css('display', 'none');
                jQuery('nav').css('opacity', 0);
                jQuery('#content').css('min-height', 'auto');

            }
        });
    });

});
<commit_msg>Delete test.js<commit_after><|endoftext|>


<commit_before>/* istanbul ignore next */
describe('stingray', function () {
  'use strict';

  //
  // Introduce some globals as this library should run in browsers only unless
  // we polyfill/mock some browser things.
  //
  global.Image = require('beacons/image');
  global.navigator = {
    cookieEnabled: true,
    language: 'en-US',
    productSub: '20030107',
    product: 'Gecko',
    appCodeName: 'Mozilla',
    mimeTypes: { length: 0 },
    vendorSub: '',
    vendor: 'Apple Computer, Inc.',
    platform: 'MacIntel',
    appName: 'Netscape',
    appVersion: '5.0 (Macintosh; Intel Mac OS X) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34',
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34',
    plugins: { length: 0 },
    onLine: false
  };

  global.document =  {
    charset: 'UTF-8',
    domain: 'localhost',
    inputEncoding: 'UTF-8',
    readyState: 'complete',
    referrer: '',
    URL: 'http://localhost:52091/?brout',
    visibility: undefined
  };

  var qs = require('querystringify')
    , parse = require('url-parse')
    , assume = require('assume')
    , Stingray = require('./')
    , server
    , stingray;

  beforeEach(function () {
    server = 'http://example.com';
    stingray = new Stingray(server);
  });

  it('is exported a function', function () {
    assume(Stingray).is.a('function');
  });

  it('can be constructed without new', function () {
    assume(Stingray()).is.instanceof(Stingray);
  });

  describe('construction', function () {
    it('accepts a custom limit', function () {
      var u = new Stingray(server, { limit : 500 });

      assume(u.limit).does.not.equal(stingray.limit);
      assume(u.limit).equals(500);
    });
  });

  describe('#set', function () {
    it('sets items to the internal data set', function () {
      assume(stingray.dataset).is.a('object');
      assume(stingray.dataset.foo).equals(undefined);

      stingray.set('foo', 'bar');
      assume(stingray.dataset.foo).equals('bar');
    });

    it('overrides existing values', function () {
      stingray.set('foo', 'bar');
      assume(stingray.dataset.foo).equals('bar');

      stingray.set('foo', 'foo');
      assume(stingray.dataset.foo).equals('foo');
    });

    it('chains', function () {
      assume(stingray.set('foo', 'bar')).equals(stingray);
    });
  });

  describe('#remove', function () {
    it('can remove added keys', function () {
      stingray.set('foo', 'bar').set('bar', 'foo');

      assume(stingray.dataset.foo).equals('bar');
      assume(stingray.dataset.bar).equals('foo');

      stingray.remove('foo');
      assume(stingray.dataset.foo).equals(undefined);
      assume(stingray.dataset.bar).equals('foo');
    });

    it('can remove multiple keys', function () {
      stingray.set('foo', 'bar').set('bar', 'foo');

      assume(stingray.dataset.foo).equals('bar');
      assume(stingray.dataset.bar).equals('foo');

      stingray.remove('foo', 'bar');
      assume(stingray.dataset.foo).equals(undefined);
      assume(stingray.dataset.bar).equals(undefined);
    });

    it('can remove multiple keys if first arg is space/comma separated', function () {
      stingray.set('foo', 'bar').set('bar', 'foo');

      assume(stingray.dataset.foo).equals('bar');
      assume(stingray.dataset.bar).equals('foo');

      stingray.remove('foo, bar');
      assume(stingray.dataset.foo).equals(undefined);
      assume(stingray.dataset.bar).equals(undefined);
    });

    it('chains', function () {
      assume(stingray.remove('foo', 'bar')).equals(stingray);
    });
  });

  describe('#payload', function () {
    it('returns an object', function () {
      var data = stingray.payload();

      assume(data).is.a('object');
    });

    it('returns an object that can be transformed in to a querystring', function () {
      var data = stingray.payload()
        , string = qs.stringify(data);

      assume(string).is.a('string');
      assume(string.length).is.below(stingray.limit);
      assume(string).contains('=');
      assume(string).contains('&');

      //
      // Before we can compare we need to transform all the values in the object
      // to strings so we can have a fair chance at matching
      //
      for (var key in data) {
        if (data.hasOwnProperty(key)) {
          data[key] = data[key].toString();
        }
      }

      assume(qs.parse(string)).deep.equals(data);
    });

    it('merges data from the initally supplied dataset', function () {
      var u = new Stingray(server, { dataset: { foo: 'bar' }})
        , data = u.payload();

      assume(data.foo).equals('bar');
    });

    it('cannot override values that are previously set', function () {
      var u = new Stingray(server, { dataset: { domain: 'bar' }})
        , data = u.payload();

      assume(data.domain).equals('bar');
      assume(stingray.payload().domain).does.not.equal(data.domain);
    });

    it('setss the custom values from the .set command', function () {
      stingray.set('domain', 'bar');
      assume(stingray.payload().domain).equals('bar');

      stingray.set('foo', 'bar');
      assume(stingray.payload().foo).equals('bar');
    });

    it('includes performance information when available', function () {
      var perf = global.performance;
      global.performance = { timing: { shizzle: 'mynizzle' }, memory: { leak: 'it' }};

      var data = stingray.payload();

      assume(data.shizzle).equals('mynizzle');
      assume(data.leak).equals('it');

      global.performance = perf;
    });
  });

  describe('#write', function () {
    it('returns false when the generate url is to damn large', function () {
      var u = new Stingray(server, { limit: 500 })
        , url = u.server + qs.stringify(u.payload(), true);

      assume(url.length).is.above(500);
      assume(u.write()).is.false();
    });

    it('returns true if its successfully written', function () {
      assume(stingray.write()).is.true();
    });
  });
});
<commit_msg>[test] Adding destroy to tests<commit_after>/* istanbul ignore next */
describe('stingray', function () {
  'use strict';

  //
  // Introduce some globals as this library should run in browsers only unless
  // we polyfill/mock some browser things.
  //
  global.Image = require('beacons/image');
  global.navigator = {
    cookieEnabled: true,
    language: 'en-US',
    productSub: '20030107',
    product: 'Gecko',
    appCodeName: 'Mozilla',
    mimeTypes: { length: 0 },
    vendorSub: '',
    vendor: 'Apple Computer, Inc.',
    platform: 'MacIntel',
    appName: 'Netscape',
    appVersion: '5.0 (Macintosh; Intel Mac OS X) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34',
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34',
    plugins: { length: 0 },
    onLine: false
  };

  global.document =  {
    charset: 'UTF-8',
    domain: 'localhost',
    inputEncoding: 'UTF-8',
    readyState: 'complete',
    referrer: '',
    URL: 'http://localhost:52091/?brout',
    visibility: undefined
  };

  var qs = require('querystringify')
    , parse = require('url-parse')
    , assume = require('assume')
    , Stingray = require('./')
    , server
    , stingray;

  beforeEach(function () {
    server = 'http://example.com';
    stingray = new Stingray(server);
  });

  afterEach(function () {
    stingray.destroy();
  });

  it('is exported a function', function () {
    assume(Stingray).is.a('function');
  });

  it('can be constructed without new', function () {
    assume(Stingray()).is.instanceof(Stingray);
  });

  describe('construction', function () {
    it('accepts a custom limit', function () {
      var u = new Stingray(server, { limit : 500 });

      assume(u.limit).does.not.equal(stingray.limit);
      assume(u.limit).equals(500);
    });
  });

  describe('#set', function () {
    it('sets items to the internal data set', function () {
      assume(stingray.dataset).is.a('object');
      assume(stingray.dataset.foo).equals(undefined);

      stingray.set('foo', 'bar');
      assume(stingray.dataset.foo).equals('bar');
    });

    it('overrides existing values', function () {
      stingray.set('foo', 'bar');
      assume(stingray.dataset.foo).equals('bar');

      stingray.set('foo', 'foo');
      assume(stingray.dataset.foo).equals('foo');
    });

    it('chains', function () {
      assume(stingray.set('foo', 'bar')).equals(stingray);
    });
  });

  describe('#remove', function () {
    it('can remove added keys', function () {
      stingray.set('foo', 'bar').set('bar', 'foo');

      assume(stingray.dataset.foo).equals('bar');
      assume(stingray.dataset.bar).equals('foo');

      stingray.remove('foo');
      assume(stingray.dataset.foo).equals(undefined);
      assume(stingray.dataset.bar).equals('foo');
    });

    it('can remove multiple keys', function () {
      stingray.set('foo', 'bar').set('bar', 'foo');

      assume(stingray.dataset.foo).equals('bar');
      assume(stingray.dataset.bar).equals('foo');

      stingray.remove('foo', 'bar');
      assume(stingray.dataset.foo).equals(undefined);
      assume(stingray.dataset.bar).equals(undefined);
    });

    it('can remove multiple keys if first arg is space/comma separated', function () {
      stingray.set('foo', 'bar').set('bar', 'foo');

      assume(stingray.dataset.foo).equals('bar');
      assume(stingray.dataset.bar).equals('foo');

      stingray.remove('foo, bar');
      assume(stingray.dataset.foo).equals(undefined);
      assume(stingray.dataset.bar).equals(undefined);
    });

    it('chains', function () {
      assume(stingray.remove('foo', 'bar')).equals(stingray);
    });
  });

  describe('#payload', function () {
    it('returns an object', function () {
      var data = stingray.payload();

      assume(data).is.a('object');
    });

    it('returns an object that can be transformed in to a querystring', function () {
      var data = stingray.payload()
        , string = qs.stringify(data);

      assume(string).is.a('string');
      assume(string.length).is.below(stingray.limit);
      assume(string).contains('=');
      assume(string).contains('&');

      //
      // Before we can compare we need to transform all the values in the object
      // to strings so we can have a fair chance at matching
      //
      for (var key in data) {
        if (data.hasOwnProperty(key)) {
          data[key] = data[key].toString();
        }
      }

      assume(qs.parse(string)).deep.equals(data);
    });

    it('merges data from the initally supplied dataset', function () {
      var u = new Stingray(server, { dataset: { foo: 'bar' }})
        , data = u.payload();

      assume(data.foo).equals('bar');
    });

    it('cannot override values that are previously set', function () {
      var u = new Stingray(server, { dataset: { domain: 'bar' }})
        , data = u.payload();

      assume(data.domain).equals('bar');
      assume(stingray.payload().domain).does.not.equal(data.domain);
    });

    it('setss the custom values from the .set command', function () {
      stingray.set('domain', 'bar');
      assume(stingray.payload().domain).equals('bar');

      stingray.set('foo', 'bar');
      assume(stingray.payload().foo).equals('bar');
    });

    it('includes performance information when available', function () {
      var perf = global.performance;
      global.performance = { timing: { shizzle: 'mynizzle' }, memory: { leak: 'it' }};

      var data = stingray.payload();

      assume(data.shizzle).equals('mynizzle');
      assume(data.leak).equals('it');

      global.performance = perf;
    });
  });

  describe('#write', function () {
    it('returns false when the generate url is to damn large', function () {
      var u = new Stingray(server, { limit: 500 })
        , url = u.server + qs.stringify(u.payload(), true);

      assume(url.length).is.above(500);
      assume(u.write()).is.false();
    });

    it('returns true if its successfully written', function () {
      assume(stingray.write()).is.true();
    });
  });

  describe('#destroy', function () {
    it('returns true on first destroy', function () {
      assume(stingray.destroy()).is.true();
    });

    it('returns false on second destroy', function () {
      assume(stingray.destroy()).is.true();
      assume(stingray.destroy()).is.false();
    });
  });
});
<|endoftext|>