<commit_before>// Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import { expect } from 'chai';

export default function checkDump(dump, expected) {
  expect(normalize(expected)).to.be.equal(normalize(dump));
}

function normalize(dump) {
  return dump
    .split('\n')
    .map(line => line.trim())
    .filter(line => line.length > 0)
    .join('\n');
}
<commit_msg>remove unnecessary filter from "checkDump" test helper<commit_after>// Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import { expect } from 'chai';

export default function checkDump(dump, expected) {
  expect(normalize(expected)).to.be.equal(normalize(dump));
}

function normalize(dump) {
  return dump
    .trim()
    .split('\n')
    .map(line => line.trim())
    .join('\n');
}
<|endoftext|>


<commit_before>define(["helper/Test", "Tone/core/Tone", "helper/PassAudio", "Tone/source/Oscillator",
	"Tone/instrument/Synth", "helper/Offline",
	"Tone/component/Filter", "Tone/core/Gain", "Tone/core/Context",
	"helper/BufferTest", "Tone/component/Merge", "Tone/signal/Signal", "Tone/component/Split", "helper/Supports", "sinon"],
function(Test, Tone, PassAudio, Oscillator, Synth, Offline,
	Filter, Gain, Context, BufferTest, Merge, Signal, Split, Supports, sinon){

	describe("Tone", function(){

		it("can be created and disposed", function(){
			var t = new Tone();
			t.dispose();
			Test.wasDisposed(t);
		});

		it("must be invoked with 'new'", function(){
			expect(function(){
				var t = Tone();
			}).to.throw(Error);
		});

		it("returns the class name with toString()", function(){
			var t = new Tone();
			expect(t.toString()).to.equal("Tone");
			t.dispose();
			var g = new Gain();
			expect(g.toString()).to.equal("Gain");
			g.dispose();
		});

		context("Unit Conversions", function(){
			it("can convert gain to db", function(){
				expect(Tone.gainToDb(0)).to.equal(-Infinity);
				expect(Tone.gainToDb(1)).is.closeTo(0, 0.1);
				expect(Tone.gainToDb(0.5)).is.closeTo(-6, 0.1);
			});

			it("can convert db to gain", function(){
				expect(Tone.dbToGain(0)).is.closeTo(1, 0.1);
				expect(Tone.dbToGain(-12)).is.closeTo(0.25, 0.1);
				expect(Tone.dbToGain(-24)).is.closeTo(0.125, 0.1);
			});

			it("can convert back and forth between db and gain representations", function(){
				expect(Tone.dbToGain(Tone.gainToDb(0))).is.closeTo(0, 0.01);
				expect(Tone.dbToGain(Tone.gainToDb(0.5))).is.closeTo(0.5, 0.01);
				expect(Tone.gainToDb(Tone.dbToGain(1))).is.closeTo(1, 0.01);
			});

			it("can convert semitone intervals to frequency ratios", function(){
				expect(Tone.intervalToFrequencyRatio(0)).to.equal(1);
				expect(Tone.intervalToFrequencyRatio(12)).to.equal(2);
				expect(Tone.intervalToFrequencyRatio(7)).to.be.closeTo(1.5, 0.01);
			});
		});

		context("Debugging", function(){

			it("logs when the class is set on the window", function(){
				var spy = sinon.stub(console, "log");
				window.TONE_DEBUG_CLASS = "Oscillator";
				var osc = new Oscillator();
				osc.start().stop();
				expect(spy.callCount).to.equal(2);
				console.log.restore();
			});

			it("assert throws an error if the boolean is false", function(){
				expect(function(){
					var tone = new Tone();
					tone.assert(false, "throws error");
				}).throws(Error);
			});

		});

		context("Type checking", function(){

			it("can test if an argument is a undefined", function(){
				expect(Tone.isUndef(undefined)).to.be.true;
				expect(Tone.isUndef("seomthing")).to.be.false;
				expect(Tone.isUndef({})).to.be.false;
			});

			it("can test if an argument is a function", function(){
				expect(Tone.isFunction(undefined)).to.be.false;
				expect(Tone.isFunction(function(){})).to.be.true;
				expect(Tone.isFunction(Tone)).to.be.true;
			});

			it("can test if an argument is a number", function(){
				expect(Tone.isNumber(undefined)).to.be.false;
				expect(Tone.isNumber(function(){})).to.be.false;
				expect(Tone.isNumber(Tone)).to.be.false;
				expect(Tone.isNumber(10)).to.be.true;
				expect(Tone.isNumber("10")).to.be.false;
			});

			it("can test if an argument is an object literal", function(){
				expect(Tone.isObject(Number)).to.be.false;
				expect(Tone.isObject(function(){})).to.be.false;
				expect(Tone.isObject(new Tone())).to.be.false;
				expect(Tone.isObject({})).to.be.true;
				expect(Tone.isObject([])).to.be.false;
				expect(Tone.isObject("10")).to.be.false;
			});

			it("can test if an argument is an array", function(){
				expect(Tone.isArray(Number)).to.be.false;
				expect(Tone.isArray({})).to.be.false;
				expect(Tone.isArray([])).to.be.true;
			});

			it("can test if an argument is a boolean", function(){
				expect(Tone.isBoolean(Number)).to.be.false;
				expect(Tone.isBoolean(true)).to.be.true;
				expect(Tone.isBoolean(false)).to.be.true;
				expect(Tone.isBoolean([])).to.be.false;
			});

			it("can test if an argument is a string", function(){
				expect(Tone.isString(Number)).to.be.false;
				expect(Tone.isString(true)).to.be.false;
				expect(Tone.isString("false")).to.be.true;
				expect(Tone.isString("thanks")).to.be.true;
			});

			it("can test if an argument is a note", function(){
				expect(Tone.isNote(undefined)).to.be.false;
				expect(Tone.isNote(function(){})).to.be.false;
				expect(Tone.isNote(Tone)).to.be.false;
				expect(Tone.isNote("Cb2")).to.be.true;
				expect(Tone.isNote("10")).to.be.false;
				expect(Tone.isNote("C4")).to.be.true;
				expect(Tone.isNote("D4")).to.be.true;
				expect(Tone.isNote("Db4")).to.be.true;
				expect(Tone.isNote("E4")).to.be.true;
				expect(Tone.isNote("Fx2")).to.be.true;
				expect(Tone.isNote("Gbb-1")).to.be.true;
				expect(Tone.isNote("A#10")).to.be.true;
				expect(Tone.isNote("Bb2")).to.be.true;
			});
		});

		context("defaults", function(){

			it("returns a default argument when the given is not defined", function(){
				expect(Tone.defaultArg(undefined, 0)).is.equal(0);
				expect(Tone.defaultArg(undefined, "also")).is.equal("also");
				expect(Tone.defaultArg("hihi", 100)).is.equal("hihi");
			});

			it("handles default arguments on a shallow object", function(){
				expect(Tone.defaultArg({ "b" : 10 }, { "a" : 4, "b" : 10 })).has.property("a", 4);
				expect(Tone.defaultArg({ "b" : 10, "c" : 20 }, { "a" : 4, "b" : 10 })).has.property("b", 10);
				expect(Tone.defaultArg({ "b" : 10, "c" : 20 }, { "a" : 4, "b" : 10 })).has.property("c", 20);
			});

			it("handles default arguments on a deep object", function(){
				expect(Tone.defaultArg({ "b" : { "c" : 10 } }, { "b" : { "c" : 20, "d" : 30 } })).has.deep.property("b.d", 30);
				expect(Tone.defaultArg({ "a" : 10 }, { "b" : { "c" : 20 } })).has.deep.property("b.c", 20);
			});

			it("maps array parameters to an object", function(){
				expect(Tone.defaults([1, 2], ["a", "b"], {})).is.deep.equal({
					"a" : 1,
					"b" : 2
				});
			});

			it("maps array parameters to an object with missing arguments", function(){
				expect(Tone.defaults([1, 2], ["a", "b", "c"], {})).is.deep.equal({
					"a" : 1,
					"b" : 2,
					"c" : undefined
				});
			});

			it("gets default arguments after creating options object", function(){
				var constr = {
					"defaults" : { "c" : 3 }
				};
				expect(Tone.defaults([1, 2], ["a", "b", "c"], constr)).is.deep.equal({
					"a" : 1,
					"b" : 2,
					"c" : 3
				});
			});

			it("uses constr as an object if third argument doesn't have a 'defaults' property", function(){
				expect(Tone.defaults([1, 2], ["a", "b", "c"], { "c" : 3 })).is.deep.equal({
					"a" : 1,
					"b" : 2,
					"c" : 3
				});
			});

			it("does not map parameter if first argument is already an object", function(){
				expect(Tone.defaults([{ "a" : 2, "b" : 3 }], ["a", "b", "c"], {})).is.deep.equal({
					"a" : 2,
					"b" : 3,
				});
			});

		});

		context("Tone.context", function(){

			if (Supports.AUDIO_CONTEXT_CLOSE_RESOLVES){

				it("can set a new context", function(){
					var origCtx = Tone.context;
					var ctx = new Context();
					Tone.context = ctx;
					expect(Tone.context).to.equal(ctx);
					expect(Tone.prototype.context).to.equal(ctx);
					//then set it back
					Tone.setContext(origCtx);
					expect(Tone.context).to.equal(origCtx);
					expect(Tone.prototype.context).to.equal(origCtx);
					return ctx.dispose();
				});

				it("new context can be a raw audio context", function(){
					var origCtx = Tone.context;
					var ctx = new AudioContext();
					Tone.context = ctx;
					//wraps it in a Tone.Context
					expect(Tone.context).to.be.instanceOf(Context);
					//then set it back
					Tone.setContext(origCtx);
					expect(Tone.context).to.equal(origCtx);
					expect(Tone.prototype.context).to.equal(origCtx);
					//and a saftey check
					return ctx.close();
				});
			}

		});

		context("Tone.prototype.set / get", function(){

			it("sets a value given an object", function(){
				var osc = new Oscillator(0);
				osc.set({
					"frequency" : 30
				});
				expect(osc.frequency.value).to.be.closeTo(30, 0.001);
				osc.dispose();
			});

			it("sets a value given a string and a value", function(){
				var osc = new Oscillator(0);
				osc.set("frequency", 2);
				expect(osc.frequency.value).to.be.closeTo(2, 0.001);
				osc.dispose();
			});

			it("ramps to a value given an object and ramp time", function(){
				return Offline(function(){
					var osc = new Oscillator(0).toMaster();
					var setValue = 30;
					osc.frequency.toMaster();
					osc.set({
						"frequency" : setValue
					}, 0.5);
					expect(osc.frequency.value).to.not.be.closeTo(setValue, 0.001);

					return function(sample, time){
						if (time > 0.5){
							expect(sample).to.closeTo(setValue, setValue * 0.1);
						}
					};
				});
			});

			it("ramps to a value given a string and a value and a ramp time", function(){
				return Offline(function(){
					var osc = new Oscillator(0).toMaster();
					var setValue = 20;
					osc.frequency.toMaster();
					osc.set("frequency", setValue, 0.2);
					expect(osc.frequency.value).to.not.be.closeTo(setValue, 0.001);
				}).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (time > 0.2){
							expect(sample).to.closeTo(setValue, setValue * 0.1);
						}
					});
				});
			});

			it("gets all defaults of the object with no arguments", function(){
				var osc = new Oscillator(0);
				expect(osc.get()).to.contain.keys(Object.keys(Oscillator.defaults));
				osc.dispose();
			});

			it("can 'get' only the given keys", function(){
				var osc = new Oscillator(0);
				var keys = ["frequency", "type"];
				expect(Object.keys(osc.get(keys))).to.deep.equal(keys);
				osc.dispose();
			});

			it("can 'set' a nested object", function(){
				var synth = new Synth();
				synth.set({
					"oscillator" : {
						"type" : "square2"
					}
				});
				expect(synth.oscillator.type).to.equal("square2");
				synth.dispose();
			});

			it("can 'set' a value with dot notation", function(){
				var synth = new Synth();
				synth.set("oscillator.type", "triangle");
				expect(synth.oscillator.type).to.equal("triangle");
				synth.dispose();
			});

			it("can 'get' a value with dot notation", function(){
				var synth = new Synth();
				synth.set({
					"oscillator" : {
						"type" : "sine10",
						"phase" : 20,
					}
				});
				expect(synth.get("oscillator.type").oscillator.type).to.equal("sine10");
				//get multiple values
				expect(synth.get(["oscillator.type", "oscillator.phase"])).to.deep.equal({
					"oscillator" : {
						"type" : "sine10",
						"phase" : 20,
					}
				});
				synth.dispose();
			});

		});
	});

});
<commit_msg>restoring the debug state<commit_after>define(["helper/Test", "Tone/core/Tone", "helper/PassAudio", "Tone/source/Oscillator",
	"Tone/instrument/Synth", "helper/Offline",
	"Tone/component/Filter", "Tone/core/Gain", "Tone/core/Context",
	"helper/BufferTest", "Tone/component/Merge", "Tone/signal/Signal", "Tone/component/Split", "helper/Supports", "sinon"],
function(Test, Tone, PassAudio, Oscillator, Synth, Offline,
	Filter, Gain, Context, BufferTest, Merge, Signal, Split, Supports, sinon){

	describe("Tone", function(){

		it("can be created and disposed", function(){
			var t = new Tone();
			t.dispose();
			Test.wasDisposed(t);
		});

		it("must be invoked with 'new'", function(){
			expect(function(){
				var t = Tone();
			}).to.throw(Error);
		});

		it("returns the class name with toString()", function(){
			var t = new Tone();
			expect(t.toString()).to.equal("Tone");
			t.dispose();
			var g = new Gain();
			expect(g.toString()).to.equal("Gain");
			g.dispose();
		});

		context("Unit Conversions", function(){
			it("can convert gain to db", function(){
				expect(Tone.gainToDb(0)).to.equal(-Infinity);
				expect(Tone.gainToDb(1)).is.closeTo(0, 0.1);
				expect(Tone.gainToDb(0.5)).is.closeTo(-6, 0.1);
			});

			it("can convert db to gain", function(){
				expect(Tone.dbToGain(0)).is.closeTo(1, 0.1);
				expect(Tone.dbToGain(-12)).is.closeTo(0.25, 0.1);
				expect(Tone.dbToGain(-24)).is.closeTo(0.125, 0.1);
			});

			it("can convert back and forth between db and gain representations", function(){
				expect(Tone.dbToGain(Tone.gainToDb(0))).is.closeTo(0, 0.01);
				expect(Tone.dbToGain(Tone.gainToDb(0.5))).is.closeTo(0.5, 0.01);
				expect(Tone.gainToDb(Tone.dbToGain(1))).is.closeTo(1, 0.01);
			});

			it("can convert semitone intervals to frequency ratios", function(){
				expect(Tone.intervalToFrequencyRatio(0)).to.equal(1);
				expect(Tone.intervalToFrequencyRatio(12)).to.equal(2);
				expect(Tone.intervalToFrequencyRatio(7)).to.be.closeTo(1.5, 0.01);
			});
		});

		context("Debugging", function(){

			it("logs when the class is set on the window", function(){
				var spy = sinon.stub(console, "log");
				window.TONE_DEBUG_CLASS = "Oscillator";
				var osc = new Oscillator();
				osc.start().stop();
				expect(spy.callCount).to.equal(2);
				spy.restore();
				window.TONE_DEBUG_CLASS = null;
			});

			it("assert throws an error if the boolean is false", function(){
				expect(function(){
					var tone = new Tone();
					tone.assert(false, "throws error");
				}).throws(Error);
			});

		});

		context("Type checking", function(){

			it("can test if an argument is a undefined", function(){
				expect(Tone.isUndef(undefined)).to.be.true;
				expect(Tone.isUndef("seomthing")).to.be.false;
				expect(Tone.isUndef({})).to.be.false;
			});

			it("can test if an argument is a function", function(){
				expect(Tone.isFunction(undefined)).to.be.false;
				expect(Tone.isFunction(function(){})).to.be.true;
				expect(Tone.isFunction(Tone)).to.be.true;
			});

			it("can test if an argument is a number", function(){
				expect(Tone.isNumber(undefined)).to.be.false;
				expect(Tone.isNumber(function(){})).to.be.false;
				expect(Tone.isNumber(Tone)).to.be.false;
				expect(Tone.isNumber(10)).to.be.true;
				expect(Tone.isNumber("10")).to.be.false;
			});

			it("can test if an argument is an object literal", function(){
				expect(Tone.isObject(Number)).to.be.false;
				expect(Tone.isObject(function(){})).to.be.false;
				expect(Tone.isObject(new Tone())).to.be.false;
				expect(Tone.isObject({})).to.be.true;
				expect(Tone.isObject([])).to.be.false;
				expect(Tone.isObject("10")).to.be.false;
			});

			it("can test if an argument is an array", function(){
				expect(Tone.isArray(Number)).to.be.false;
				expect(Tone.isArray({})).to.be.false;
				expect(Tone.isArray([])).to.be.true;
			});

			it("can test if an argument is a boolean", function(){
				expect(Tone.isBoolean(Number)).to.be.false;
				expect(Tone.isBoolean(true)).to.be.true;
				expect(Tone.isBoolean(false)).to.be.true;
				expect(Tone.isBoolean([])).to.be.false;
			});

			it("can test if an argument is a string", function(){
				expect(Tone.isString(Number)).to.be.false;
				expect(Tone.isString(true)).to.be.false;
				expect(Tone.isString("false")).to.be.true;
				expect(Tone.isString("thanks")).to.be.true;
			});

			it("can test if an argument is a note", function(){
				expect(Tone.isNote(undefined)).to.be.false;
				expect(Tone.isNote(function(){})).to.be.false;
				expect(Tone.isNote(Tone)).to.be.false;
				expect(Tone.isNote("Cb2")).to.be.true;
				expect(Tone.isNote("10")).to.be.false;
				expect(Tone.isNote("C4")).to.be.true;
				expect(Tone.isNote("D4")).to.be.true;
				expect(Tone.isNote("Db4")).to.be.true;
				expect(Tone.isNote("E4")).to.be.true;
				expect(Tone.isNote("Fx2")).to.be.true;
				expect(Tone.isNote("Gbb-1")).to.be.true;
				expect(Tone.isNote("A#10")).to.be.true;
				expect(Tone.isNote("Bb2")).to.be.true;
			});
		});

		context("defaults", function(){

			it("returns a default argument when the given is not defined", function(){
				expect(Tone.defaultArg(undefined, 0)).is.equal(0);
				expect(Tone.defaultArg(undefined, "also")).is.equal("also");
				expect(Tone.defaultArg("hihi", 100)).is.equal("hihi");
			});

			it("handles default arguments on a shallow object", function(){
				expect(Tone.defaultArg({ "b" : 10 }, { "a" : 4, "b" : 10 })).has.property("a", 4);
				expect(Tone.defaultArg({ "b" : 10, "c" : 20 }, { "a" : 4, "b" : 10 })).has.property("b", 10);
				expect(Tone.defaultArg({ "b" : 10, "c" : 20 }, { "a" : 4, "b" : 10 })).has.property("c", 20);
			});

			it("handles default arguments on a deep object", function(){
				expect(Tone.defaultArg({ "b" : { "c" : 10 } }, { "b" : { "c" : 20, "d" : 30 } })).has.deep.property("b.d", 30);
				expect(Tone.defaultArg({ "a" : 10 }, { "b" : { "c" : 20 } })).has.deep.property("b.c", 20);
			});

			it("maps array parameters to an object", function(){
				expect(Tone.defaults([1, 2], ["a", "b"], {})).is.deep.equal({
					"a" : 1,
					"b" : 2
				});
			});

			it("maps array parameters to an object with missing arguments", function(){
				expect(Tone.defaults([1, 2], ["a", "b", "c"], {})).is.deep.equal({
					"a" : 1,
					"b" : 2,
					"c" : undefined
				});
			});

			it("gets default arguments after creating options object", function(){
				var constr = {
					"defaults" : { "c" : 3 }
				};
				expect(Tone.defaults([1, 2], ["a", "b", "c"], constr)).is.deep.equal({
					"a" : 1,
					"b" : 2,
					"c" : 3
				});
			});

			it("uses constr as an object if third argument doesn't have a 'defaults' property", function(){
				expect(Tone.defaults([1, 2], ["a", "b", "c"], { "c" : 3 })).is.deep.equal({
					"a" : 1,
					"b" : 2,
					"c" : 3
				});
			});

			it("does not map parameter if first argument is already an object", function(){
				expect(Tone.defaults([{ "a" : 2, "b" : 3 }], ["a", "b", "c"], {})).is.deep.equal({
					"a" : 2,
					"b" : 3,
				});
			});

		});

		context("Tone.context", function(){

			if (Supports.AUDIO_CONTEXT_CLOSE_RESOLVES){

				it("can set a new context", function(){
					var origCtx = Tone.context;
					var ctx = new Context();
					Tone.context = ctx;
					expect(Tone.context).to.equal(ctx);
					expect(Tone.prototype.context).to.equal(ctx);
					//then set it back
					Tone.setContext(origCtx);
					expect(Tone.context).to.equal(origCtx);
					expect(Tone.prototype.context).to.equal(origCtx);
					return ctx.dispose();
				});

				it("new context can be a raw audio context", function(){
					var origCtx = Tone.context;
					var ctx = new AudioContext();
					Tone.context = ctx;
					//wraps it in a Tone.Context
					expect(Tone.context).to.be.instanceOf(Context);
					//then set it back
					Tone.setContext(origCtx);
					expect(Tone.context).to.equal(origCtx);
					expect(Tone.prototype.context).to.equal(origCtx);
					//and a saftey check
					return ctx.close();
				});
			}

		});

		context("Tone.prototype.set / get", function(){

			it("sets a value given an object", function(){
				var osc = new Oscillator(0);
				osc.set({
					"frequency" : 30
				});
				expect(osc.frequency.value).to.be.closeTo(30, 0.001);
				osc.dispose();
			});

			it("sets a value given a string and a value", function(){
				var osc = new Oscillator(0);
				osc.set("frequency", 2);
				expect(osc.frequency.value).to.be.closeTo(2, 0.001);
				osc.dispose();
			});

			it("ramps to a value given an object and ramp time", function(){
				return Offline(function(){
					var osc = new Oscillator(0).toMaster();
					var setValue = 30;
					osc.frequency.toMaster();
					osc.set({
						"frequency" : setValue
					}, 0.5);
					expect(osc.frequency.value).to.not.be.closeTo(setValue, 0.001);

					return function(sample, time){
						if (time > 0.5){
							expect(sample).to.closeTo(setValue, setValue * 0.1);
						}
					};
				});
			});

			it("ramps to a value given a string and a value and a ramp time", function(){
				return Offline(function(){
					var osc = new Oscillator(0).toMaster();
					var setValue = 20;
					osc.frequency.toMaster();
					osc.set("frequency", setValue, 0.2);
					expect(osc.frequency.value).to.not.be.closeTo(setValue, 0.001);
				}).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (time > 0.2){
							expect(sample).to.closeTo(setValue, setValue * 0.1);
						}
					});
				});
			});

			it("gets all defaults of the object with no arguments", function(){
				var osc = new Oscillator(0);
				expect(osc.get()).to.contain.keys(Object.keys(Oscillator.defaults));
				osc.dispose();
			});

			it("can 'get' only the given keys", function(){
				var osc = new Oscillator(0);
				var keys = ["frequency", "type"];
				expect(Object.keys(osc.get(keys))).to.deep.equal(keys);
				osc.dispose();
			});

			it("can 'set' a nested object", function(){
				var synth = new Synth();
				synth.set({
					"oscillator" : {
						"type" : "square2"
					}
				});
				expect(synth.oscillator.type).to.equal("square2");
				synth.dispose();
			});

			it("can 'set' a value with dot notation", function(){
				var synth = new Synth();
				synth.set("oscillator.type", "triangle");
				expect(synth.oscillator.type).to.equal("triangle");
				synth.dispose();
			});

			it("can 'get' a value with dot notation", function(){
				var synth = new Synth();
				synth.set({
					"oscillator" : {
						"type" : "sine10",
						"phase" : 20,
					}
				});
				expect(synth.get("oscillator.type").oscillator.type).to.equal("sine10");
				//get multiple values
				expect(synth.get(["oscillator.type", "oscillator.phase"])).to.deep.equal({
					"oscillator" : {
						"type" : "sine10",
						"phase" : 20,
					}
				});
				synth.dispose();
			});

		});
	});

});
<|endoftext|>


<commit_before>/*jshint white: false, strict: false, plusplus: false, onevar: false,
  nomen: false */
/*global module: false, gladius: false, stop: false, start: false,
  expect: false, asyncTest: false, ok: false, deepEqual: false, equal: false */

(function() {
  var engine = null;

  module('core/Load', {

    setup : function() {
      stop();

      gladius.create({
        debug : true
      }, function(instance) {
        engine = instance;
        start();
      });
    },
    teardown : function() {
      engine = null;
    }
  });

  asyncTest( 'invoke load with an empty list', function() {
    expect(3);

    function onprogress ( ) {
      // TD: no start here means tests will hang, so it's probably impossible
      // for the ok() below to ever fire, but just in case...
      ok( false, "progress should not be called for 100% completion");
    }

    function oncomplete ( result ) {
      start();
      ok( true, "empty load completed");
      deepEqual(result, {}, "result set is empty after empty load done");

      // TD: test that cache has not been modified
    }

    var result = engine.core.resource.load([], {
      oncomplete: oncomplete,
      onprogress: onprogress,
      cache: "myEmptyCache"});

    deepEqual(result, {}, "result set is empty after empty load initiated");
  });

  asyncTest( 'invoke load with a single uncached resource', function() {
    expect(6);

    var resourcePath = "assets/test-loadfile1.json";

    function onprogress ( ) {
      ok( false, "progress should not be called for only 1 file");
    }

    function oncomplete ( result ) {
      ok( true, "single uncached load completed");
      ok( result.hasOwnProperty(resourcePath),
          "result set has correct URL property");

      deepEqual(result[resourcePath], {},
        "result set contains correct data");

      equal( Object.keys(result).length, 1, "result set is right size");

      start();
      // TD: test that cache has not been modified
    }

    var resourceToLoad = {
      type: "engine.core.resource.json",
      source: resourcePath,
      onsuccess: function( result ) {
        deepEqual(result, {}, "empty JSON object should have been loaded");
      },
      onfailure: function( error ) {
        ok(false, "failed to load minimal JSON file: " + error);
      }
    };

    var result = engine.core.resource.load([resourceToLoad], {
      oncomplete: oncomplete,
      onprogress: onprogress,
      cache: "myEmptyCache"});

    deepEqual(result, {}, "result set is empty after single uncached load started");
  });

  asyncTest( 'invoke load with a single non-existent resource', function() {
    expect(4);

    var resourcePath = "no-such-url-exists";

    function onprogress ( ) {
      ok( false, "progress should not be called for only 1 file");
    }

    function oncomplete ( result ) {
      // XXX should we have another callback or arg to signal that
      // something went wrong?
      ok( true, "single non-existent load completed");
      equal( Object.keys(result).length, 0, "result set is empty");

      start();
      // TD: test that cache has been appropriately modified
    }

    var resourceToLoad = {
      type: "engine.core.resource.json",
      source: resourcePath,
      onsuccess: function( result ) {
        ok(false, "non-existent file should not have loaded successfully");
      },
      onfailure: function( error ) {
        ok(true, "non-existent file failed to load: " + error);
      }
    };

    var result = engine.core.resource.load([resourceToLoad], {
      oncomplete: oncomplete,
      onprogress: onprogress,
      cache: "myEmptyCache"});

    deepEqual(result, {}, "result set is empty after non-existent load started");
  });

  asyncTest( 'load three uncached resource', function() {
    expect(12);

    var resourcePath = "assets/test-loadfile1.json";
    var resourcePath2 = "assets/test-loadfile2.json";
    var resourcePath3 = "assets/test-loadfile3.json";

    function onprogress ( ) {
      // TD (dmose): I'm not convinced that this API is very useful.  The
      // only simple granularity we can offer is calling back after each
      // file loads, and that progress updating could just be done on the
      // onsuccess/onfailure handler for each file.  I'd like to talk to
      // bzbarsky, biesi, or someone else with experience with the gecko
      // webprogress stuff.  Or, even more ideally, a UX person.  Would
      // also be interesting to chat with experienced game devs here.

      // we need to either make a passing a test or kill this API
      // before landing on the develop branch
    }

    function oncomplete ( result ) {
      ok( true, "three uncached loads completed");
      equal( Object.keys(result).length, 3, "result set is right size" );

      var resources = [resourcePath, resourcePath2, resourcePath3];
      for ( var i = 0; i < resources.length; i++ ) {
        ok( result.hasOwnProperty(resources[i]),
          "result set has expected URL property " + resources[i] );
        deepEqual(result[resources[i]], {},
          "result set contains correct data for " + resources[i] );
      }

      start();
      // TD: test that cache has been appropriately modified
    }

    function makeResourceInfo(path) {
      var r = {
        type: "engine.core.resource.json",
        source: path,
        onsuccess: function( result ) {
          deepEqual(result, {}, "empty JSON object should have been loaded");
        },
        onfailure: function( error ) {
          ok(false, "failed to load minimal JSON file: " + error);
        }
      };

      return r;
    }

    var resourcesToLoad = [
      makeResourceInfo(resourcePath),
      makeResourceInfo(resourcePath2),
      makeResourceInfo(resourcePath3)
    ];

    var result = engine.core.resource.load(resourcesToLoad, {
      oncomplete: oncomplete,
      onprogress: onprogress,
      cache: "myEmptyCache"});

    deepEqual(result, {}, "result set is empty after single uncached load started");
  });

  // TD: test group load with some failing & some succeeding loads

  // TD: test constructor type handling

  // TD: test what happens when itemsToLoad contains dups &
  // non-canonicalized dups

  // TD: test that passing in various edge cases and null for options
  // behaves appropriately

  // TD: test what happens when itemsToLoad is not an array.  duck-type as
  // single object to load?

  // TD: ensure that we test that result is not populated before one of
  // onprogress or oncomplete is called; refactor regular resources to
  // behave this way?

  // TD: progress should not be called at 100% complete; get rid of onprogress
  // ok()

}());
<commit_msg>Tweak a few comments and move makeResourceInfo to a broader scope<commit_after>/*jshint white: false, strict: false, plusplus: false, onevar: false,
  nomen: false */
/*global module: false, gladius: false, stop: false, start: false,
  expect: false, asyncTest: false, ok: false, deepEqual: false, equal: false */

(function() {
  var engine = null;

  module('core/Load', {

    setup : function() {
      stop();

      gladius.create({
        debug : true
      }, function(instance) {
        engine = instance;
        start();
      });
    },
    teardown : function() {
      engine = null;
    }
  });

  asyncTest( 'invoke load with an empty list', function() {
    expect(3);

    function onprogress ( ) {
      // TD: no start here means tests will hang, so it's probably impossible
      // for the ok() below to ever fire, but just in case...
      ok( false, "progress should not be called for 100% completion");
    }

    function oncomplete ( result ) {
      start();
      ok( true, "empty load completed");
      deepEqual(result, {}, "result set is empty after empty load done");

      // TD: test that cache has not been modified
    }

    var result = engine.core.resource.load([], {
      oncomplete: oncomplete,
      onprogress: onprogress,
      cache: "myEmptyCache"});

    deepEqual(result, {}, "result set is empty after empty load initiated");
  });

  asyncTest( 'invoke load with a single uncached resource', function() {
    expect(6);

    var resourcePath = "assets/test-loadfile1.json";

    function onprogress ( ) {
      ok( false, "progress should not be called for only 1 file");
    }

    function oncomplete ( result ) {
      ok( true, "single uncached load completed");
      ok( result.hasOwnProperty(resourcePath),
          "result set has correct URL property");

      deepEqual(result[resourcePath], {},
        "result set contains correct data");

      equal( Object.keys(result).length, 1, "result set is right size");

      start();
      // TD: test that cache has not been modified
    }

    var resourceToLoad = {
      type: "engine.core.resource.json",
      source: resourcePath,
      onsuccess: function( result ) {
        deepEqual(result, {}, "empty JSON object should have been loaded");
      },
      onfailure: function( error ) {
        ok(false, "failed to load minimal JSON file: " + error);
      }
    };

    var result = engine.core.resource.load([resourceToLoad], {
      oncomplete: oncomplete,
      onprogress: onprogress,
      cache: "myEmptyCache"});

    deepEqual(result, {}, "result set is empty after single uncached load started");
  });

  asyncTest( 'invoke load with a single non-existent resource', function() {
    expect(4);

    var resourcePath = "no-such-url-exists";

    function onprogress ( ) {
      ok( false, "progress should not be called for only 1 file");
    }

    function oncomplete ( result ) {
      // XXX should we have another callback or arg to signal that
      // something went wrong?
      ok( true, "single non-existent load completed");
      equal( Object.keys(result).length, 0, "result set is empty");

      start();
      // TD: test that cache has been appropriately modified
    }

    var resourceToLoad = {
      type: "engine.core.resource.json",
      source: resourcePath,
      onsuccess: function( result ) {
        ok(false, "non-existent file should not have loaded successfully");
      },
      onfailure: function( error ) {
        ok(true, "non-existent file failed to load: " + error);
      }
    };

    var result = engine.core.resource.load([resourceToLoad], {
      oncomplete: oncomplete,
      onprogress: onprogress,
      cache: "myEmptyCache"});

    deepEqual(result, {}, "result set is empty after non-existent load started");
  });

  function makeResourceInfo(path) {
    var r = {
      type : "engine.core.resource.json",
      source : path,
      onsuccess : function(result) {
        deepEqual(result, {}, "empty JSON object should have been loaded");
      },
      onfailure : function(error) {
        ok(false, "failed to load minimal JSON file: " + error);
      }
    };

    return r;
  }

  asyncTest( 'load three uncached resource', function() {
    expect(12);

    var resourcePath = "assets/test-loadfile1.json";
    var resourcePath2 = "assets/test-loadfile2.json";
    var resourcePath3 = "assets/test-loadfile3.json";

    function onprogress ( ) {
      // TD (dmose): I'm not convinced that this API is very useful.  The
      // only simple granularity we can offer is calling back after each
      // file loads, and that progress updating could just be done on the
      // onsuccess/onfailure handler for each file.  I'd like to talk to
      // bzbarsky, biesi, or someone else with experience with the gecko
      // webprogress stuff.  Or, even more ideally, a UX person.  Would
      // also be interesting to chat with experienced game devs here.

      // we need to either make a passing a test or kill this API
      // before landing on the develop branch
    }

    function oncomplete ( result ) {
      ok( true, "three uncached loads completed");
      equal( Object.keys(result).length, 3, "result set is right size" );

      var resources = [resourcePath, resourcePath2, resourcePath3];
      for ( var i = 0; i < resources.length; i++ ) {
        ok( result.hasOwnProperty(resources[i]),
          "result set has expected URL property " + resources[i] );
        deepEqual(result[resources[i]], {},
          "result set contains correct data for " + resources[i] );
      }

      start();
      // TD: test that cache has been appropriately modified
    }

    var resourcesToLoad = [
      makeResourceInfo(resourcePath),
      makeResourceInfo(resourcePath2),
      makeResourceInfo(resourcePath3)
    ];

    var result = engine.core.resource.load(resourcesToLoad, {
      oncomplete: oncomplete,
      onprogress: onprogress,
      cache: "myEmptyCache"});

    deepEqual(result, {}, "result set is empty after single uncached load started");
  });

  // TD: test group load with some failing & some succeeding loads

  // TD: test constructor type handling (with mesh & script loads?)

  // TD: test what happens when itemsToLoad contains dups &
  // non-canonicalized dups

  // TD: test that passing in various edge cases and null for options
  // behaves appropriately

  // TD: test what happens when itemsToLoad is not an array.  duck-type as
  // single object to load?

  // TD: ensure that we test that result is not populated before one of
  // onprogress or oncomplete is called; refactor regular resources to
  // behave this way?

  // TD: progress should not be called at 100% complete; get rid of onprogress
  // ok()

}());
<|endoftext|>


<commit_before>const chai = require('chai');
const expect = chai.expect;
const sinon  = require('sinon');

const SuperRepo = require('../lib/index.js');

describe('Data Sync', () => {
    var clock;

    let repository;
    const TIMEFRAME = 60 * 1000; // 1 min
    let networkRequestsCount;

    beforeEach(() => {
        clock = sinon.useFakeTimers();
        networkRequestsCount = 0;

        repository = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: TIMEFRAME,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve({ whatever: true }));
            }
        });
    });
    afterEach(() => {
        clock.restore();
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is outdated, therefore, the process should start with a network request. ', done => {
        expect(networkRequestsCount).to.equal(0);

        repository.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME - 1);
            expect(networkRequestsCount).to.equal(1);

            clock.tick(1);
            expect(networkRequestsCount).to.equal(2);

            clock.tick(TIMEFRAME);
            expect(networkRequestsCount).to.equal(3);

            clock.tick(5 * TIMEFRAME);
            expect(networkRequestsCount).to.equal(8);
        }).then(done, done);
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is NOT outdated, therefore, the process should NOT start with a network request. Case: there is NO delay between getting the data and initiating the sync process.', done => {
        repository.getData().then(() => {

            expect(networkRequestsCount).to.equal(1);

            repository.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(1);

                clock.tick(TIMEFRAME - 1);

                expect(networkRequestsCount).to.equal(1);

                clock.tick(1);
                expect(networkRequestsCount).to.equal(2);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(3);

                clock.tick(10 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(13);
            }).then(done, done);

        });
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is NOT outdated, therefore, the process should NOT start with a network request. Case: there is delay between getting the data and initiating the sync process.', done => {
        repository.getData().then(() => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME - 1000);

            repository.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(1);

                clock.tick(1000);
                expect(networkRequestsCount).to.equal(2);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(3);

                clock.tick(100 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(103);
            }).then(done, done);
        });
    });

    it('Should stop the background data sync process.', done => {
        repository.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME);
            expect(networkRequestsCount).to.equal(2);

            repository.destroySyncer();

            clock.tick(100 * TIMEFRAME);
            expect(networkRequestsCount).to.equal(2);

            repository.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(3);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(4);

                repository.destroySyncer();

                clock.tick(100 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(4);
            }).then(done, done);
        });
    });

    it('Should NOT initiate a background data sync process faster than 1 second', done => {
        let networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: 500,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve({ whatever: true }));
            }
        });

        repo.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(500);
            expect(networkRequestsCount).to.equal(1);

            clock.tick(500);
            expect(networkRequestsCount).to.equal(2);

            clock.tick(1000);
            expect(networkRequestsCount).to.equal(3);

            clock.tick(10 * 1000);
            expect(networkRequestsCount).to.equal(13);
        }).then(done, done);
    });
});
<commit_msg>Add: test edge cases when outOfDateAfter is less than 1s<commit_after>const chai = require('chai');
const expect = chai.expect;
const sinon  = require('sinon');

const SuperRepo = require('../lib/index.js');

describe('Data Sync', () => {
    var clock;

    let repository;
    const TIMEFRAME = 60 * 1000; // 1 min
    let networkRequestsCount;

    beforeEach(() => {
        clock = sinon.useFakeTimers();
        networkRequestsCount = 0;

        repository = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: TIMEFRAME,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve({ whatever: true }));
            }
        });
    });
    afterEach(() => {
        clock.restore();
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is outdated, therefore, the process should start with a network request. ', done => {
        expect(networkRequestsCount).to.equal(0);

        repository.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME - 1);
            expect(networkRequestsCount).to.equal(1);

            clock.tick(1);
            expect(networkRequestsCount).to.equal(2);

            clock.tick(TIMEFRAME);
            expect(networkRequestsCount).to.equal(3);

            clock.tick(5 * TIMEFRAME);
            expect(networkRequestsCount).to.equal(8);
        }).then(done, done);
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is NOT outdated, therefore, the process should NOT start with a network request. Case: there is NO delay between getting the data and initiating the sync process.', done => {
        repository.getData().then(() => {

            expect(networkRequestsCount).to.equal(1);

            repository.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(1);

                clock.tick(TIMEFRAME - 1);

                expect(networkRequestsCount).to.equal(1);

                clock.tick(1);
                expect(networkRequestsCount).to.equal(2);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(3);

                clock.tick(10 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(13);
            }).then(done, done);

        });
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is NOT outdated, therefore, the process should NOT start with a network request. Case: there is delay between getting the data and initiating the sync process.', done => {
        repository.getData().then(() => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME - 1000);

            repository.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(1);

                clock.tick(1000);
                expect(networkRequestsCount).to.equal(2);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(3);

                clock.tick(100 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(103);
            }).then(done, done);
        });
    });

    it('Should stop the background data sync process.', done => {
        repository.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME);
            expect(networkRequestsCount).to.equal(2);

            repository.destroySyncer();

            clock.tick(100 * TIMEFRAME);
            expect(networkRequestsCount).to.equal(2);

            repository.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(3);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(4);

                repository.destroySyncer();

                clock.tick(100 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(4);
            }).then(done, done);
        });
    });

    it('Should NOT initiate a background data sync process faster than 1 second when `outOfDateAfter` option is less than 1 second', done => {
        let networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: 500,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve({ whatever: true }));
            }
        });

        repo.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(500);
            expect(networkRequestsCount).to.equal(1);

            clock.tick(500);
            expect(networkRequestsCount).to.equal(2);

            clock.tick(1000);
            expect(networkRequestsCount).to.equal(3);

            clock.tick(10 * 1000);
            expect(networkRequestsCount).to.equal(13);
        }).then(done, done);
    });

    it('Should initiate a background data sync process on every 1 second when `outOfDateAfter` option is not defined', done => {
        let networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve({ whatever: true }));
            }
        });

        repo.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(500);
            expect(networkRequestsCount).to.equal(1);

            clock.tick(500);
            expect(networkRequestsCount).to.equal(2);

            clock.tick(1000);
            expect(networkRequestsCount).to.equal(3);

            clock.tick(10 * 1000);
            expect(networkRequestsCount).to.equal(13);
        }).then(done, done);
    });

    it('Should initiate a background data sync process on every 1 second when `outOfDateAfter` option is set to -1', done => {
        let networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve({ whatever: true }));
            }
        });

        repo.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(500);
            expect(networkRequestsCount).to.equal(1);

            clock.tick(500);
            expect(networkRequestsCount).to.equal(2);

            clock.tick(1000);
            expect(networkRequestsCount).to.equal(3);

            clock.tick(10 * 1000);
            expect(networkRequestsCount).to.equal(13);
        }).then(done, done);
    });

});
<|endoftext|>


<commit_before>/* global describe, it, xit */
/* jslint node: true, esnext: true */

"use strict";

const fs = require('fs');
const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();

const endpointImpl = require('../lib/endpointImplementation');

describe('endpoint definition', function () {

	describe('name', function () {
		it('given name present', function () {
			const endpoint = endpointImpl.createEndpoint('e1', {});
			assert(endpoint.name === 'e1');
		});
	});

	describe('with implementation function', function () {
		function myImplementation() {}

		describe('as object', function () {
			it('implementation present', function () {
				const endpoint = endpointImpl.createEndpoint('e1', {
					implementation: myImplementation
				});
				assert(endpoint.implementation === myImplementation);
			});
		});
		describe('as direct function', function () {
			it('implementation present', function () {
				const endpoint = endpointImpl.createEndpoint('e1', myImplementation);
				assert(endpoint.implementation === myImplementation);
			});
		});
	});

	describe('with target', function () {
		describe('as object', function () {
			it('target present', function () {
				const endpoint = endpointImpl.createEndpoint('e1', {
					target: "myTarget"
				});
				assert(endpoint.target === 'myTarget');
			});
		});
		describe('as direct string', function () {
			it('target present', function () {
				const endpoint = endpointImpl.createEndpoint('e1', "myTarget");
				assert(endpoint.target === 'myTarget');
			});
		});
	});

	describe('should have correct direction', function () {
		it('for in', function () {
			const endpoint = endpointImpl.createEndpoint('e1', {
				direction: 'in'
			});
			assert(endpoint.direction === 'in');
			assert(endpoint.isIn, "isIn when in");
		});

		it('for out', function () {
			const endpoint = endpointImpl.createEndpoint('e1', {
				direction: 'out'
			});
			assert(endpoint.direction === 'out');
			assert(endpoint.isOut, "isOut when out");
		});

		it('for inout', function () {
			const endpoint = endpointImpl.createEndpoint('e1', {
				direction: 'inout'
			});
			assert(endpoint.direction === 'inout');
			assert(endpoint.isOut, "isOut when inout");
			assert(endpoint.isIn, "isIn when inout");
		});
	});

	describe('initialize', function () {
		const endpoint = endpointImpl.createEndpoint('e1', {
			direction: 'in',
			implementation: function* () {
				yield {
					info: {
						name: "<" + this.name + ">"
					},
					stream: "body"
				};
			}
		});

		let requests = endpoint.initialize({}, {
			name: "myStep"
		});

		let number = 0;
		for (let request of requests) {
			number++;
			it('should have info from endpoint coming from <this>', function () {
				assert(request.info.name === '<e1>');
			});
		}

		it('should be exatly one request', function () {
			assert(number === 1, "got one request");
		});
	});

});
<commit_msg>test(endpoint): direction with given meta object<commit_after>/* global describe, it, xit */
/* jslint node: true, esnext: true */

"use strict";

const fs = require('fs');
const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();

const endpointImpl = require('../lib/endpointImplementation');

describe('endpoint definition', function () {

  describe('name', function () {
    it('given name present', function () {
      const endpoint = endpointImpl.createEndpoint('e1', {});
      assert(endpoint.name === 'e1');
    });
  });

  describe('with implementation function', function () {
    function myImplementation() {}

    describe('as object', function () {
      it('implementation present', function () {
        const endpoint = endpointImpl.createEndpoint('e1', {
          implementation: myImplementation
        });
        assert(endpoint.implementation === myImplementation);
      });
    });
    describe('as direct function', function () {
      it('implementation present', function () {
        const endpoint = endpointImpl.createEndpoint('e1', myImplementation);
        assert(endpoint.implementation === myImplementation);
      });
    });
  });

  describe('with target', function () {
    describe('as object', function () {
      it('target present', function () {
        const endpoint = endpointImpl.createEndpoint('e1', {
          target: "myTarget"
        });
        assert(endpoint.target === 'myTarget');
      });
    });
    describe('as direct string', function () {
      it('target present', function () {
        const endpoint = endpointImpl.createEndpoint('e1', "myTarget");
        assert(endpoint.target === 'myTarget');
      });
    });
  });

  describe('should have correct direction', function () {
    it('for in', function () {
      const endpoint = endpointImpl.createEndpoint('e1', {
        direction: 'in'
      });
      assert(endpoint.direction === 'in');
      assert(endpoint.isIn, "isIn when in");
    });

    it('for out', function () {
      const endpoint = endpointImpl.createEndpoint('e1', {
        direction: 'out'
      });
      assert(endpoint.direction === 'out');
      assert(endpoint.isOut, "isOut when out");
    });

    it('for inout', function () {
      const endpoint = endpointImpl.createEndpoint('e1', {
        direction: 'inout'
      });
      assert(endpoint.direction === 'inout');
      assert(endpoint.isOut, "isOut when inout");
      assert(endpoint.isIn, "isIn when inout");
    });

    it('also with meta object', function () {
      const endpoint = endpointImpl.createEndpoint('e1', {
        target: 'file:/tmp/a',
        direction: 'out'
      }, endpointImpl.implementations.file);
      assert(endpoint.direction === 'out');
      assert(endpoint.isOut, "isOut when out");
    });
  });

  describe('initialize', function () {
    const endpoint = endpointImpl.createEndpoint('e1', {
      direction: 'in',
      implementation: function* () {
        yield {
          info: {
            name: "<" + this.name + ">"
          },
          stream: "body"
        };
      }
    });

    let requests = endpoint.initialize({}, {
      name: "myStep"
    });

    let number = 0;
    for (let request of requests) {
      number++;
      it('should have info from endpoint coming from <this>', function () {
        assert(request.info.name === '<e1>');
      });
    }

    it('should be exatly one request', function () {
      assert(number === 1, "got one request");
    });
  });

});
<|endoftext|>


<commit_before>/*
 * errs-test.js: Tests for the `errs` module.
 *
 * (C) 2012, Nodejitsu Inc.
 * MIT LICENSE
 *
 */

var assert = require('assert'),
    vows = require('vows'),
    errs = require('../lib/errs'),
    fixtures = require('./fixtures'),
    macros = require('./macros');

var opts = [{
  foo: 'bar',
  status: 404,
  whatever: 'some other property'
}, {
  testing: true,
  'some-string': 'is-a-value',
  message: 'This is an error. There are many like it.'
}, {
  'a-function': 'that returns an object',
  should: true,
  have: 4,
  properties: 'yes'
}]

vows.describe('errs').addBatch({
  "Using errs module": {
    "the register() method": {
      "should register the prototype": function () {
        errs.register('named', fixtures.NamedError);
        assert.equal(errs.registered['named'], fixtures.NamedError);
      }
    },
    "the create() method with": {
      "a string": macros.create.string('An error as a string'),
      "no parameters": macros.create.string('An error as a string'),
      "an object": {
        "that has no message": macros.create.object(opts[0]),
        "that has a message": macros.create.object(opts[1])
      },
      "an error": macros.create.err(new Error('An instance of an error')),
      "a function": macros.create.fn(function () {
        return opts[2];
      }),
      "a registered type": {
        "that exists": macros.create.registered('named', fixtures.NamedError, opts[1]),
        "that doesnt exist": macros.create.registered('bad', null, opts[1])
      }
    },
    "the handle() method": {
      "with a callback": {
        topic: function () {
          var err = this.err = errs.create('Some async error');
          errs.handle(err, this.callback.bind(this, null));
        },
        "should invoke the callback with the error": function (_, err) {
          assert.equal(err, this.err);
        }
      },
      "with no callback": {
        topic: function () {
          var err = this.err = errs.create('Some emitted error'),
              emitter = errs.handle(err);

          emitter.once('error', this.callback.bind(this, null))
        },
        "should invoke the callback with the error": function (_, err) {
          assert.equal(err, this.err);
        }
      }
    }
  }
}).addBatch({
  "Using errs module": {
    "the unregister() method": {
      "should unregister the prototype": function () {
        errs.unregister('named');
        assert.isTrue(!errs.registered['named']);
      }
    }
  }
}).export(module);
<commit_msg>Add test for `.register()` when used without a type.<commit_after>/*
 * errs-test.js: Tests for the `errs` module.
 *
 * (C) 2012, Nodejitsu Inc.
 * MIT LICENSE
 *
 */

var assert = require('assert'),
    vows = require('vows'),
    errs = require('../lib/errs'),
    fixtures = require('./fixtures'),
    macros = require('./macros');

var opts = [{
  foo: 'bar',
  status: 404,
  whatever: 'some other property'
}, {
  testing: true,
  'some-string': 'is-a-value',
  message: 'This is an error. There are many like it.'
}, {
  'a-function': 'that returns an object',
  should: true,
  have: 4,
  properties: 'yes'
}]

vows.describe('errs').addBatch({
  "Using errs module": {
    "the register() method": {
      "should register the prototype": function () {
        errs.register('named', fixtures.NamedError);
        assert.equal(errs.registered['named'], fixtures.NamedError);
      },
      "should register an error without providing its name": function () {
        errs.register(fixtures.AnError);
        assert.equal(errs.registered['anerror'], fixtures.AnError);
      }
    },
    "the create() method with": {
      "a string": macros.create.string('An error as a string'),
      "no parameters": macros.create.string('An error as a string'),
      "an object": {
        "that has no message": macros.create.object(opts[0]),
        "that has a message": macros.create.object(opts[1])
      },
      "an error": macros.create.err(new Error('An instance of an error')),
      "a function": macros.create.fn(function () {
        return opts[2];
      }),
      "a registered type": {
        "that exists": macros.create.registered('named', fixtures.NamedError, opts[1]),
        "that doesnt exist": macros.create.registered('bad', null, opts[1])
      }
    },
    "the handle() method": {
      "with a callback": {
        topic: function () {
          var err = this.err = errs.create('Some async error');
          errs.handle(err, this.callback.bind(this, null));
        },
        "should invoke the callback with the error": function (_, err) {
          assert.equal(err, this.err);
        }
      },
      "with no callback": {
        topic: function () {
          var err = this.err = errs.create('Some emitted error'),
              emitter = errs.handle(err);

          emitter.once('error', this.callback.bind(this, null))
        },
        "should invoke the callback with the error": function (_, err) {
          assert.equal(err, this.err);
        }
      }
    }
  }
}).addBatch({
  "Using errs module": {
    "the unregister() method": {
      "should unregister the prototype": function () {
        errs.unregister('named');
        assert.isTrue(!errs.registered['named']);
      }
    }
  }
}).export(module);
<|endoftext|>


<commit_before>var EndoxaGraph = require('../module'),
  chai       = require('chai'),
  expect     = chai.expect;

describe('EndoxaGraph', function() {
  it('exists', function() {
    expect(EndoxaGraph).to.be.an('object');
  });
});
<commit_msg>use assert instead of expect.<commit_after>var graph = require('../module'),
  chai       = require('chai'),
  assert     = chai.assert;

describe('EndoxaGraph', function() {
  it('exists', function() {
    assert.isObject(graph)
  });
});
<|endoftext|>


<commit_before>const chai = require('chai'),
			expect = chai.expect
			find = require('../utils/find');

let testData = require('./mock/search.json');

describe('find', function () {

	describe('player', function () {

		it('should find and return the correct player when given a player ID', function () {
			// Looking for Eric Young Jr. of the New York Yankees - 458913
			let requestedPlayer = find.player(testData, '458913');
			expect(requestedPlayer).to.have.property('player_id', '458913');
		});
		it('should return the correct player when given a team abbreviation', function () {
			// Looking for Chris Young of the Kansas City Royals - 432934
			let requestedPlayer = find.player(testData, 'KC');
			expect(requestedPlayer).to.have.property('player_id', '432934');
		});

		describe('error handling', function () {
			it('should return missing key error if no key is given', function() {
				let requestedPlayer = find.player(testData, '');
				expect(requestedPlayer).to.be.an('error', 'find.player wasn\'t given a key');
			});
			it('should return an invalid key type error if an invalid key is given', function () {
				let requestedPlayer = find.player(testData, 123456);
				expect(requestedPlayer).to.be.an('error', 'find.player expected key to be a string, but was given a number.')
			});
			it('should return an error if no matching key is found', function () {
				let requestedPlayer = find.player(testData, '123456');
				expect(requestedPlayer).to.be.an('error', 'find.player could not find a player with a matching key.');
			});
		});

	});

	describe('teamId', function () {
		// Find team ID of New York Mets - 121
		it ('should find and return the correct team ID when given a team abbreviation', function () {
			let teamId = find.teamId('nym');
			expect(teamId).to.equal('121');
		});
		it ('should find and return the correct team ID when given a team name', function () {
			let teamId = find.teamId('New York Mets')
			expect(teamId).to.equal('121');
		});
		it ('should find and return the correct team ID when given a team ID', function () {
			let teamId = find.teamId('121');
			expect(teamId).to.equal('121');
		});
	});

});

<commit_msg>test error handling in find<commit_after>const chai = require('chai'),
			expect = chai.expect
			find = require('../utils/find');

let testData = require('./mock/search.json');

describe('find', function () {

	describe('player', function () {

		it('should find and return the correct player when given a player ID', function () {
			// Looking for Eric Young Jr. of the New York Yankees - 458913
			let requestedPlayer = find.player(testData, '458913');
			expect(requestedPlayer).to.have.property('player_id', '458913');
		});
		it('should return the correct player when given a team abbreviation', function () {
			// Looking for Chris Young of the Kansas City Royals - 432934
			let requestedPlayer = find.player(testData, 'KC');
			expect(requestedPlayer).to.have.property('player_id', '432934');
		});

		describe('error handling', function () {
			it('should return missing key error if no key is given', function() {
				let requestedPlayer = find.player(testData, '');
				expect(requestedPlayer).to.be.an('error', 'find.player wasn\'t given a key');
			});
			it('should return an invalid key type error if an invalid key is given', function () {
				let requestedPlayer = find.player(testData, 123456);
				expect(requestedPlayer).to.be.an('error', 'find.player expected key to be a string, but was given a number.')
			});
			it('should return an error if no matching key is found', function () {
				let requestedPlayer = find.player(testData, '123456');
				expect(requestedPlayer).to.be.an('error', 'find.player could not find a player with a matching key.');
			});
		});

	});

	describe('teamId', function () {
		// Find team ID of New York Mets - 121
		it ('should find and return the correct team ID when given a team abbreviation', function () {
			let teamId = find.teamId('nym');
			expect(teamId).to.equal('121');
		});
		it ('should find and return the correct team ID when given a team name', function () {
			let teamId = find.teamId('New York Mets')
			expect(teamId).to.equal('121');
		});
		it ('should find and return the correct team ID when given a team ID', function () {
			let teamId = find.teamId('121');
			expect(teamId).to.equal('121');
		});
		it('should return undefined if no team ID can be found', function () {
				let requestedPlayer = find.teamId('inv');
				expect(requestedPlayer).to.be.undefined;
			});
		describe('error handling', function () {
			it('should return missing key error if no key is given', function () {
				let requestedPlayer = find.teamId('');
				expect(requestedPlayer).to.be.an('error', 'find.teamId wasn\'t given a key');
			});
			it('should return an invalid key type error if an invalid key is given', function () {
				let requestedPlayer = find.teamId(123456);
				expect(requestedPlayer).to.be.an('error', 'find.teamId expected key to be a string, but was given a number.')
			});
		});
	});

});

<|endoftext|>


<commit_before>
var app = require('../fixtures/bootstrap');

var vows = require('vows'),
    assert = require('assert'),
    EventEmitter = require('events').EventEmitter;

var onBeforeCreateCheck;

vows.describe('Message Queue (middleware)').addBatch({

  '': {

    topic: function() {

      var promise = new EventEmitter();

      app.use('mq', {
        server: 'amqp://',
        queues: ['my_queue', 'another_queue'],
        exchanges: {
          alpha: {type: 'fanout'},
          beta: {type: 'topic'}
        },
        onBeforeCreate: function(multi) {
          onBeforeCreateCheck =
            (Object.keys(app.mq.queues).length === 0)         // There should be no queues set
            && (Object.keys(app.mq.exchanges).length === 0)   // There should be no exchanges set
            && (multi.constructor.name == 'Multi')            // The parameter should contain a multi instance
            && (multi.queue instanceof Function && multi.exchange instanceof Function);   // Is the correct multi
        },
        onInitialize: function(err, queues, exchanges) {
          app.log("MQ Initialized...");
          app.mq.queue('', function(err, q) {
            var counter = 0;
            q.bind(exchanges.alpha, '');
            q.subscribe(function(msg) {
              promise.emit('success', msg.data.toString('utf8'));
            });
            var intID = setInterval(function() {
              counter++;
              exchanges.alpha.publish('', "Hello World! " + counter);
              clearTimeout(intID);
            }, 500);
          });
        }
      });

      return promise;

    },

    'Passes Integrity Checks': function() {
      assert.equal(app.mq.constructor.name, 'MessageQueue');
      assert.equal(app.mq.connection.constructor.name, 'Connection');
    },

    'Properly sets queues': function(msg) {
      var queues = app.mq.queues;
      assert.isTrue(typeof queues == 'object');
      assert.deepEqual(Object.keys(queues), ['my_queue', 'another_queue']);
      assert.isTrue(queues.my_queue.name == 'my_queue');
      assert.isTrue(queues.my_queue.constructor.name == 'Queue');
      assert.isTrue(queues.another_queue.name == 'another_queue');
      assert.isTrue(queues.another_queue.constructor.name == 'Queue');
    },

    'Properly sets random queues': function() {
      assert.isArray(app.mq.randomQueues);
      assert.isTrue(app.mq.randomQueues.length == 1);
      assert.equal(app.mq.randomQueues[0].constructor.name, 'Queue');
    },

    'Runs the onBeforeCreate callback': function() {
      assert.isTrue(onBeforeCreateCheck);
    },

    'Properly configures exchanges': function(msg) {
      var exchanges = app.mq.exchanges;
      assert.isTrue(typeof exchanges == 'object');
      assert.deepEqual(Object.keys(exchanges), ['alpha', 'beta']);
      assert.isTrue(exchanges.alpha.name == 'alpha');
      assert.isTrue(exchanges.alpha.constructor.name == 'Exchange');
      assert.isTrue(exchanges.alpha.options.type == 'fanout');
      assert.isTrue(exchanges.beta.name == 'beta');
      assert.isTrue(exchanges.beta.constructor.name == 'Exchange');
      assert.isTrue(exchanges.beta.options.type == 'topic');
    },

    'Messages are sent/received properly': function(msg) {
      assert.strictEqual(msg, 'Hello World! 1');
    }

  }

}).export(module);
<commit_msg>Modified travis ci rabbitmq connection uri<commit_after>
var app = require('../fixtures/bootstrap');

var vows = require('vows'),
    assert = require('assert'),
    EventEmitter = require('events').EventEmitter;

var onBeforeCreateCheck;

vows.describe('Message Queue (middleware)').addBatch({

  '': {

    topic: function() {

      var promise = new EventEmitter();

      app.use('mq', {
        server: (app.environment == 'travis') ? 'amqp://guest:guest@127.0.0.1:5672/' : 'amqp://',
        queues: ['my_queue', 'another_queue'],
        exchanges: {
          alpha: {type: 'fanout'},
          beta: {type: 'topic'}
        },
        onBeforeCreate: function(multi) {
          onBeforeCreateCheck =
            (Object.keys(app.mq.queues).length === 0)         // There should be no queues set
            && (Object.keys(app.mq.exchanges).length === 0)   // There should be no exchanges set
            && (multi.constructor.name == 'Multi')            // The parameter should contain a multi instance
            && (multi.queue instanceof Function && multi.exchange instanceof Function);   // Is the correct multi
        },
        onInitialize: function(err, queues, exchanges) {
          app.log("MQ Initialized...");
          app.mq.queue('', function(err, q) {
            var counter = 0;
            q.bind(exchanges.alpha, '');
            q.subscribe(function(msg) {
              promise.emit('success', msg.data.toString('utf8'));
            });
            var intID = setInterval(function() {
              counter++;
              exchanges.alpha.publish('', "Hello World! " + counter);
              clearTimeout(intID);
            }, 500);
          });
        }
      });

      return promise;

    },

    'Passes Integrity Checks': function() {
      assert.equal(app.mq.constructor.name, 'MessageQueue');
      assert.equal(app.mq.connection.constructor.name, 'Connection');
    },

    'Properly sets queues': function(msg) {
      var queues = app.mq.queues;
      assert.isTrue(typeof queues == 'object');
      assert.deepEqual(Object.keys(queues), ['my_queue', 'another_queue']);
      assert.isTrue(queues.my_queue.name == 'my_queue');
      assert.isTrue(queues.my_queue.constructor.name == 'Queue');
      assert.isTrue(queues.another_queue.name == 'another_queue');
      assert.isTrue(queues.another_queue.constructor.name == 'Queue');
    },

    'Properly sets random queues': function() {
      assert.isArray(app.mq.randomQueues);
      assert.isTrue(app.mq.randomQueues.length == 1);
      assert.equal(app.mq.randomQueues[0].constructor.name, 'Queue');
    },

    'Runs the onBeforeCreate callback': function() {
      assert.isTrue(onBeforeCreateCheck);
    },

    'Properly configures exchanges': function(msg) {
      var exchanges = app.mq.exchanges;
      assert.isTrue(typeof exchanges == 'object');
      assert.deepEqual(Object.keys(exchanges), ['alpha', 'beta']);
      assert.isTrue(exchanges.alpha.name == 'alpha');
      assert.isTrue(exchanges.alpha.constructor.name == 'Exchange');
      assert.isTrue(exchanges.alpha.options.type == 'fanout');
      assert.isTrue(exchanges.beta.name == 'beta');
      assert.isTrue(exchanges.beta.constructor.name == 'Exchange');
      assert.isTrue(exchanges.beta.options.type == 'topic');
    },

    'Messages are sent/received properly': function(msg) {
      assert.strictEqual(msg, 'Hello World! 1');
    }

  }

}).export(module);
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// for license information please see license.txt

// constructor: parent, label, method, args
frappe.ui.Tree = Class.extend({
	init: function(args) {
		$.extend(this, args);
		this.nodes = {};
		this.wrapper = $('
').appendTo(this.parent);
		this.rootnode = new frappe.ui.TreeNode({
			tree: this,
			parent: this.wrapper,
			label: this.label,
			parent_label: null,
			expandable: true,
			is_root: true,
			data: {
				value: this.label,
				parent: this.label,
				expandable: true
			}
		});
		this.rootnode.toggle();
	},
	refresh: function() {
		this.selected_node.reload_parent();
	},
	get_selected_node: function() {
		return this.selected_node;
	},
	toggle: function() {
		this.get_selected_node().toggle();
	}
});

frappe.ui.TreeNode = Class.extend({
	init: function(args) {
		$.extend(this, args);
		this.loaded = false;
		this.expanded = false;
		this.tree.nodes[this.label] = this;
		if(this.parent_label)
			this.parent_node = this.tree.nodes[this.parent_label];

		this.make();
		this.setup_drag_drop();

		if(this.tree.onrender) {
			this.tree.onrender(this);
		}
	},
	make: function() {
		var me = this;
		this.tree_link = $('')
			.click(function(event) {
				me.tree.selected_node = me;
				me.tree.wrapper.find(".tree-link.active").removeClass("active");
				me.tree_link.addClass("active");
				if(me.tree.toolbar) {
					me.show_toolbar();
				}
				if(me.tree.click) {
					me.tree.click(this);
				}
				if(me.tree.onclick) {
					me.tree.onclick(me);
				}
			})
			.data('label', this.label)
			.data('node', this)
			.appendTo(this.parent);

		this.$ul = $('
')
			.toggle(false).appendTo(this.parent);

		this.make_icon();

	},
	make_icon: function() {
		// label with icon
		var me= this;
		var icon_html = '';
		if(this.expandable) {
			icon_html = '';
		}
		$(icon_html + ' ' + this.get_label() + "").
			appendTo(this.tree_link);

		this.tree_link.find('i').click(function() {
			setTimeout(function() { me.toolbar.find(".btn-expand").click(); }, 100);
		});

		this.tree_link.find('a').click(function() {
			if(!me.expanded) setTimeout(function() { me.toolbar.find(".btn-expand").click(); }, 100);
		});
	},
	get_label: function() {
		if(this.tree.get_label) {
			return this.tree.get_label(this);
		}
		if (this.title && this.title != this.label) {
			return __(this.title) + ` <span class='text-muted'>(${this.label})</span>`;
		} else {
			return __(this.title || this.label);
		}
	},
	toggle: function(callback) {
		if(this.expandable && this.tree.method && !this.loaded) {
			this.load(callback)
		} else {
			this.toggle_node(callback);
		}
	},
	show_toolbar: function() {
		if(this.tree.cur_toolbar)
			$(this.tree.cur_toolbar).toggle(false);

		if(!this.toolbar)
			this.make_toolbar();

		this.tree.cur_toolbar = this.toolbar;
		this.toolbar.toggle(true);
	},
	make_toolbar: function() {
		var me = this;
		this.toolbar = $('').insertAfter(this.tree_link);

		$.each(this.tree.toolbar, function(i, item) {
			if(item.toggle_btn) {
				item = {
					condition: function() { return me.expandable; },
					get_label: function() { return me.expanded ? __("Collapse") : __("Expand") },
					click:function(node, btn) {
						node.toggle(function() {
							$(btn).html(node.expanded ? __("Collapse") : __("Expand"));
						});
					},
					btnClass: "btn-expand hidden-xs"
				}
			}
			if(item.condition) {
				if(!item.condition(me)) return;
			}
			var label = item.get_label ? item.get_label() : item.label;
			var link = $("<button class='btn btn-default btn-xs'></button>")
				.html(label)
				.appendTo(me.toolbar)
				.click(function() { item.click(me, this); return false; });

			if(item.btnClass) link.addClass(item.btnClass);
		})

	},
	setup_drag_drop: function() {
		// experimental
		var me = this;
		if(this.tree.drop && this.parent_label) {
			this.$ul.droppable({
				hoverClass: "tree-hover",
				greedy: true,
				drop: function(event, ui) {
					event.preventDefault();
					var dragged_node = $(ui.draggable).find(".tree-link:first").data("node");
					var dropped_node = $(this).parent().find(".tree-link:first").data("node");
					me.tree.drop(dragged_node, dropped_node, $(ui.draggable), $(this));
					return false;
				}
			});
		}

	},
	addnode: function(data) {
		var $li = $('
');
		if(this.tree.drop) $li.draggable({revert:true});

		return new frappe.ui.TreeNode({
			tree: this.tree,
			parent: $li.appendTo(this.$ul),
			parent_label: this.label,
			label: data.value,
			title: data.title,
			expandable: data.expandable,
			data: data
		});
	},
	toggle_node: function(callback) {
		// expand children
		if(this.$ul) {
			if(this.$ul.children().length) {
				this.$ul.toggle(!this.expanded);
			}

			// open close icon
			this.tree_link.find('i').removeClass();
			if(!this.expanded) {
				this.tree_link.find('i').addClass('fa fa-fw fa-folder-open text-muted');
			} else {
				this.tree_link.find('i').addClass('fa fa-fw fa-folder text-muted');
			}
		}

		// select this link
		this.tree.wrapper.find('.selected')
			.removeClass('selected');
		this.tree_link.toggleClass('selected');
		this.expanded = !this.expanded;

		this.expanded ?
			this.parent.addClass('opened') :
			this.parent.removeClass('opened');
		if(callback) callback();
	},
	reload: function() {
		this.load();
	},
	reload_parent: function() {
		this.parent_node.load_all();
	},
	load_all: function(callback) {
		var  me = this;
		let args = $.extend({}, this.tree.args);

		args.parent = this.data.value;
		args.tree_method = this.tree.method;
		args.is_root = this.is_root;

		return frappe.call({
			method: 'frappe.desk.treeview.get_all_nodes',
			args: args,
			callback: function(r) {
				$.each(r.message, function(i, d) {
					me.render_expand_node(me.tree.nodes[d.parent], d.data);
				});
				if(callback) { callback(); }
			}
		});
	},
	load: function(callback) {
		var node = this;
		var args = $.extend(this.tree.args || {}, {
			parent: this.data.value
		});

		args.is_root = this.is_root;

		return frappe.call({
			method: this.tree.method,
			args: args,
			callback: function(r) {
				node.render_expand_node(node, r.message, callback);
			}
		})
	},
	render_expand_node: function(node, data, callback) {
		node.$ul.empty();
		if (data) {
			$.each(data, function(i, v) {
				var child_node = node.addnode(v);
				child_node.tree_link
					.data('node-data', v)
					.data('node', child_node);
			});
		}

		node.expanded = false;
		node.toggle_node(callback);
		node.loaded = true;
	},
})
<commit_msg>fix load all by Faris in tree master (#4543)<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// for license information please see license.txt

// constructor: parent, label, method, args
frappe.ui.Tree = Class.extend({
	init: function(args) {
		$.extend(this, args);
		this.nodes = {};
		this.wrapper = $('
').appendTo(this.parent);
		this.rootnode = new frappe.ui.TreeNode({
			tree: this,
			parent: this.wrapper,
			label: this.label,
			parent_label: null,
			expandable: true,
			is_root: true,
			data: {
				value: this.label,
				parent: this.label,
				expandable: true
			}
		});
		this.rootnode.toggle();
	},
	refresh: function() {
		this.selected_node.reload_parent();
	},
	get_selected_node: function() {
		return this.selected_node;
	},
	toggle: function() {
		this.get_selected_node().toggle();
	}
});

frappe.ui.TreeNode = Class.extend({
	init: function(args) {
		$.extend(this, args);
		this.loaded = false;
		this.expanded = false;
		this.tree.nodes[this.label] = this;
		if(this.parent_label)
			this.parent_node = this.tree.nodes[this.parent_label];

		this.make();
		this.setup_drag_drop();

		if(this.tree.onrender) {
			this.tree.onrender(this);
		}
	},
	make: function() {
		var me = this;
		this.tree_link = $('')
			.click(function(event) {
				me.tree.selected_node = me;
				me.tree.wrapper.find(".tree-link.active").removeClass("active");
				me.tree_link.addClass("active");
				if(me.tree.toolbar) {
					me.show_toolbar();
				}
				if(me.tree.click) {
					me.tree.click(this);
				}
				if(me.tree.onclick) {
					me.tree.onclick(me);
				}
			})
			.data('label', this.label)
			.data('node', this)
			.appendTo(this.parent);

		this.$ul = $('
')
			.toggle(false).appendTo(this.parent);

		this.make_icon();

	},
	make_icon: function() {
		// label with icon
		var me= this;
		var icon_html = '';
		if(this.expandable) {
			icon_html = '';
		}
		$(icon_html + ' ' + this.get_label() + "").
			appendTo(this.tree_link);

		this.tree_link.find('i').click(function() {
			setTimeout(function() { me.toolbar.find(".btn-expand").click(); }, 100);
		});

		this.tree_link.find('a').click(function() {
			if(!me.expanded) setTimeout(function() { me.toolbar.find(".btn-expand").click(); }, 100);
		});
	},
	get_label: function() {
		if(this.tree.get_label) {
			return this.tree.get_label(this);
		}
		if (this.title && this.title != this.label) {
			return __(this.title) + ` <span class='text-muted'>(${this.label})</span>`;
		} else {
			return __(this.title || this.label);
		}
	},
	toggle: function(callback) {
		if(this.expandable && this.tree.method && !this.loaded) {
			this.load(callback)
		} else {
			this.toggle_node(callback);
		}
	},
	show_toolbar: function() {
		if(this.tree.cur_toolbar)
			$(this.tree.cur_toolbar).toggle(false);

		if(!this.toolbar)
			this.make_toolbar();

		this.tree.cur_toolbar = this.toolbar;
		this.toolbar.toggle(true);
	},
	make_toolbar: function() {
		var me = this;
		this.toolbar = $('').insertAfter(this.tree_link);

		$.each(this.tree.toolbar, function(i, item) {
			if(item.toggle_btn) {
				item = {
					condition: function() { return me.expandable; },
					get_label: function() { return me.expanded ? __("Collapse") : __("Expand") },
					click:function(node, btn) {
						node.toggle(function() {
							$(btn).html(node.expanded ? __("Collapse") : __("Expand"));
						});
					},
					btnClass: "btn-expand hidden-xs"
				}
			}
			if(item.condition) {
				if(!item.condition(me)) return;
			}
			var label = item.get_label ? item.get_label() : item.label;
			var link = $("<button class='btn btn-default btn-xs'></button>")
				.html(label)
				.appendTo(me.toolbar)
				.click(function() { item.click(me, this); return false; });

			if(item.btnClass) link.addClass(item.btnClass);
		})

	},
	setup_drag_drop: function() {
		// experimental
		var me = this;
		if(this.tree.drop && this.parent_label) {
			this.$ul.droppable({
				hoverClass: "tree-hover",
				greedy: true,
				drop: function(event, ui) {
					event.preventDefault();
					var dragged_node = $(ui.draggable).find(".tree-link:first").data("node");
					var dropped_node = $(this).parent().find(".tree-link:first").data("node");
					me.tree.drop(dragged_node, dropped_node, $(ui.draggable), $(this));
					return false;
				}
			});
		}

	},
	addnode: function(data) {
		var $li = $('
');
		if(this.tree.drop) $li.draggable({revert:true});

		return new frappe.ui.TreeNode({
			tree: this.tree,
			parent: $li.appendTo(this.$ul),
			parent_label: this.label,
			label: data.value,
			title: data.title,
			expandable: data.expandable,
			data: data
		});
	},
	toggle_node: function(callback) {
		// expand children
		if(this.$ul) {
			if(this.$ul.children().length) {
				this.$ul.toggle(!this.expanded);
			}

			// open close icon
			this.tree_link.find('i').removeClass();
			if(!this.expanded) {
				this.tree_link.find('i').addClass('fa fa-fw fa-folder-open text-muted');
			} else {
				this.tree_link.find('i').addClass('fa fa-fw fa-folder text-muted');
			}
		}

		// select this link
		this.tree.wrapper.find('.selected')
			.removeClass('selected');
		this.tree_link.toggleClass('selected');
		this.expanded = !this.expanded;

		this.expanded ?
			this.parent.addClass('opened') :
			this.parent.removeClass('opened');
		if(callback) callback();
	},
	reload: function() {
		this.load();
	},
	reload_parent: function() {
		this.parent_node && this.parent_node.load_all();
	},
	load_all: function(callback) {
		var  me = this;
		let args = $.extend({}, this.tree.args);

		args.parent = this.data.value;
		args.tree_method = this.tree.method;
		args.is_root = this.is_root;

		return frappe.call({
			method: 'frappe.desk.treeview.get_all_nodes',
			args: args,
			callback: function(r) {
				$.each(r.message, function(i, d) {
					me.render_expand_node(me.tree.nodes[d.parent], d.data);
				});
				if(callback) { callback(); }
			}
		});
	},
	load: function(callback) {
		var node = this;
		var args = $.extend(this.tree.args || {}, {
			parent: this.data.value
		});

		args.is_root = this.is_root;

		return frappe.call({
			method: this.tree.method,
			args: args,
			callback: function(r) {
				node.render_expand_node(node, r.message, callback);
			}
		})
	},
	render_expand_node: function(node, data, callback) {
		node.$ul.empty();
		if (data) {
			$.each(data, function(i, v) {
				var child_node = node.addnode(v);
				child_node.tree_link
					.data('node-data', v)
					.data('node', child_node);
			});
		}

		node.expanded = false;
		node.toggle_node(callback);
		node.loaded = true;
	},
})
<|endoftext|>


<commit_before>import assert from 'assert';
import File from 'vinyl';
import {Minifier} from '../src';
import path from 'path';

/**
 * @test {Minifier}
 */
describe('Minifier', function() {
  this.timeout(60000);

  /**
   * @test {Minifier#constructor}
   */
  describe('#constructor()', () => {
    it('should initialize the existing properties', () => {
      assert.equal(new Minifier({binary: 'FooBar'})._options.binary, 'FooBar');
      assert.equal(new Minifier({silent: true})._options.silent, true);
    });

    it('should not create new properties', () =>
      assert(!('foo' in new Minifier({foo: 'bar'})))
    );
  });

  /**
   * @test {Minifier#close}
   */
  describe('#close()', () => {
    it('should reject the promise if the PHP process is not started or already terminated', () => {
      let minifier = new Minifier();
      minifier._phpServer = null;
      minifier.close().then(
        () => { throw new Error('This promise should not be resolved.'); },
        () => assert(true)
      );
    });
  });

  /**
   * @test {Minifier#listen}
   */
  describe('#listen()', () => {
    it('should reject the promise if the PHP process is already started', () => {
      let minifier = new Minifier();
      minifier._phpServer = {host: '127.0.0.1:8000'};
      minifier.listen().then(
        () => { throw new Error('This promise should not be resolved.'); },
        () => assert(true)
      );
    });
  });

  /**
   * @test {Minifier#_transform}
   */
  describe('#_transform()', () => {
    let file = new File({path: path.join(__dirname, 'sample.php')});
    let minifier = new Minifier({silent: true});

    it('should remove the inline comments', () =>
      minifier._transform(file, 'utf8', (err, result) => {
        assert.ifError(err);
        assert(result.contents.toString().includes('<?= \'Hello World!\' ?>'));
        return minifier.close();
      })
    );

    it('should remove the multi-line comments', () =>
      minifier._transform(file, 'utf8', (err, result) => {
        assert.ifError(err);
        assert(result.contents.toString().includes('namespace dummy; class Dummy'));
        return minifier.close();
      })
    );

    it('should remove the single-line comments', () =>
      minifier._transform(file, 'utf8', (err, result) => {
        assert.ifError(err);
        assert(result.contents.toString().includes('$className = get_class($this); return $className;'));
        return minifier.close();
      })
    );

    it('should remove the whitespace', () =>
      minifier._transform(file, 'utf8', (err, result) => {
        assert.ifError(err);
        assert(result.contents.toString().includes('__construct() { }'));
        return minifier.close();
      })
    );
  });
});
<commit_msg>Updated the unit tests<commit_after>import assert from 'assert';
import File from 'vinyl';
import {Minifier} from '../src/index';
import path from 'path';

/**
 * @test {Minifier}
 */
describe('Minifier', function() {
  this.timeout(60000);

  /**
   * @test {Minifier#constructor}
   */
  describe('#constructor()', () => {
    it('should initialize the existing properties', () => {
      assert.equal(new Minifier({binary: './FooBar.exe'})._options.binary, 'FooBar.exe');
      assert.equal(new Minifier({silent: true})._options.silent, true);
    });

    it('should not create new properties', () =>
      assert(!('foo' in new Minifier({foo: 'bar'})))
    );
  });

  /**
   * @test {Minifier#close}
   */
  describe('#close()', () => {
    it('should error the observable if the PHP process is not started or already terminated', done => {
      let minifier = new Minifier();
      minifier._phpServer = null;
      minifier.close().subscribe({
        complete: () => done(new Error('This observable should not be completed.')),
        error: () => { assert(true); done(); }
      });
    });
  });

  /**
   * @test {Minifier#listen}
   */
  describe('#listen()', () => {
    it('should error the observable if the PHP process is already started', done => {
      let minifier = new Minifier();
      minifier._phpServer = {host: '127.0.0.1:8000'};
      minifier.listen().subscribe({
        complete: () => done(new Error('This observable should not be completed.')),
        error: () => { assert(true); done(); }
      });
    });
  });

  /**
   * @test {Minifier#_transform}
   */
  describe('#_transform()', () => {
    let file = new File({path: path.join(__dirname, 'sample.php')});
    let minifier = new Minifier({silent: true});

    it('should remove the inline comments', () =>
      minifier._transform(file, 'utf8', (err, result) => {
        assert.ifError(err);
        assert(result.contents.toString().includes('<?= \'Hello World!\' ?>'));
        minifier.close().subscribe();
      })
    );

    it('should remove the multi-line comments', () =>
      minifier._transform(file, 'utf8', (err, result) => {
        assert.ifError(err);
        assert(result.contents.toString().includes('namespace dummy; class Dummy'));
        minifier.close().subscribe();
      })
    );

    it('should remove the single-line comments', () =>
      minifier._transform(file, 'utf8', (err, result) => {
        assert.ifError(err);
        assert(result.contents.toString().includes('$className = get_class($this); return $className;'));
        minifier.close().subscribe();
      })
    );

    it('should remove the whitespace', () =>
      minifier._transform(file, 'utf8', (err, result) => {
        assert.ifError(err);
        assert(result.contents.toString().includes('__construct() { }'));
        minifier.close().subscribe();
      })
    );
  });
});
<|endoftext|>