<commit_before>var tap = require('../tap');
var buf = require('buffer');

tap.count(68);

// testing vars
var foo1 = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var foo2 = { "a": 2, "b": [false, true, "a"] };
var foo3 = { "a": 3, "b": { "1": false, "x": 54 } };
var foo4 = { "a": { "b": { "c": { "d": 1 } } } };
var foo5 = '{\n "a": {\n  "b": {\n   "c": {\n    "d": 1\n   }\n  }\n }\n}'
var foo6 = { "location": { "city": { "name": "Chattanooga", "population": 167674 }, "state": { "abbreviation": "TN", "name": "Tennessee", "population": 6403000 } }, "name": "Jim Cowart", "company": "appendTo" };
var foo7 = '{"location":{"city":{"name":"Chattanooga","population":167674},"state":{"abbreviation":"TN","name":"Tennessee","population":6403000}},"name":"Jim Cowart","company":"appendTo"}';
var foo8 = { "a": [ { "b": [ { "c": [ [1,2,3], [], [4,5,6] ] }, { "d": { "e": { "f": [7,8,9], "g": [ [9,8,7], [] ] } } } ] }, "g", [ [ [ { "h": [ [ [ [ [6,5,4] ] ] ] ] } ] ] ], { "i": [ { "j": [ { "k": [ [3,2,1] ] } ] } ] } ] };
var foo9 = '{"a":[{"b":[{"c":[[1,2,3],[],[4,5,6]]},{"d":{"e":{"g":[[9,8,7],[]],"f":[7,8,9]}}}]},"g",[[[{"h":[[[[[6,5,4]]]]]}]]],{"i":[{"j":[{"k":[[3,2,1]]}]}]}]}';
var fooA = { "1800": { "name": "Generic Access", "type": "org.bluetooth.service.generic_access" }, "1801": { "name": "Generic Attribute", "type": "org.bluetooth.service.generic_attribute" }, "1802": { "name": "Immediate Alert", "type": "org.bluetooth.service.immediate_alert" } };
var fooB = '{"1800":{"name":"Generic Access","type":"org.bluetooth.service.generic_access"},"1801":{"name":"Generic Attribute","type":"org.bluetooth.service.generic_attribute"},"1802":{"name":"Immediate Alert","type":"org.bluetooth.service.immediate_alert"}}';

// testing replacer array and functions
var censor_arr = ['transport','month'];
function censor(key, value) {
  tap.ok(this[key] == value, '"this" value correct in replacer');
  if (typeof(value) == "string") {
    return undefined;
  }
  return value;
}

//  1:objects                                   2:string                             3:message                       4:replacer         5:spacer
var objs = [
  { 1:null,                                     2:'null',                            3:'non object null',            4:null,            5:null },
  { 1:true,                                     2:'true',                            3:'non object bool',            4:null,            5:null },
  { 1:3,                                        2:'3',                               3:'non object number',          4:null,            5:null },
  { 1:7.42,                                     2:'7.42',                            3:'non object double',          4:null,            5:null },
  { 1:[],                                       2:'[]',                              3:'empty array',                4:null,            5:null },
  { 1:[0, 1, 2],                                2:'[0,1,2]',                         3:'array',                      4:null,            5:null },
  { 1:[3,"a"],                                  2:'[3,"a"]',                         3:'mixed array',                4:null,            5:null },
  { 1:[3,false,3.454,"a","a"],                  2:'[3,false,3.454,"a","a"]',         3:'repeat value array',         4:null,            5:null },
  { 1:[[[],[],[]],[[],[[1,2]]]],                2:'[[[],[],[]],[[],[[1,2]]]]',       3:'super nested arrays',        4:null,            5:null },
  { 1:foo2,                                     2:'{"a":2,"b":[false,true,"a"]}',    3:'sringify lvl 1 array',       4:null,            5:null },
  { 1:{},                                       2:'{}',                              3:'empty object',               4:null,            5:null },
  { 1:Object(),                                 2:'{}',                              3:'empty object constructor',   4:null,            5:null },
  { 1:{"hi":5},                                 2:'{"hi":5}',                        3:'object explicit key',        4:null,            5:null },
  { 1:{hi:5},                                   2:'{"hi":5}',                        3:'object implicit key',        4:null,            5:null },
  { 1:{"a":{}},                                 2:'{"a":{}}',                        3:'lvl 1 empty object',         4:null,            5:null },
  { 1:foo3,                                     2:'{"a":3,"b":{"1":false,"x":54}}',  3:'lvl 1 object',               4:null,            5:null },
  { 1:foo4,                                     2:'{"a":{"b":{"c":{"d":1}}}}',       3:'super nested objects',       4:null,            5:null },
  { 1:foo6,                                     2:foo7,                              3:'realistic object',           4:null,            5:null },
  { 1:foo8,                                     2:foo9,                              3:'array object mess',          4:null,            5:null },
  { 1:fooA,                                     2:fooB,                              3:'input file test',            4:null,            5:null },
  { 1:{"hi":5},                                 2:'{\n  "hi": 5\n}',                 3:'spacer string',              4:null,            5:'  ' },
  { 1:{"hi":5},                                 2:'{\n   "hi": 5\n}',                3:'spacer number',              4:null,            5:3 },
  { 1:foo4,                                     2:foo5,                              3:'super nested spacer',        4:null,            5:' ' },
  { 1:foo1,                                     2:'{"month":7,"transport":"car"}',   3:'replacer array',             4:censor_arr,      5:null },
  { 1:{a: function () {}, b: 5},                2:'{"b":5}',                         3:'function',                   4:null,            5:null },
  { 1:[1,function(){},2],                       2:'[1,null,2]',                      3:'function in array',          4:null,            5:null },
  { 1:new buf.Buffer([11,22,33,44]),            2:'[11,22,33,44]',                   3:'buffer',                     4:null,            5:null },
  { 1:NaN,                                      2:'null',                            3:'NaN',                        4:null,            5:null },
  { 1:Infinity,                                 2:'null',                            3:'Infinity',                   4:null,            5:null },
  { 1:-Infinity,                                2:'null',                            3:'-Infinity',                  4:null,            5:null },
  { 1:[[],"11"],                                2:'[[],"11"]',                       3:'arr in arr then value',      4:null,            5:null },
  { 1:'hello\n',                                2:'"hello\\n"',                      3:'non object string',          4:null,            5:null },
]

var objs2 = [
  { 1:{"hi":5},                                 2:'{\n123456789A"hi": 5\n}',         3:'spacer string long',         4:null,            5:'123456789AB' },
  { 1:foo1,                                     2:'{"month":45,"week":7}',           3:'replacer function',          4:censor,          5:null },
]

// Simple parsing testing
console.log('# parsing tesing');
tap.ok(JSON.parse("{\"hi\": 5}").hasOwnProperty, 'json object is real object');
tap.ok(JSON.parse("[0, 1, 2]").slice, 'json array is real array');

// string->parse->stringify should equal original string
for (var i in objs) {
  var obj = JSON.parse(objs[i][2])
  var res = JSON.stringify(obj, objs[i][4], objs[i][5]);
  tap.eq(res, objs[i][2], objs[i][3]);

  tap.eq(JSON.stringify(objs[i][1], objs[i][4], objs[i][5]), objs[i][2], objs[i][3]);
}

// stringified object should equal corresponding string
for (var i in objs2) {
  var res = JSON.stringify(objs[i][1], objs[i][4], objs[i][5]);
  tap.eq(res, objs[i][2], objs[i][3]);
}

var d = new Date(42);
tap.eq(JSON.stringify({
  toJSON: function () { return "foo"; }
}), "\"foo\"", 'toJSON called on dates');

var a = { toJSON: function () { return "hello"; }}
tap.eq(JSON.stringify(a), '"hello"', 'toJSON called on objects')

var a = { toJSON: function () { return { toJSON: function () { return 5; }}; }}
tap.eq(JSON.stringify(a), '{}', 'toJSON isnt recursive')
<commit_msg>Adds additional test thanks to @jiahuang.<commit_after>var tap = require('../tap');
var buf = require('buffer');

tap.count(72);

// testing vars
var foo1 = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var foo2 = { "a": 2, "b": [false, true, "a"] };
var foo3 = { "a": 3, "b": { "1": false, "x": 54 } };
var foo4 = { "a": { "b": { "c": { "d": 1 } } } };
var foo5 = '{\n "a": {\n  "b": {\n   "c": {\n    "d": 1\n   }\n  }\n }\n}'
var foo6 = { "location": { "city": { "name": "Chattanooga", "population": 167674 }, "state": { "abbreviation": "TN", "name": "Tennessee", "population": 6403000 } }, "name": "Jim Cowart", "company": "appendTo" };
var foo7 = '{"location":{"city":{"name":"Chattanooga","population":167674},"state":{"abbreviation":"TN","name":"Tennessee","population":6403000}},"name":"Jim Cowart","company":"appendTo"}';
var foo8 = { "a": [ { "b": [ { "c": [ [1,2,3], [], [4,5,6] ] }, { "d": { "e": { "f": [7,8,9], "g": [ [9,8,7], [] ] } } } ] }, "g", [ [ [ { "h": [ [ [ [ [6,5,4] ] ] ] ] } ] ] ], { "i": [ { "j": [ { "k": [ [3,2,1] ] } ] } ] } ] };
var foo9 = '{"a":[{"b":[{"c":[[1,2,3],[],[4,5,6]]},{"d":{"e":{"g":[[9,8,7],[]],"f":[7,8,9]}}}]},"g",[[[{"h":[[[[[6,5,4]]]]]}]]],{"i":[{"j":[{"k":[[3,2,1]]}]}]}]}';
var fooA = { "1800": { "name": "Generic Access", "type": "org.bluetooth.service.generic_access" }, "1801": { "name": "Generic Attribute", "type": "org.bluetooth.service.generic_attribute" }, "1802": { "name": "Immediate Alert", "type": "org.bluetooth.service.immediate_alert" } };
var fooB = '{"1800":{"name":"Generic Access","type":"org.bluetooth.service.generic_access"},"1801":{"name":"Generic Attribute","type":"org.bluetooth.service.generic_attribute"},"1802":{"name":"Immediate Alert","type":"org.bluetooth.service.immediate_alert"}}';

// testing replacer array and functions
var censor_arr = ['transport','month'];
function censor(key, value) {
  tap.ok(this[key] == value, '"this" value correct in replacer');
  if (typeof(value) == "string") {
    return undefined;
  }
  return value;
}

//  1:objects                                   2:string                             3:message                       4:replacer         5:spacer
var objs = [
  { 1:null,                                     2:'null',                            3:'non object null',            4:null,            5:null },
  { 1:true,                                     2:'true',                            3:'non object bool',            4:null,            5:null },
  { 1:3,                                        2:'3',                               3:'non object number',          4:null,            5:null },
  { 1:7.42,                                     2:'7.42',                            3:'non object double',          4:null,            5:null },
  { 1:[],                                       2:'[]',                              3:'empty array',                4:null,            5:null },
  { 1:[0, 1, 2],                                2:'[0,1,2]',                         3:'array',                      4:null,            5:null },
  { 1:[3,"a"],                                  2:'[3,"a"]',                         3:'mixed array',                4:null,            5:null },
  { 1:[3,false,3.454,"a","a"],                  2:'[3,false,3.454,"a","a"]',         3:'repeat value array',         4:null,            5:null },
  { 1:[[[],[],[]],[[],[[1,2]]]],                2:'[[[],[],[]],[[],[[1,2]]]]',       3:'super nested arrays',        4:null,            5:null },
  { 1:foo2,                                     2:'{"a":2,"b":[false,true,"a"]}',    3:'sringify lvl 1 array',       4:null,            5:null },
  { 1:{},                                       2:'{}',                              3:'empty object',               4:null,            5:null },
  { 1:Object(),                                 2:'{}',                              3:'empty object constructor',   4:null,            5:null },
  { 1:{"hi":5},                                 2:'{"hi":5}',                        3:'object explicit key',        4:null,            5:null },
  { 1:{hi:5},                                   2:'{"hi":5}',                        3:'object implicit key',        4:null,            5:null },
  { 1:{"a":{}},                                 2:'{"a":{}}',                        3:'lvl 1 empty object',         4:null,            5:null },
  { 1:foo3,                                     2:'{"a":3,"b":{"1":false,"x":54}}',  3:'lvl 1 object',               4:null,            5:null },
  { 1:foo4,                                     2:'{"a":{"b":{"c":{"d":1}}}}',       3:'super nested objects',       4:null,            5:null },
  { 1:foo6,                                     2:foo7,                              3:'realistic object',           4:null,            5:null },
  { 1:foo8,                                     2:foo9,                              3:'array object mess',          4:null,            5:null },
  { 1:fooA,                                     2:fooB,                              3:'input file test',            4:null,            5:null },
  { 1:{"hi":5},                                 2:'{\n  "hi": 5\n}',                 3:'spacer string',              4:null,            5:'  ' },
  { 1:{"hi":5},                                 2:'{\n   "hi": 5\n}',                3:'spacer number',              4:null,            5:3 },
  { 1:foo4,                                     2:foo5,                              3:'super nested spacer',        4:null,            5:' ' },
  { 1:foo1,                                     2:'{"month":7,"transport":"car"}',   3:'replacer array',             4:censor_arr,      5:null },
  { 1:{a: function () {}, b: 5},                2:'{"b":5}',                         3:'function',                   4:null,            5:null },
  { 1:[1,function(){},2],                       2:'[1,null,2]',                      3:'function in array',          4:null,            5:null },
  { 1:new buf.Buffer([11,22,33,44]),            2:'[11,22,33,44]',                   3:'buffer',                     4:null,            5:null },
  { 1:NaN,                                      2:'null',                            3:'NaN',                        4:null,            5:null },
  { 1:Infinity,                                 2:'null',                            3:'Infinity',                   4:null,            5:null },
  { 1:-Infinity,                                2:'null',                            3:'-Infinity',                  4:null,            5:null },
  { 1:[[],"11"],                                2:'[[],"11"]',                       3:'arr in arr then value',      4:null,            5:null },
  { 1:'hello\n',                                2:'"hello\\n"',                      3:'non object string',          4:null,            5:null },
]

var objs2 = [
  { 1:{"hi":5},                                 2:'{\n123456789A"hi": 5\n}',         3:'spacer string long',         4:null,            5:'123456789AB' },
  { 1:foo1,                                     2:'{"month":45,"week":7}',           3:'replacer function',          4:censor,          5:null },
  { 1:[[], {}, [null], [0], [[{}]], "14121269654077727"], 2:'[[],{},[null],[0],[[{}]],"14121269654077727"]', 3:'complex object', 4:null, 5:null},
]

// Simple parsing testing
console.log('# parsing tesing');
tap.ok(JSON.parse("{\"hi\": 5}").hasOwnProperty, 'json object is real object');
tap.ok(JSON.parse("[0, 1, 2]").slice, 'json array is real array');

// string->parse->stringify should equal original string
for (var i in objs) {
  var obj = JSON.parse(objs[i][2])
  var res = JSON.stringify(obj, objs[i][4], objs[i][5]);
  tap.eq(res, objs[i][2], objs[i][3]);

  tap.eq(JSON.stringify(objs[i][1], objs[i][4], objs[i][5]), objs[i][2], objs[i][3]);
}

// stringified object should equal corresponding string
for (var i in objs2) {
  var res = JSON.stringify(objs[i][1], objs[i][4], objs[i][5]);
  tap.eq(res, objs[i][2], objs[i][3]);
}

var d = new Date(42);
tap.eq(JSON.stringify({
  toJSON: function () { return "foo"; }
}), "\"foo\"", 'toJSON called on dates');

var a = { toJSON: function () { return "hello"; }}
tap.eq(JSON.stringify(a), '"hello"', 'toJSON called on objects')

var a = { toJSON: function () { return { toJSON: function () { return 5; }}; }}
tap.eq(JSON.stringify(a), '{}', 'toJSON isnt recursive')

var arr = JSON.parse("[[], {}, [null], [0], [[{}]], \"14121269654077727\"]");
<|endoftext|>


<commit_before>"use strict";

var neume = require("../../src");

require("../../src/ugen/osc");
require("../../src/ugen/add");
require("../../src/ugen/mul");
require("../../src/ugen/env");

var util = neume.util;
var NOP = function() {};

describe("neume.UGen", function() {
  var context = null;
  var synth = null;
  var ugen0 = null;
  var registered = null;

  beforeEach(function() {
    var audioContext = new global.AudioContext();
    context = new neume.Context(audioContext.destination);
    synth = {
      $context: context
    };
    ugen0 = neume.UGen.build(synth, "sin.kr.lfo#ugen0", {}, []);
    ugen0.toAudioNode().$id = "ugen0";
  });

  describe("constructor", function() {
    it("(synth: neume.Synth, key: string, spec: object, inputs: Array<any>)", function() {
      assert(ugen0 instanceof neume.UGen);
      assert(ugen0 instanceof neume.Emitter);
      assert(ugen0.$id === "ugen0");
      assert.deepEqual(ugen0.$class, [ "kr", "lfo" ]);
    });
    it("throw an error if given invalid key", function() {
      assert.throws(function() {
        neume.UGen.build(synth, "#id", {}, []);
      }, Error);
    });
  });

  describe(".build", function() {
    it("(synth: neume.Synth, key: string, spec: object, inputs: Array<any>): neume.UGen", function() {
      var ugen = neume.UGen.build(synth, "sin", {}, []);

      assert(ugen instanceof neume.UGen);
    });
    it("(synth: neume.Synth, key: number, spec: object, inputs: Array<any>): neume.UGen", function() {
      var ugen = neume.UGen.build(synth, 100, {}, []);

      assert(ugen instanceof neume.UGen);
      assert(ugen.$key === "number");
    });
    it("(synth: neume.Synth, key: object, spec: object, inputs: Array<any>): neume.UGen", function() {
      var ugen = neume.UGen.build(synth, new Date(), {}, []);

      assert(ugen instanceof neume.UGen);
      assert(ugen.$key === "object");
    });
    it("(synth: neume.Synth, unknownKey: string, spec: object, inputs: Array<any>): throws an error", function() {
      assert.throws(function() {
        neume.UGen.build(synth, "unknown", {}, []);
      }, Error);
    });
  });

  describe(".register", function() {
    it("(name: string, func: function): void", function() {
      [
        "fb-sin", "DX7", "OD-1", "<@-@>"
      ].forEach(function(ok) {
        assert.doesNotThrow(function() {
          neume.UGen.register(ok, NOP);
        });
      });
    });
    it("(invalidName: string, func: function): throw an error", function() {
      [
        "0", "sin.kr", "sin#lfo",
        "-fb", "fb-", "fb--sin", "<@-@>b"
      ].forEach(function(ng) {
        assert.throws(function() {
          neume.UGen.register(ng, NOP);
        }, Error);
      });
    });
    it("(name: string, func: !function): throw an error", function() {
      assert.throws(function() {
        neume.UGen.register("not-a-function", { call: NOP, apply: NOP });
      }, TypeError);
    });
  });

  describe("#$", function() {
    it("(key:string): neume.UGen", function() {
      var node = context.createGain();
      var spy = sinon.spy();

      var a = neume.UGen.build({
        $context: context,
        $builder: spy
      }, "sin", { add: 880 }, []);

      a.$("lpf");

      assert(spy.calledOnce);
      assert(spy.calledWith("lpf", {}, [ a ]));
    });
    it("(key:string, spec:object): neume.UGen", function() {
      var node = context.createGain();
      var spy = sinon.spy();

      var a = neume.UGen.build({
        $context: context,
        $builder: spy
      }, "sin", { add: 880 }, []);

      a.$("lpf", { freq: 200 });

      assert(spy.calledOnce);
      assert(spy.calledWith("lpf", { freq: 200 }, [ a ]));
    });
    it("(key:string, ...args:any): neume.UGen", function() {
      var node = context.createGain();
      var spy = sinon.spy();

      var a = neume.UGen.build({
        $context: context,
        $builder: spy
      }, "sin", { add: 880 }, []);

      a.$("lpf", ugen0);

      assert(spy.calledOnce);
      assert(spy.calledWith("lpf", {}, [ a, ugen0 ]));
    });
    it("(key:string, spec:object, ...args: any): neume.UGen", function() {
      var node = context.createGain();
      var spy = sinon.spy();

      var a = neume.UGen.build({
        $context: context,
        $builder: spy
      }, "sin", { add: 880 }, []);

      a.$("lpf", { freq: 200 }, ugen0);

      assert(spy.calledOnce);
      assert(spy.calledWith("lpf", { freq: 200 }, [ a, ugen0 ]));
    });
  });

  describe("#mul", function() {
    it("(value: any): neume.UGen", function() {
      var node = context.createGain();
      var spy = sinon.spy();

      var a = neume.UGen.build({
        $context: context,
        $builder: spy
      }, "sin", { add: 880 }, []);

      a.mul(1000);

      assert(spy.calledOnce);
      assert(spy.calledWith("*", a, 1000));
    });
  });

  describe("#add", function() {
    it("(value: any): neume.UGen", function() {
      var node = context.createGain();
      var spy = sinon.spy();

      var a = neume.UGen.build({
        $context: context,
        $builder: spy
      }, "sin", { add: 880 }, []);

      a.add(1000);

      assert(spy.calledOnce);
      assert(spy.calledWith("+", a, 1000));
    });
  });

  describe("#toAudioNode", function() {
    it("(): AudioNode", function() {
      assert(ugen0.toAudioNode() instanceof global.AudioNode);
    });
  });

  describe("#connect", function() {
    it("(to: AudioNode): self", function() {
      var node = context.createGain();

      neume.UGen.build(synth, "sin#ugen0", {}, []).connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [
          {
            name: "OscillatorNode",
            type: "sine",
            frequency: {
              value: 440,
              inputs: []
            },
            detune: {
              value: 0,
              inputs: []
            },
            inputs: []
          }
        ]
      });
    });
    it("(to: AudioNode): self // when with offset", function() {
      var node = context.createGain();

      neume.UGen.build(synth, "sin#ugen0", { add: 880 }, []).connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [
          {
            name: "OscillatorNode",
            type: "sine",
            frequency: {
              value: 440,
              inputs: []
            },
            detune: {
              value: 0,
              inputs: []
            },
            inputs: []
          },
          {
            name: "GainNode",
            gain: {
              value: 880,
              inputs: []
            },
            inputs: [ DC(1) ]
          }
        ]
      });
      assert(node.$inputs[1].$inputs[0].buffer.getChannelData(0)[0] === 1);
    });
    it("(to: AudioParam): self", function() {
      var node = context.createGain();

      node.gain.value = 0;

      neume.UGen.build(synth, "sin#ugen0", {}, []).connect(node.gain);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 0,
          inputs: [
            {
              name: "OscillatorNode",
              type: "sine",
              frequency: {
                value: 440,
                inputs: []
              },
              detune: {
                value: 0,
                inputs: []
              },
              inputs: []
            }
          ]
        },
        inputs: []
      });
    });
    it("(to: AudioParam): self // when with offset", function() {
      var node = context.createGain();

      node.gain.value = 0;

      neume.UGen.build(synth, "sin#ugen0", { add: 880 }, []).connect(node.gain);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 880,
          inputs: [
            {
              name: "OscillatorNode",
              type: "sine",
              frequency: {
                value: 440,
                inputs: []
              },
              detune: {
                value: 0,
                inputs: []
              },
              inputs: []
            }
          ]
        },
        inputs: []
      });
    });
  });

  describe("#disconnect", function() {
    it("(): self", function() {
      var node = context.createGain();

      neume.UGen.build(synth, "sin#ugen0", {}, []).connect(node).disconnect();

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: []
      });
    });
  });

  describe("method bindings", function() {
    it("works", function() {
      var ugen1 = neume.UGen.build(synth, "adsr", {}, []);

      assert(ugen1.release() === ugen1);
      assert(ugen1.release(0) === ugen1);
    });
  });

  describe("mul(a, b)", function() {
    it("return a when a * 1", function() {
      var node = context.createGain();

      var b = 1;
      var a = neume.UGen.build(synth, "sin", { mul: b }, []);

      a.connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [
          {
            name: "OscillatorNode",
            type: "sine",
            frequency: {
              value: 440,
              inputs: []
            },
            detune: {
              value: 0,
              inputs: []
            },
            inputs: []
          }
        ]
      });
    });
    it("return DC(0) when a * 0", function() {
      var node = context.createGain();

      var b = 0;
      var a = neume.UGen.build(synth, "sin", { mul: b }, []);

      a.connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [ DC(0) ]
      });
    });
    it("return a * b", function() {
      var node = context.createGain();

      var b = neume.UGen.build(synth, "sin", {}, []);
      var a = neume.UGen.build(synth, "sin", { mul: b }, []);

      a.connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [
          {
            name: "GainNode",
            gain: {
              value: 0,
              inputs: [
                {
                  name: "OscillatorNode",
                  type: "sine",
                  frequency: {
                    value: 440,
                    inputs: []
                  },
                  detune: {
                    value: 0,
                    inputs: []
                  },
                  inputs: []
                }
              ]
            },
            inputs: [
              {
                name: "OscillatorNode",
                type: "sine",
                frequency: {
                  value: 440,
                  inputs: []
                },
                detune: {
                  value: 0,
                  inputs: []
                },
                inputs: []
              }
            ]
          }
        ]
      });
    });
  });

});
<commit_msg>clean test code<commit_after>"use strict";

var neume = require("../../src");

require("../../src/ugen/osc");
require("../../src/ugen/add");
require("../../src/ugen/mul");
require("../../src/ugen/env");

var util = neume.util;
var NOP = function() {};

describe("neume.UGen", function() {
  var context = null;
  var synth = null;

  beforeEach(function() {
    context = new neume.Context(new global.AudioContext().destination);
    synth = new neume.Synth(context, NOP, []);
  });

  describe("constructor", function() {
    it("(synth: neume.Synth, key: string, spec: object, inputs: Array<any>)", function() {
      var ugen = neume.UGen.build(synth, "sin.kr.lfo#ugen0", {}, []);

      assert(ugen instanceof neume.UGen);
      assert(ugen instanceof neume.Emitter);
      assert(ugen.$id === "ugen0");
      assert.deepEqual(ugen.$class, [ "kr", "lfo" ]);
    });
    it("throw an error if given invalid key", function() {
      assert.throws(function() {
        neume.UGen.build(synth, "#id", {}, []);
      }, Error);
    });
  });

  describe(".build", function() {
    it("(synth: neume.Synth, key: string, spec: object, inputs: Array<any>): neume.UGen", function() {
      var ugen = neume.UGen.build(synth, "sin", {}, []);

      assert(ugen instanceof neume.UGen);
    });
    it("(synth: neume.Synth, key: number, spec: object, inputs: Array<any>): neume.UGen", function() {
      var ugen = neume.UGen.build(synth, 100, {}, []);

      assert(ugen instanceof neume.UGen);
      assert(ugen.$key === "number");
    });
    it("(synth: neume.Synth, key: object, spec: object, inputs: Array<any>): neume.UGen", function() {
      var ugen = neume.UGen.build(synth, new Date(), {}, []);

      assert(ugen instanceof neume.UGen);
      assert(ugen.$key === "object");
    });
    it("(synth: neume.Synth, unknownKey: string, spec: object, inputs: Array<any>): throws an error", function() {
      assert.throws(function() {
        neume.UGen.build(synth, "unknown", {}, []);
      }, Error);
    });
  });

  describe(".register", function() {
    it("(name: string, func: function): void", function() {
      [
        "fb-sin", "DX7", "OD-1", "<@-@>"
      ].forEach(function(ok) {
        assert.doesNotThrow(function() {
          neume.UGen.register(ok, NOP);
        });
      });
    });
    it("(invalidName: string, func: function): throw an error", function() {
      [
        "0", "sin.kr", "sin#lfo",
        "-fb", "fb-", "fb--sin", "<@-@>b"
      ].forEach(function(ng) {
        assert.throws(function() {
          neume.UGen.register(ng, NOP);
        }, Error);
      });
    });
    it("(name: string, func: !function): throw an error", function() {
      assert.throws(function() {
        neume.UGen.register("not-a-function", { call: NOP, apply: NOP });
      }, TypeError);
    });
  });

  describe("#$", function() {
    it("(key:string): neume.UGen", sinon.test(function() {
      var spy = this.spy(synth, "$builder");
      var ugen = neume.UGen.build(synth, "sin", {}, []);

      ugen.$("lpf");

      assert(spy.calledOnce);
      assert(spy.calledWith("lpf", {}, [ ugen ]));
    }));
    it("(key:string, spec:object): neume.UGen", sinon.test(function() {
      var spy = this.spy(synth, "$builder");
      var ugen = neume.UGen.build(synth, "sin", {}, []);

      ugen.$("lpf", { freq: 200 });

      assert(spy.calledOnce);
      assert(spy.calledWith("lpf", { freq: 200 }, [ ugen ]));
    }));
    it("(key:string, ...args:any): neume.UGen", sinon.test(function() {
      var spy = this.spy(synth, "$builder");
      var node = context.createGain();
      var ugen = neume.UGen.build(synth, "sin", {}, []);

      ugen.$("lpf", node);

      assert(spy.calledOnce);
      assert(spy.calledWith("lpf", {}, [ ugen, node ]));
    }));
    it("(key:string, spec:object, ...args: any): neume.UGen", sinon.test(function() {
      var spy = this.spy(synth, "$builder");
      var node = context.createGain();
      var ugen = neume.UGen.build(synth, "sin", {}, []);

      ugen.$("lpf", { freq: 200 }, node);

      assert(spy.calledOnce);
      assert(spy.calledWith("lpf", { freq: 200 }, [ ugen, node ]));
    }));
  });

  describe("#mul", function() {
    it("(value: any): neume.UGen", sinon.test(function() {
      var spy = this.spy(synth, "$builder");
      var node = context.createGain();
      var ugen = neume.UGen.build(synth, "sin", {}, []);

      ugen.mul(1000);

      assert(spy.calledOnce);
      assert(spy.calledWith("*", ugen, 1000));
    }));
  });

  describe("#add", function() {
    it("(value: any): neume.UGen", sinon.test(function() {
      var spy = this.spy(synth, "$builder");
      var node = context.createGain();
      var ugen = neume.UGen.build(synth, "sin", {}, []);

      ugen.add(1000);

      assert(spy.calledOnce);
      assert(spy.calledWith("+", ugen, 1000));
    }));
  });

  describe("#toAudioNode", function() {
    it("(): AudioNode", function() {
      var ugen = neume.UGen.build(synth, "sin", {}, []);
      assert(ugen.toAudioNode() instanceof global.AudioNode);
      assert(ugen.toAudioNode() === ugen.toAudioNode());
    });
  });

  describe("#connect", function() {
    it("(to: AudioNode): self", function() {
      var node = context.createGain();

      neume.UGen.build(synth, "sin", {}, []).connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [
          {
            name: "OscillatorNode",
            type: "sine",
            frequency: {
              value: 440,
              inputs: []
            },
            detune: {
              value: 0,
              inputs: []
            },
            inputs: []
          }
        ]
      });
    });
    it("(to: AudioNode): self // when with offset", function() {
      var node = context.createGain();

      neume.UGen.build(synth, "sin", { add: 880 }, []).connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [
          {
            name: "OscillatorNode",
            type: "sine",
            frequency: {
              value: 440,
              inputs: []
            },
            detune: {
              value: 0,
              inputs: []
            },
            inputs: []
          },
          {
            name: "GainNode",
            gain: {
              value: 880,
              inputs: []
            },
            inputs: [ DC(1) ]
          }
        ]
      });
      assert(node.$inputs[1].$inputs[0].buffer.getChannelData(0)[0] === 1);
    });
    it("(to: AudioParam): self", function() {
      var node = context.createGain();

      neume.UGen.build(synth, "sin", {}, []).connect(node.gain);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: [
            {
              name: "OscillatorNode",
              type: "sine",
              frequency: {
                value: 440,
                inputs: []
              },
              detune: {
                value: 0,
                inputs: []
              },
              inputs: []
            }
          ]
        },
        inputs: []
      });
    });
    it("(to: AudioParam): self // when with offset", function() {
      var node = context.createGain();

      neume.UGen.build(synth, "sin", { add: 880 }, []).connect(node.gain);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 880,
          inputs: [
            {
              name: "OscillatorNode",
              type: "sine",
              frequency: {
                value: 440,
                inputs: []
              },
              detune: {
                value: 0,
                inputs: []
              },
              inputs: []
            }
          ]
        },
        inputs: []
      });
    });
  });

  describe("#disconnect", function() {
    it("(): self", function() {
      var node = context.createGain();

      neume.UGen.build(synth, "sin", {}, []).connect(node).disconnect();

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: []
      });
    });
  });

  describe("method bindings", function() {
    it("works", function() {
      var ugen = neume.UGen.build(synth, "adsr", {}, []);

      assert(ugen.release() === ugen);
      assert(ugen.release(0) === ugen);
    });
  });

  describe("mul(a, b)", function() {
    it("return a when a * 1", function() {
      var node = context.createGain();

      var b = 1;
      var a = neume.UGen.build(synth, "sin", { mul: b }, []);

      a.connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [
          {
            name: "OscillatorNode",
            type: "sine",
            frequency: {
              value: 440,
              inputs: []
            },
            detune: {
              value: 0,
              inputs: []
            },
            inputs: []
          }
        ]
      });
    });
    it("return DC(0) when a * 0", function() {
      var node = context.createGain();

      var b = 0;
      var a = neume.UGen.build(synth, "sin", { mul: b }, []);

      a.connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [ DC(0) ]
      });
    });
    it("return a * b", function() {
      var node = context.createGain();

      var b = neume.UGen.build(synth, "sin", {}, []);
      var a = neume.UGen.build(synth, "sin", { mul: b }, []);

      a.connect(node);

      assert.deepEqual(node.toJSON(), {
        name: "GainNode",
        gain: {
          value: 1,
          inputs: []
        },
        inputs: [
          {
            name: "GainNode",
            gain: {
              value: 0,
              inputs: [
                {
                  name: "OscillatorNode",
                  type: "sine",
                  frequency: {
                    value: 440,
                    inputs: []
                  },
                  detune: {
                    value: 0,
                    inputs: []
                  },
                  inputs: []
                }
              ]
            },
            inputs: [
              {
                name: "OscillatorNode",
                type: "sine",
                frequency: {
                  value: 440,
                  inputs: []
                },
                detune: {
                  value: 0,
                  inputs: []
                },
                inputs: []
              }
            ]
          }
        ]
      });
    });
  });

});
<|endoftext|>


<commit_before>const f = require('lodash/fp');
const babylon = require('babylon');

const parseDependencies = (functionStr) => {
    const parsed = babylon.parse(functionStr, {
        sourceType: 'script' });
    // get the first argument of the function, then get its desctructued properties
    const properties = f.flow(
        f.get('program.body.0.expression.params.0.properties'),
        f.map('key.name')
        )(parsed);
    return properties;
};

const checkMissingDependencies = (factoryMethod, dependencies) => {
    // check if all dependencies are available for module
    const functionStr = factoryMethod.toString();
    const requiredDependencies = parseDependencies(functionStr);

    const missingDependency = f.find(d => !dependencies[d], requiredDependencies);

    return missingDependency;
};

const createProxy = (dependencies) => {
    const proxyHandler = {
        get (target, name) {
            // check string names only to avoid breaking symbols (console.log)
            if (typeof name === 'string' && !target[name]) {
                console.trace(`dependency "${name}" not found`);
            }
            return target[name];
        },
    };

    return new Proxy(dependencies, proxyHandler);
};

// TODO: use getters for lazy loading?
module.exports = (moduleDefinitions, existingModules = {}) =>
    f.flow(
        f.toPairs,
        f.reduce((dependencies, [name, factoryMethod]) => {
            if (dependencies[name]) {
                throw new Error(`dependency name (${name}) already exists`);
            }

            // check if all dependencies are available for module
            const missingDependency = checkMissingDependencies(factoryMethod, dependencies);
            if (missingDependency) {
                console.trace(`missing dependency "${missingDependency}" for module "${name}"`);
            }

            const instance = factoryMethod(dependencies);
            return f.assign(dependencies, { [name]: instance });
        }, existingModules),
        createProxy
    )(moduleDefinitions);
<commit_msg>rename param<commit_after>const f = require('lodash/fp');
const babylon = require('babylon');

const parseDependencies = (functionStr) => {
    const parsed = babylon.parse(functionStr, {
        sourceType: 'script' });
    // get the first argument of the function, then get its desctructued properties
    const properties = f.flow(
        f.get('program.body.0.expression.params.0.properties'),
        f.map('key.name')
        )(parsed);
    return properties;
};

const checkMissingDependencies = (factoryMethod, dependencies) => {
    // check if all dependencies are available for module
    const functionStr = factoryMethod.toString();
    const requiredDependencies = parseDependencies(functionStr);

    const missingDependency = f.find(d => !dependencies[d], requiredDependencies);

    return missingDependency;
};

const createProxy = (dependencies) => {
    const proxyHandler = {
        get (target, name) {
            // check string names only to avoid breaking symbols (console.log)
            if (typeof name === 'string' && !target[name]) {
                console.trace(`dependency "${name}" not found`);
            }
            return target[name];
        },
    };

    return new Proxy(dependencies, proxyHandler);
};

// TODO: use getters for lazy loading?
module.exports = (moduleDefinitions, existingDependencies = {}) =>
    f.flow(
        f.toPairs,
        f.reduce((dependencies, [name, factoryMethod]) => {
            if (dependencies[name]) {
                throw new Error(`dependency name (${name}) already exists`);
            }

            // check if all dependencies are available for module
            const missingDependency = checkMissingDependencies(factoryMethod, dependencies);
            if (missingDependency) {
                console.trace(`missing dependency "${missingDependency}" for module "${name}"`);
            }

            const instance = factoryMethod(dependencies);
            return f.assign(dependencies, { [name]: instance });
        }, existingDependencies),
        createProxy
    )(moduleDefinitions);
<|endoftext|>


<commit_before>/*
 * Unit Test for Mapael
 * Module: Basic
 *
 * Here are tested:
 *      - Basic map creation
 *      - Basic map interaction
 *      - options.map.name
 */
$(function() {

    module("Basic");

    var CST_NB_OF_FRANCE_DPTMT = 96;
    var CST_MAP_MAX_WIDTH = 800;
    var CST_MAP_MAX_HEIGHT = 834.8948306319708; // Calculated

    test("Default instance creation", function(assert) {

        /* Create the basic map! */
        $(".mapcontainer").mapael({
            map: {
                name: "france_departments"
            }
        });

        /* Some basic checks */
        assert.ok($(".mapcontainer .map svg")[0], "SVG map created" );
        assert.ok($(".mapcontainer .map svg path")[0], "Path in SVG map" );
        assert.equal($(".mapcontainer .map svg path").length, CST_NB_OF_FRANCE_DPTMT, "All France department drawn" );
        assert.equal($(".mapcontainer .map svg").attr("width"), CST_MAP_MAX_WIDTH, "Check map width size" );
        assert.equal($(".mapcontainer .map svg").attr("height"), CST_MAP_MAX_HEIGHT, "Check map height size" );
        assert.ok($(".mapcontainer").hasClass("mapael"), "Has mapael class" );
        assert.ok(typeof $(".mapcontainer").data("mapael") === "function", "Has mapael data" );
        assert.ok($(".mapcontainer .map .mapTooltip")[0], "Has tooltip div" );

    });

    test("Creation fail: wrong map", function(assert) {

        /* Error if wrong map name */
        assert.throws(function(){
            $(".mapcontainer").mapael({
                map: { name: "not_existing_map" }
            });
        }, "Throw error" );

        assert.notOk($(".mapcontainer svg")[0], "Map not existing" );

    });

    test("Creation fail: existing map", function(assert) {
        $(".mapcontainer").mapael({
            map: { name: "france_departments" }
        });
        assert.throws(function(){
            $(".mapcontainer").mapael({
                map: { name: "france_departments" }
            });
        }, "Throw error" );
    });

    test("Mouseover", function(assert) {
        var mouseover_async_done = assert.async(CST_NB_OF_FRANCE_DPTMT);

        /* Create the map */
        $(".mapcontainer").mapael({
            map: {
                name: "france_departments"
            }
        });

        /* mouseover event check (background changement) */
        var default_fill = $(".mapcontainer svg path:first").attr("fill");
        $(".mapcontainer svg path").each(function(id, elem) {
            var $elem = $(elem);

            $elem.trigger("mouseover");
            setTimeout(function() {
                var new_fill = $elem.attr("fill");
                assert.notEqual(default_fill, new_fill, "Check new background" );
                assert.ok($(".mapcontainer .map .mapTooltip").is( ":hidden" ), "Check tooltip hidden" );

                $elem.trigger("mouseout");
                setTimeout(function() {
                    var new_fill = $elem.attr("fill");
                    assert.equal(new_fill, default_fill, "Check old background" );
                    mouseover_async_done();
                }, 500);
            }, 500);
        });

    });

    test("Responsive", function(assert) {
        var responsive_async_done = assert.async();

        /* Create the map */
        $(".mapcontainer").mapael({
            map: {
                name: "france_departments"
            }
        });

        /* Responsive checks */
        $(".mapcontainer").width(CST_MAP_MAX_WIDTH/2);
        $(window).trigger('resize');
        setTimeout(function() {
            var $svg = $(".mapcontainer .map svg");
            assert.equal($svg.attr("width"), CST_MAP_MAX_WIDTH/2, "Check new map width size" );
            assert.equal($svg.attr("height"), CST_MAP_MAX_HEIGHT/2, "Check new map height size" );

            $(".mapcontainer").width(CST_MAP_MAX_WIDTH);
            $(window).trigger('resize');
            setTimeout(function() {
                var $svg = $(".mapcontainer .map svg");
                assert.equal($svg.attr("width"), CST_MAP_MAX_WIDTH, "Check old map width size" );
                assert.equal($svg.attr("height"), CST_MAP_MAX_HEIGHT, "Check old map height size" );
                responsive_async_done();
            }, 500);
        }, 500);

    });

});<commit_msg>Update UT for new arch<commit_after>/*
 * Unit Test for Mapael
 * Module: Basic
 *
 * Here are tested:
 *      - Basic map creation
 *      - Basic map interaction
 *      - options.map.name
 */
$(function() {

    module("Basic");

    var CST_NB_OF_FRANCE_DPTMT = 96;
    var CST_MAP_MAX_WIDTH = 800;
    var CST_MAP_MAX_HEIGHT = 834.8948306319708; // Calculated

    test("Default instance creation", function(assert) {

        /* Create the basic map! */
        $(".mapcontainer").mapael({
            map: {
                name: "france_departments"
            }
        });

        /* Some basic checks */
        assert.ok($(".mapcontainer .map svg")[0], "SVG map created" );
        assert.ok($(".mapcontainer .map svg path")[0], "Path in SVG map" );
        assert.equal($(".mapcontainer .map svg path").length, CST_NB_OF_FRANCE_DPTMT, "All France department drawn" );
        assert.equal($(".mapcontainer .map svg").attr("width"), CST_MAP_MAX_WIDTH, "Check map width size" );
        assert.equal($(".mapcontainer .map svg").attr("height"), CST_MAP_MAX_HEIGHT, "Check map height size" );
        assert.ok($(".mapcontainer").hasClass("mapael"), "Has mapael class" );
        assert.ok(typeof $(".mapcontainer").data("mapael") === "object", "Has mapael data" );
        assert.ok($(".mapcontainer .map .mapTooltip")[0], "Has tooltip div" );

    });

    test("Creation fail: wrong map", function(assert) {

        /* Error if wrong map name */
        assert.throws(function(){
            $(".mapcontainer").mapael({
                map: { name: "not_existing_map" }
            });
        }, "Throw error" );

        assert.notOk($(".mapcontainer svg")[0], "Map not existing" );

    });

    test("Creation fail: existing map", function(assert) {
        $(".mapcontainer").mapael({
            map: { name: "france_departments" }
        });
        assert.throws(function(){
            $(".mapcontainer").mapael({
                map: { name: "france_departments" }
            });
        }, "Throw error" );
    });

    test("Mouseover", function(assert) {
        var mouseover_async_done = assert.async(CST_NB_OF_FRANCE_DPTMT);

        /* Create the map */
        $(".mapcontainer").mapael({
            map: {
                name: "france_departments"
            }
        });

        /* mouseover event check (background changement) */
        var default_fill = $(".mapcontainer svg path:first").attr("fill");
        $(".mapcontainer svg path").each(function(id, elem) {
            var $elem = $(elem);

            $elem.trigger("mouseover");
            setTimeout(function() {
                var new_fill = $elem.attr("fill");
                assert.notEqual(default_fill, new_fill, "Check new background" );
                assert.ok($(".mapcontainer .map .mapTooltip").is( ":hidden" ), "Check tooltip hidden" );

                $elem.trigger("mouseout");
                setTimeout(function() {
                    var new_fill = $elem.attr("fill");
                    assert.equal(new_fill, default_fill, "Check old background" );
                    mouseover_async_done();
                }, 500);
            }, 500);
        });

    });

    test("Responsive", function(assert) {
        var responsive_async_done = assert.async();

        /* Create the map */
        $(".mapcontainer").mapael({
            map: {
                name: "france_departments"
            }
        });

        /* Responsive checks */
        $(".mapcontainer").width(CST_MAP_MAX_WIDTH/2);
        $(window).trigger('resize');
        setTimeout(function() {
            var $svg = $(".mapcontainer .map svg");
            assert.equal($svg.attr("width"), CST_MAP_MAX_WIDTH/2, "Check new map width size" );
            assert.equal($svg.attr("height"), CST_MAP_MAX_HEIGHT/2, "Check new map height size" );

            $(".mapcontainer").width(CST_MAP_MAX_WIDTH);
            $(window).trigger('resize');
            setTimeout(function() {
                var $svg = $(".mapcontainer .map svg");
                assert.equal($svg.attr("width"), CST_MAP_MAX_WIDTH, "Check old map width size" );
                assert.equal($svg.attr("height"), CST_MAP_MAX_HEIGHT, "Check old map height size" );
                responsive_async_done();
            }, 500);
        }, 500);

    });

});
<|endoftext|>


<commit_before>var Bird   = require('../index');
var expect = require('chai').expect;
var path   = require('path');
var oauth  = {
  consumer_key: process.env.TW_CONSUMER_KEY,
  consumer_secret: process.env.TW_CONSUMER_SECRET,
  token: process.env.TW_TEST_TOKEN,
  token_secret: process.env.TW_TEST_TOKEN_SECRET
};

describe("Bird", function(){

  describe('requestToken', function(){
    it('returns a valid oauth token', function(done){
      Bird.auth.requestToken({
        oauth: {
          consumer_key: oauth.consumer_key,
          consumer_secret: oauth.consumer_secret
        }
      }, function(err, res, body){
        expect(err).to.be.null;
        expect(res.statusCode).to.eq(200);
        done();
      });
    });
  });

  describe('Bird.timelines', function(){
    it('is a namespace for each of the twitter timeline routes', function() {
      expect(Bird.timelines).to.be.an('object');
    });

    describe("Bird.timelines.home", function(){
      it("returns a valid json response", function(done){
        Bird.timelines.home({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given oauth parameters", function(){
        expect(Bird.timelines.home).to.throw(Error);
      });
    });

    describe("Bird.timelines.mentions", function(){
      it("returns a valid json response", function(done){
        Bird.timelines.mentions({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given oauth parameters", function(){
        expect(Bird.timelines.mentions).to.throw(Error);
      });
    });

    describe("Bird.timelines.user", function(){
      it("returns a valid json response", function(done){
        Bird.timelines.user({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given oauth parameters", function(){
        expect(Bird.timelines.user).to.throw(Error);
      });
    });

    describe("Bird.timelines.retweetsOfMe", function(){
      it("returns a valid json response", function(done){
        Bird.timelines.retweetsOfMe({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given oauth parameters", function(){
        expect(Bird.timelines.retweetsOfMe).to.throw(Error);
      });
    });
  });

  describe('Bird.tweets', function(){
    it('is a namespace for each of the twitter tweets routes', function() {
      expect(Bird.tweets).to.be.an('object');
    });

    describe('Bird.tweets.retweets', function(){
      it("throws an error when not given an id parameter", function(){
        expect(function(){
          Bird.tweets.show({ oauth: oauth });
        }).to.throw(Error);
      });
    });

    describe('Bird.tweets.update', function(){
      it('sends new tweets', function(done){
        Bird.tweets.update({ oauth: oauth, status: 'Bird.tweets.update ' + Date.now() }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given an status parameter", function(){
        var fn = function(){
          Bird.tweets.update({ oauth: oauth });
        }
        expect(fn).to.throw(Error);
      });
    });

    describe("Bird.tweets.show", function(){
      it("throws an error when not given an id parameter", function(){
        var fn = function(){
          Bird.tweets.show({ oauth: oauth });
        }
        expect(fn).to.throw(Error);
      });
    });
  });

  describe('Bird.media.upload', function(){
    it('uploads the test image', function(done){
      // increase the timeout to 5s
      this.timeout(5000);

      Bird.media.upload({
        oauth: oauth,
        media: path.resolve('test/test-media.png')
      }, function(err, r, b){
        expect(r.statusCode).to.eq(200);
        done();
      });
    });

    describe('attaching an image to a tweet', function(){
      it('attaches the media by id to a new tweet', function(done){
        // increase the timeout to 5s
        this.timeout(5000);

        Bird.media.upload({
          oauth: oauth,
          media: path.resolve('test/test-media.png')
        }, function(err, r, b){
          expect(r.statusCode).to.eq(200);

          // attach media ids to from uploaded file to tweet
          Bird.tweets.update({
            oauth: oauth,
            status: 'Bird.tweets.update ' + Date.now(),
            media_ids: JSON.parse(b).media_id_string
          }, function(err, r, b){
            expect(r.statusCode).to.eq(200);
            done();
          });
        });
      });
    });
  });

  describe('Bird.application.rateLimits', function(){
    it('returns the current api limits for the application', function(done){
      Bird.application.rateLimits({ oauth: oauth }, function(err, r, b){
        expect(r.statusCode).to.eq(200);
        done();
      });
    });
  });

  describe('Bird.followers.list', function(){
    it('returns the current api limits for the application', function(done){
      Bird.followers.list({ oauth: oauth }, function(err, r, b){
        expect(r.statusCode).to.eq(200);
        done();
      });
    });
  });

  describe('Bird.followers.index', function(){
    it('returns the current api limits for the application', function(done){
      Bird.followers.index({ oauth: oauth }, function(err, r, b){
        expect(r.statusCode).to.eq(200);
        done();
      });
    });
  });

  describe('Bird.help', function(){
    it('is a namespace', function(){
      expect(Bird.help).to.be.an('object');
    });

    describe('Bird.help.configuration', function(){
      it('returns some configuration', function(done){
        Bird.help.configuration({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.help.languages', function(){
      it('returns some language info', function(done){
        Bird.help.languages({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.help.privacy', function(){
      it('returns some privacy info', function(done){
        Bird.help.privacy({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.help.tos', function(){
      it('returns the twitter terms of service', function(done){
        Bird.help.tos({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

  });

  describe('Bird.trends', function(){
    it('is a namespace', function(){
      expect(Bird.trends).to.be.an('object');
    });

    describe('Bird.trends.place', function(){
      it('returns trending places', function(done){
        Bird.trends.place({ oauth: oauth, id: 1 }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.trends.available', function(){
      it('returns available trends', function(done){
        Bird.trends.available({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.trends.closest', function(){
      it('throws when necessary params are not provided', function(){
        expect(function(){
          Bird.trends.closest({ oauth: oauth });
        }).to.throw(Error);
      });

      it('returns available trends', function(done){
        Bird.trends.closest({ oauth: oauth, lat: 0, long: 0 }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });
  });

  describe('Bird.users', function(){
    it('is a namespace', function() {
      expect(Bird.users).to.be.an('object');
    });

    describe('Bird.users.reportSpam', function(){
      it('throws when necessary params are not provided', function(){
        expect(function(){
          Bird.users.reportSpam({ oauth: oauth });
        }).to.throw(Error);
      });
    });
  });

  describe('Bird.geo', function(){
    it('is a namespace', function(){
      expect(Bird.geo).to.be.an('object');
    });
  });

});
<commit_msg>Added test for Bird.geo.place<commit_after>var Bird   = require('../index');
var expect = require('chai').expect;
var path   = require('path');
var oauth  = {
  consumer_key: process.env.TW_CONSUMER_KEY,
  consumer_secret: process.env.TW_CONSUMER_SECRET,
  token: process.env.TW_TEST_TOKEN,
  token_secret: process.env.TW_TEST_TOKEN_SECRET
};

describe("Bird", function(){

  describe('requestToken', function(){
    it('returns a valid oauth token', function(done){
      Bird.auth.requestToken({
        oauth: {
          consumer_key: oauth.consumer_key,
          consumer_secret: oauth.consumer_secret
        }
      }, function(err, res, body){
        expect(err).to.be.null;
        expect(res.statusCode).to.eq(200);
        done();
      });
    });
  });

  describe('Bird.timelines', function(){
    it('is a namespace for each of the twitter timeline routes', function() {
      expect(Bird.timelines).to.be.an('object');
    });

    describe("Bird.timelines.home", function(){
      it("returns a valid json response", function(done){
        Bird.timelines.home({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given oauth parameters", function(){
        expect(Bird.timelines.home).to.throw(Error);
      });
    });

    describe("Bird.timelines.mentions", function(){
      it("returns a valid json response", function(done){
        Bird.timelines.mentions({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given oauth parameters", function(){
        expect(Bird.timelines.mentions).to.throw(Error);
      });
    });

    describe("Bird.timelines.user", function(){
      it("returns a valid json response", function(done){
        Bird.timelines.user({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given oauth parameters", function(){
        expect(Bird.timelines.user).to.throw(Error);
      });
    });

    describe("Bird.timelines.retweetsOfMe", function(){
      it("returns a valid json response", function(done){
        Bird.timelines.retweetsOfMe({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given oauth parameters", function(){
        expect(Bird.timelines.retweetsOfMe).to.throw(Error);
      });
    });
  });

  describe('Bird.tweets', function(){
    it('is a namespace for each of the twitter tweets routes', function() {
      expect(Bird.tweets).to.be.an('object');
    });

    describe('Bird.tweets.retweets', function(){
      it("throws an error when not given an id parameter", function(){
        expect(function(){
          Bird.tweets.show({ oauth: oauth });
        }).to.throw(Error);
      });
    });

    describe('Bird.tweets.update', function(){
      it('sends new tweets', function(done){
        Bird.tweets.update({ oauth: oauth, status: 'Bird.tweets.update ' + Date.now() }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        })
      });

      it("throws an error when not given an status parameter", function(){
        var fn = function(){
          Bird.tweets.update({ oauth: oauth });
        }
        expect(fn).to.throw(Error);
      });
    });

    describe("Bird.tweets.show", function(){
      it("throws an error when not given an id parameter", function(){
        var fn = function(){
          Bird.tweets.show({ oauth: oauth });
        }
        expect(fn).to.throw(Error);
      });
    });
  });

  describe('Bird.media.upload', function(){
    it('uploads the test image', function(done){
      // increase the timeout to 5s
      this.timeout(5000);

      Bird.media.upload({
        oauth: oauth,
        media: path.resolve('test/test-media.png')
      }, function(err, r, b){
        expect(r.statusCode).to.eq(200);
        done();
      });
    });

    describe('attaching an image to a tweet', function(){
      it('attaches the media by id to a new tweet', function(done){
        // increase the timeout to 5s
        this.timeout(5000);

        Bird.media.upload({
          oauth: oauth,
          media: path.resolve('test/test-media.png')
        }, function(err, r, b){
          expect(r.statusCode).to.eq(200);

          // attach media ids to from uploaded file to tweet
          Bird.tweets.update({
            oauth: oauth,
            status: 'Bird.tweets.update ' + Date.now(),
            media_ids: JSON.parse(b).media_id_string
          }, function(err, r, b){
            expect(r.statusCode).to.eq(200);
            done();
          });
        });
      });
    });
  });

  describe('Bird.application.rateLimits', function(){
    it('returns the current api limits for the application', function(done){
      Bird.application.rateLimits({ oauth: oauth }, function(err, r, b){
        expect(r.statusCode).to.eq(200);
        done();
      });
    });
  });

  describe('Bird.followers.list', function(){
    it('returns the current api limits for the application', function(done){
      Bird.followers.list({ oauth: oauth }, function(err, r, b){
        expect(r.statusCode).to.eq(200);
        done();
      });
    });
  });

  describe('Bird.followers.index', function(){
    it('returns the current api limits for the application', function(done){
      Bird.followers.index({ oauth: oauth }, function(err, r, b){
        expect(r.statusCode).to.eq(200);
        done();
      });
    });
  });

  describe('Bird.help', function(){
    it('is a namespace', function(){
      expect(Bird.help).to.be.an('object');
    });

    describe('Bird.help.configuration', function(){
      it('returns some configuration', function(done){
        Bird.help.configuration({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.help.languages', function(){
      it('returns some language info', function(done){
        Bird.help.languages({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.help.privacy', function(){
      it('returns some privacy info', function(done){
        Bird.help.privacy({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.help.tos', function(){
      it('returns the twitter terms of service', function(done){
        Bird.help.tos({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

  });

  describe('Bird.trends', function(){
    it('is a namespace', function(){
      expect(Bird.trends).to.be.an('object');
    });

    describe('Bird.trends.place', function(){
      it('returns trending places', function(done){
        Bird.trends.place({ oauth: oauth, id: 1 }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.trends.available', function(){
      it('returns available trends', function(done){
        Bird.trends.available({ oauth: oauth }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });

    describe('Bird.trends.closest', function(){
      it('throws when necessary params are not provided', function(){
        expect(function(){
          Bird.trends.closest({ oauth: oauth });
        }).to.throw(Error);
      });

      it('returns available trends', function(done){
        Bird.trends.closest({ oauth: oauth, lat: 0, long: 0 }, function(err, r, b){
          expect(r.statusCode).to.eq(200);
          done();
        });
      });
    });
  });

  describe('Bird.users', function(){
    it('is a namespace', function() {
      expect(Bird.users).to.be.an('object');
    });

    describe('Bird.users.reportSpam', function(){
      it('throws when necessary params are not provided', function(){
        expect(function(){
          Bird.users.reportSpam({ oauth: oauth });
        }).to.throw(Error);
      });
    });
  });

  describe('Bird.geo', function(){
    it('is a namespace', function(){
      expect(Bird.geo).to.be.an('object');
    });

    describe('Bird.geo.place', function(){
      it('throws without required params', function(){
        expect(function(){
          Bird.geo.place({ oauth: oauth });
        }).to.throw(Error);
      });
    });
  });

});
<|endoftext|>


<commit_before>var Plate = require ('../lib/plate'), Test = require ('./test');

var t = new Test ();

// test 1 - 1 level of indentation, escaped {{.

t.teq ((Plate.format ('There is {{{\\nso much}}} {{=a_man|plain}} can do.\n\n' +
        '{{=us|html}} we have many friends: \n' +
        '{{-friends|friend|i;there is {{=friend|plain}}, }}...', {
  'a_man': 'Jan',
  'us': 'My friend & I',
  'friends': ['Thaddee', 'Serge', 'Marie']
})),
    'There is {{\\nso much}} Jan can do.\n\n' +
    'My friend & I we have many friends: \n' +
    'there is Thaddee, there is Serge, there is Marie, ...');

// test 2 - 2 levels of indentation.

t.teq (Plate.format ('Your base belongs to {{-us|me|i;\n' +
      '- {{-me|name|j;{{=name|plain}} }}; }}',
      {us: [['John', 'Connor'], ['Paul', 'Irish'], ['Ash', 'William']]}),
    'Your base belongs to \n- John Connor ; \n- Paul Irish ; \n' +
    '- Ash William ; ');

// compound expressions
t.teq (Plate.format ('Thaddee {{?apostles.indexOf(thaddee)!=-1|was|wasn\'t}} an apostle'
      ,{thaddee:'Thaddaeus', apostles:['Simon','Andrew','James','John','Philip'
        ,'Bartholomew','Matthew','Thomas','James','Simon','Judas','Judas']})
      ,'Thaddee wasn\'t an apostle');

// conditional macro tests.
t.teq (Plate.format ('I am{{?present| here. Hello!; out.}} Anyway, how do you do?',
                  {present: true}),
       'I am here. Hello! Anyway, how do you do?');
t.teq (Plate.format ('I am{{?present| here. Hello!; out.}} Anyway, how do you do?',
                  {present:false}),
       'I am out. Anyway, how do you do?');

// comment macro test.
t.teq (Plate.format ('There should be{{# nothing!}}...', {}),
       'There should be...');

// macro macro test.
t.teq (Plate.format ('First param{{!s; return params[0]}}: {{steh; yep...}}!', {}),
       'First param: teh!');

// macro macro macro test.
t.teq (Plate.format ('First param{{!first; return params[0]}}: {{~first|teh; yep...}}!', {}),
       'First param: teh!');

// parser tests.
t.teq (Plate.format ('Plain {{=data|plain}}.',{data:'text'}), 'Plain text.');
t.teq (Plate.format ('Html {{=data|html}}.',{data:'<text & stuff>'}),
       'Html <text & stuff>.');
t.teq (Plate.format ('Xml {{=data|xml}}.',{data:'<text & stuff>'}),
       'Xml <text & stuff>.');
t.teq (Plate.format ('XmlAttr {{=data|xmlattr}}.',{data:'<\'text\' & "stuff">'}),
       'XmlAttr <'text' & "stuff">.');
t.teq (Plate.format ('JsonString "{{=data|jsonstring}}"',
                     {data:'file "foo\\bar":\tok\nBody:\r\fdel=\b'}),
       'JsonString "file \\"foo\\\\bar\\":\\tok\\nBody:\\r\\fdel=\\b"');
t.teq (Plate.format ('Uri {{=data|uri}}.',{data:'conversion done'}),
       'Uri conversion%20done.');
t.teq (Plate.format ('Non-Uri {{=data|!uri}}.',{data:'conversion%20done'}),
       'Non-Uri conversion done.');
t.teq (Plate.format ('Int {{=data|integer}}.',{data:73.6}), 'Int 74.');
t.teq (Plate.format ('Radix {{=data|intradix|2}}.',{data:2}), 'Radix 10.');
t.teq (Plate.format ('Float {{=data|float|2}}.',{data:73.6}), 'Float 73.60.');
t.teq (Plate.format ('Exp {{=data|exp|2}}.',{data:73.6}), 'Exp 7.36e+1.');

// error test.
t.teq (Plate.format ('Nonint {{=data|integer}}.',{data:'hi'}), 'Nonint .');

// tl;dr.
t.tldr ();

<commit_msg>Another error in the lib/ → camp/ rename<commit_after>var Plate = require ('../camp/plate'), Test = require ('./test');

var t = new Test ();

// test 1 - 1 level of indentation, escaped {{.

t.teq ((Plate.format ('There is {{{\\nso much}}} {{=a_man|plain}} can do.\n\n' +
        '{{=us|html}} we have many friends: \n' +
        '{{-friends|friend|i;there is {{=friend|plain}}, }}...', {
  'a_man': 'Jan',
  'us': 'My friend & I',
  'friends': ['Thaddee', 'Serge', 'Marie']
})),
    'There is {{\\nso much}} Jan can do.\n\n' +
    'My friend & I we have many friends: \n' +
    'there is Thaddee, there is Serge, there is Marie, ...');

// test 2 - 2 levels of indentation.

t.teq (Plate.format ('Your base belongs to {{-us|me|i;\n' +
      '- {{-me|name|j;{{=name|plain}} }}; }}',
      {us: [['John', 'Connor'], ['Paul', 'Irish'], ['Ash', 'William']]}),
    'Your base belongs to \n- John Connor ; \n- Paul Irish ; \n' +
    '- Ash William ; ');

// compound expressions
t.teq (Plate.format ('Thaddee {{?apostles.indexOf(thaddee)!=-1|was|wasn\'t}} an apostle'
      ,{thaddee:'Thaddaeus', apostles:['Simon','Andrew','James','John','Philip'
        ,'Bartholomew','Matthew','Thomas','James','Simon','Judas','Judas']})
      ,'Thaddee wasn\'t an apostle');

// conditional macro tests.
t.teq (Plate.format ('I am{{?present| here. Hello!; out.}} Anyway, how do you do?',
                  {present: true}),
       'I am here. Hello! Anyway, how do you do?');
t.teq (Plate.format ('I am{{?present| here. Hello!; out.}} Anyway, how do you do?',
                  {present:false}),
       'I am out. Anyway, how do you do?');

// comment macro test.
t.teq (Plate.format ('There should be{{# nothing!}}...', {}),
       'There should be...');

// macro macro test.
t.teq (Plate.format ('First param{{!s; return params[0]}}: {{steh; yep...}}!', {}),
       'First param: teh!');

// macro macro macro test.
t.teq (Plate.format ('First param{{!first; return params[0]}}: {{~first|teh; yep...}}!', {}),
       'First param: teh!');

// parser tests.
t.teq (Plate.format ('Plain {{=data|plain}}.',{data:'text'}), 'Plain text.');
t.teq (Plate.format ('Html {{=data|html}}.',{data:'<text & stuff>'}),
       'Html <text & stuff>.');
t.teq (Plate.format ('Xml {{=data|xml}}.',{data:'<text & stuff>'}),
       'Xml <text & stuff>.');
t.teq (Plate.format ('XmlAttr {{=data|xmlattr}}.',{data:'<\'text\' & "stuff">'}),
       'XmlAttr <'text' & "stuff">.');
t.teq (Plate.format ('JsonString "{{=data|jsonstring}}"',
                     {data:'file "foo\\bar":\tok\nBody:\r\fdel=\b'}),
       'JsonString "file \\"foo\\\\bar\\":\\tok\\nBody:\\r\\fdel=\\b"');
t.teq (Plate.format ('Uri {{=data|uri}}.',{data:'conversion done'}),
       'Uri conversion%20done.');
t.teq (Plate.format ('Non-Uri {{=data|!uri}}.',{data:'conversion%20done'}),
       'Non-Uri conversion done.');
t.teq (Plate.format ('Int {{=data|integer}}.',{data:73.6}), 'Int 74.');
t.teq (Plate.format ('Radix {{=data|intradix|2}}.',{data:2}), 'Radix 10.');
t.teq (Plate.format ('Float {{=data|float|2}}.',{data:73.6}), 'Float 73.60.');
t.teq (Plate.format ('Exp {{=data|exp|2}}.',{data:73.6}), 'Exp 7.36e+1.');

// error test.
t.teq (Plate.format ('Nonint {{=data|integer}}.',{data:'hi'}), 'Nonint .');

// tl;dr.
t.tldr ();

<|endoftext|>


<commit_before>
/**
 * WPCOM module
 */

var WPCOM = require('../');
var Site = require('../lib/site');
var Media = require('../lib/media');
var util = require('./util');
var fs = require('fs');
var assert = require('assert');

/**
 * Testing data
 */

var test = require('./data');

/**
 * WPCOM instance
 */

describe('WPCOM#Site#Media', function(){

  // Create a new_media before to start the tests

  var new_media;
  before(function(done){
    util.addMedia(function(err, media) {
      if (err) throw err;

      new_media = media;
      done();
    });
  });

  describe('sync', function(){

    it('should create an `Media` instance from `Site`', function(){
      var media = WPCOM().site().media();
      assert.ok(media instanceof Media);
    });

  });

  describe('async', function(){

    describe('media.get()', function(){

      it('should get added media', function(done){
        var site = util.private_site();
        var media = site.media(test.media_id);

        media.get(function(err, info){
          if (err) throw err;

          assert.equal(3, info.id);
          done();
        });
      });

    });

    describe('media.addFiles([fs])', function(){

      it('should create a new media from a file', function(done){
        var site = util.private_site();

        // pass streams
        var files = [];
        for (var i = 0; i < test.new_media_data.files.length; i++) {
          files.push(fs.createReadStream(test.new_media_data.files[i]));
        }

        site
        .media()
        .addFiles(files, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.ok(data.media instanceof Array);
          assert.equal(test.new_media_data.files.length, data.media.length);
          done();
        });

      });

    });

    describe('media.addUrls([\'url1\', \'url2\'])', function(){

      it('should create a new media', function(done){
        var site = util.private_site();

        site
        .media()
        .addUrls(test.new_media_data.media_urls, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.ok(data.media instanceof Array);
          assert.equal(test.new_media_data.media_urls.length, data.media.length);
          done();
        });

      });

    });

  });

});
<commit_msg>test: add media.delete() test<commit_after>
/**
 * WPCOM module
 */

var WPCOM = require('../');
var Site = require('../lib/site');
var Media = require('../lib/media');
var util = require('./util');
var fs = require('fs');
var assert = require('assert');

/**
 * Testing data
 */

var test = require('./data');

/**
 * WPCOM instance
 */

describe('WPCOM#Site#Media', function(){

  // Create a new_media before to start the tests

  var new_media;
  before(function(done){
    util.addMedia(function(err, media) {
      if (err) throw err;

      new_media = media;
      done();
    });
  });

  describe('sync', function(){

    it('should create an `Media` instance from `Site`', function(){
      var media = WPCOM().site().media();
      assert.ok(media instanceof Media);
    });

  });

  describe('async', function(){

    describe('media.get()', function(){

      it('should get added media', function(done){
        var site = util.private_site();
        var media = site.media(test.media_id);

        media.get(function(err, info){
          if (err) throw err;

          assert.equal(3, info.id);
          done();
        });
      });

    });

    describe('media.addFiles([fs])', function(){

      it('should create a new media from a file', function(done){
        var site = util.private_site();

        // pass streams
        var files = [];
        for (var i = 0; i < test.new_media_data.files.length; i++) {
          files.push(fs.createReadStream(test.new_media_data.files[i]));
        }

        site
        .media()
        .addFiles(files, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.ok(data.media instanceof Array);
          assert.equal(test.new_media_data.files.length, data.media.length);
          done();
        });

      });

    });

    describe('media.addUrls([\'url1\', \'url2\'])', function(){

      it('should create a new media', function(done){
        var site = util.private_site();

        site
        .media()
        .addUrls(test.new_media_data.media_urls, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.ok(data.media instanceof Array);
          assert.equal(test.new_media_data.media_urls.length, data.media.length);
          done();
        });

      });

    });

    describe('media.delete()', function(){

      it('should delete a media', function(done){
        var site = util.private_site();

        site
        .media(new_media.media[0].id)
        .del(function(err, data){
          if (err) throw err;

          assert.equal(new_media.media[0].id, data.id);
          done();
        });

      });

    });

  });

});
<|endoftext|>