<commit_before>var Convex = require(__dirname + '/../../src/shapes/Convex');
var vec2 =   require(__dirname + '/../../src/math/vec2');

exports.construct = function(test){
    new Convex();

    test.throws(function(){
        var c = new Convex([[-1,-1],
                            [-1, 1],
                            [ 1, 1],
                            [ 1,-1]]);
    },"Should throw exception on clockwise winding.");

    test.done();
};

exports.computeAABB = function(test){
    // STUB
    test.done();
};

exports.computeMomentOfInertia = function(test){
    var w = 2,
        h = 1;
    var c = new Convex([
        [-w/2,-h/2],
        [ w/2,-h/2],
        [ w/2, h/2],
        [-w/2, h/2],
    ]);
    var mass = 1;
    var I = c.computeMomentOfInertia(mass);
    var boxInertia = mass*(h*h+w*w)/12;
    test.ok(Math.abs(I-boxInertia) < 0.01,'Convex dont compute square inertia correctly');
    test.done();
};

exports.triangleArea = function(test){
    test.equal( Convex.triangleArea([0, 0], [1, 0], [1, 1]),  1/2);
    test.done();
};

exports.updateArea = function(test){
    var c = new Convex([[-1,-1],
                        [ 1,-1],
                        [ 1, 1],
                        [-1, 1]]);
    c.updateArea();
    test.equal(c.area, 4)

    var c = new Convex([
        [990, 0],
        [990, 10],
        [0, 10],
        [0, 0]
    ]);
    test.equal(c.area,9900);

    test.done();
};

exports.updateBoundingRadius = function(test){
    // STUB
    test.done();
};

exports.updateCenterOfMass = function(test){

    // Test with box
    var c = new Convex([[-1,-1],
                        [ 1,-1],
                        [ 1, 1],
                        [-1, 1]]);
    c.updateCenterOfMass();
    test.equal(c.centerOfMass[0],0);
    test.equal(c.centerOfMass[1],0);

    // rotate and translate all points
    var offset = vec2.fromValues(1,1);
    for(var i=0; i!==c.vertices.length; i++){
        var v = c.vertices[i];
        vec2.rotate(v,v,Math.PI/4);
        vec2.add(v,v,offset);
    }

    c.updateCenterOfMass();

    test.ok(Math.abs(c.centerOfMass[0]-offset[0]) < 0.01);
    test.ok(Math.abs(c.centerOfMass[1]-offset[1]) < 0.01);

    test.done();
};

exports.updateTriangles = function(test){
    // STUB
    test.done();
};

<commit_msg>more convex tests<commit_after>var Convex = require(__dirname + '/../../src/shapes/Convex')
,   vec2 =   require(__dirname + '/../../src/math/vec2')
,   AABB =   require(__dirname + '/../../src/collision/AABB')

exports.construct = function(test){
    new Convex();

    test.throws(function(){
        var c = new Convex([[-1,-1],
                            [-1, 1],
                            [ 1, 1],
                            [ 1,-1]]);
    },"Should throw exception on clockwise winding.");

    test.done();
};

exports.computeAABB = function(test){
    var w = 2,
        h = 1;
    var c = new Convex([
        [-w/2,-h/2],
        [ w/2,-h/2],
        [ w/2, h/2],
        [-w/2, h/2],
    ]);

    var aabb = new AABB();
    c.computeAABB(aabb,[1,2],0);

    test.equal(aabb.lowerBound[0],-w/2 + 1);
    test.equal(aabb.lowerBound[1],-h/2 + 2);
    test.equal(aabb.upperBound[0], w/2 + 1);
    test.equal(aabb.upperBound[1], h/2 + 2);

    test.done();
};

exports.computeMomentOfInertia = function(test){
    var w = 2,
        h = 1;
    var c = new Convex([
        [-w/2,-h/2],
        [ w/2,-h/2],
        [ w/2, h/2],
        [-w/2, h/2],
    ]);
    var mass = 1;
    var I = c.computeMomentOfInertia(mass);
    var boxInertia = mass*(h*h+w*w)/12;
    test.ok(Math.abs(I-boxInertia) < 0.01,'Convex dont compute square inertia correctly');
    test.done();
};

exports.triangleArea = function(test){
    test.equal( Convex.triangleArea([0, 0], [1, 0], [1, 1]),  1/2);
    test.done();
};

exports.updateArea = function(test){
    var c = new Convex([[-1,-1],
                        [ 1,-1],
                        [ 1, 1],
                        [-1, 1]]);
    c.updateArea();
    test.equal(c.area, 4)

    var c = new Convex([
        [990, 0],
        [990, 10],
        [0, 10],
        [0, 0]
    ]);
    test.equal(c.area,9900);

    test.done();
};

exports.updateBoundingRadius = function(test){
    // STUB
    test.done();
};

exports.updateCenterOfMass = function(test){

    // Test with box
    var c = new Convex([[-1,-1],
                        [ 1,-1],
                        [ 1, 1],
                        [-1, 1]]);
    c.updateCenterOfMass();
    test.equal(c.centerOfMass[0],0);
    test.equal(c.centerOfMass[1],0);

    // rotate and translate all points
    var offset = vec2.fromValues(1,1);
    for(var i=0; i!==c.vertices.length; i++){
        var v = c.vertices[i];
        vec2.rotate(v,v,Math.PI/4);
        vec2.add(v,v,offset);
    }

    c.updateCenterOfMass();

    test.ok(Math.abs(c.centerOfMass[0]-offset[0]) < 0.01);
    test.ok(Math.abs(c.centerOfMass[1]-offset[1]) < 0.01);

    test.done();
};

exports.updateTriangles = function(test){
    // STUB
    test.done();
};

<|endoftext|>


<commit_before>/*
 *  ITachIRBridge.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-06-27
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

var iotdb = require('iotdb');
var _ = iotdb._;
var bunyan = iotdb.bunyan;

var itach = require('node-itach');
var arp = require('iotdb-arp');

var logger = bunyan.createLogger({
    name: 'homestar-itach-ir',
    module: 'ITachIRBridge',
});

/**
 *  See {iotdb.bridge.Bridge#Bridge} for documentation.
 *

 *  @param {object|undefined} native
 *  only used for instances, should be
 */
var ITachIRBridge = function (initd, native) {
    var self = this;

    self.initd = _.defaults(initd,
        iotdb.keystore().get("bridges/ITachIRBridge/initd"), {
            host: null,
            mac: null,
            arp: true,
            ipd: {},
        }
    );
    self.native = native;
    self.connectd = {
        data_out: function(paramd) {
        },
    }

    if (self.native) {
        self.queue = _.queue("ITachIRBridge");
    }

    self.arping = false;
};

ITachIRBridge.prototype = new iotdb.Bridge();

ITachIRBridge.prototype.name = function () {
    return "ITachIRBridge";
};

/* --- lifecycle --- */

/**
 *  See {iotdb.bridge.Bridge#discover} for documentation.
 */
ITachIRBridge.prototype.discover = function () {
    var self = this;

    logger.info({
        method: "discover"
    }, "called");

    if (self.initd.host && self.initd.mac) {
        self._discover_host(self.initd);
    } else if (self.initd.arp) {
        self._discover_arp();
    }
};

ITachIRBridge.prototype._discover_arp = function () {
    var self = this;

    if (self.arping) {
        return;
    }
    self.arping = true;

    logger.info({
        method: "_discover_arp",
        initd: self.initd,
    }, "called");

    arp.browser({
        verbose: self.initd.verbose,
        poll: 3 * 60,
    }, function (error, arpd) {
        if (error) {
            return;
        } else if (!arpd) {
            return
        }

        if (!arpd.mac.match(/^00:0C:1E:/)) {
            return;
        } if (self.initd.ipd[arpd.ip]) {
            return;
        }

        self.initd.ipd[arpd.ip] = true;

        self._discover_host(_.defaults({
            host: arpd.ip,
            mac: arpd.mac,
            probe: false,
            retry: 0,
        }, self.initd));
    });
};

ITachIRBridge.prototype._discover_host = function (arpd) {
    var self = this;
    self.discovered(new ITachIRBridge(_.defaults(arpd, self.initd), {}));
};

/**
 *  See {iotdb.bridge.Bridge#connect} for documentation.
 */
ITachIRBridge.prototype.connect = function (connectd) {
    var self = this;
    if (!self.native) {
        return;
    }

    self._validate_connect(connectd);

    self.connectd = _.defaults(connectd, self.connectd, {});
};

ITachIRBridge.prototype._forget = function () {
    var self = this;
    if (!self.native) {
        return;
    }

    logger.info({
        method: "_forget"
    }, "called");

    self.initd.ipd[self.initd.host] = false;

    self.native = null;
    self.pulled();
};

/**
 *  See {iotdb.bridge.Bridge#disconnect} for documentation.
 */
ITachIRBridge.prototype.disconnect = function () {
    var self = this;
    if (!self.native || !self.native) {
        return;
    }

    self._forget();
};

/* --- data --- */

/**
 *  See {iotdb.bridge.Bridge#push} for documentation.
 */
ITachIRBridge.prototype.push = function (pushd, done) {
    var self = this;
    if (!self.native) {
        done(new Error("not connected"));
        return;
    }

    self._validate_push(pushd);

    if (!self.connectd.data_out) {
        done(new Error("'data_out' not implemented"));
        return;
    }

    logger.info({
        method: "push",
        pushd: pushd
    }, "push");

    var paramd = {
        rawd: {},
        cookd: pushd,
        scratchd: self.scratchd,
    };
    self.connectd.data_out(paramd);

    var irs = paramd.rawd.irs;
    if (!irs) {
        done();
        return;
    }

    var count = irs.length;

    irs.map(function(ir) {
        var qitem = {
            run: function () {
                self._itach().send({
                    ir: ir,
                    module: "3"
                }, function callback(error) {
                    if (error) {
                        console.log("#", error);
                    }
                });

                self.queue.finished(qitem);
            },
            coda: function() {
                if (--count === 0) {
                    done();
                }
            },
        };
        self.queue.add(qitem);
    });
};

/**
 *  See {iotdb.bridge.Bridge#pull} for documentation.
 */
ITachIRBridge.prototype.pull = function () {
    var self = this;
    if (!self.native) {
        return;
    }
};

/* --- state --- */

/**
 *  See {iotdb.bridge.Bridge#meta} for documentation.
 */
ITachIRBridge.prototype.meta = function () {
    var self = this;
    if (!self.native) {
        return;
    }

    return {
        "iot:thing-id": _.id.thing_urn.unique("ITachIR", self.initd.mac.replace(/:/g, '')),
        "schema:name": "ITachIR",

        // "iot:thing-number": self.initd.number,
        // "iot:device-id": _.id.thing_urn.unique("ITachIR", self.native.uuid),
        // "schema:manufacturer": "",
        // "schema:model": "",
    };
};

/**
 *  See {iotdb.bridge.Bridge#reachable} for documentation.
 */
ITachIRBridge.prototype.reachable = function () {
    return this.native !== null;
};

/**
 *  See {iotdb.bridge.Bridge#configure} for documentation.
 */
ITachIRBridge.prototype.configure = function (app) {};

/* -- internals -- */
var _itachd = {};

/**
 *  If you need a singleton to access the library
 */
ITachIRBridge.prototype._itach = function () {
    var self = this;
    var ip = self.initd.host;

    if (!_itachd[ip]) {
        _itachd[ip] = new itach({
            host: ip,
        });
    };

    return _itachd[ip];
};

/*
 *  API
 */
exports.Bridge = ITachIRBridge;

<commit_msg>remove bunyan reference<commit_after>/*
 *  ITachIRBridge.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-06-27
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

var iotdb = require('iotdb');
var _ = iotdb._;

var itach = require('node-itach');
var arp = require('iotdb-arp');

var logger = iotdb.logger({
    name: 'homestar-itach-ir',
    module: 'ITachIRBridge',
});

/**
 *  See {iotdb.bridge.Bridge#Bridge} for documentation.
 *

 *  @param {object|undefined} native
 *  only used for instances, should be
 */
var ITachIRBridge = function (initd, native) {
    var self = this;

    self.initd = _.defaults(initd,
        iotdb.keystore().get("bridges/ITachIRBridge/initd"), {
            host: null,
            mac: null,
            arp: true,
            ipd: {},
        }
    );
    self.native = native;
    self.connectd = {
        data_out: function(paramd) {
        },
    }

    if (self.native) {
        self.queue = _.queue("ITachIRBridge");
    }

    self.arping = false;
};

ITachIRBridge.prototype = new iotdb.Bridge();

ITachIRBridge.prototype.name = function () {
    return "ITachIRBridge";
};

/* --- lifecycle --- */

/**
 *  See {iotdb.bridge.Bridge#discover} for documentation.
 */
ITachIRBridge.prototype.discover = function () {
    var self = this;

    logger.info({
        method: "discover"
    }, "called");

    if (self.initd.host && self.initd.mac) {
        self._discover_host(self.initd);
    } else if (self.initd.arp) {
        self._discover_arp();
    }
};

ITachIRBridge.prototype._discover_arp = function () {
    var self = this;

    if (self.arping) {
        return;
    }
    self.arping = true;

    logger.info({
        method: "_discover_arp",
        initd: self.initd,
    }, "called");

    arp.browser({
        verbose: self.initd.verbose,
        poll: 3 * 60,
    }, function (error, arpd) {
        if (error) {
            return;
        } else if (!arpd) {
            return
        }

        if (!arpd.mac.match(/^00:0C:1E:/)) {
            return;
        } if (self.initd.ipd[arpd.ip]) {
            return;
        }

        self.initd.ipd[arpd.ip] = true;

        self._discover_host(_.defaults({
            host: arpd.ip,
            mac: arpd.mac,
            probe: false,
            retry: 0,
        }, self.initd));
    });
};

ITachIRBridge.prototype._discover_host = function (arpd) {
    var self = this;
    self.discovered(new ITachIRBridge(_.defaults(arpd, self.initd), {}));
};

/**
 *  See {iotdb.bridge.Bridge#connect} for documentation.
 */
ITachIRBridge.prototype.connect = function (connectd) {
    var self = this;
    if (!self.native) {
        return;
    }

    self._validate_connect(connectd);

    self.connectd = _.defaults(connectd, self.connectd, {});
};

ITachIRBridge.prototype._forget = function () {
    var self = this;
    if (!self.native) {
        return;
    }

    logger.info({
        method: "_forget"
    }, "called");

    self.initd.ipd[self.initd.host] = false;

    self.native = null;
    self.pulled();
};

/**
 *  See {iotdb.bridge.Bridge#disconnect} for documentation.
 */
ITachIRBridge.prototype.disconnect = function () {
    var self = this;
    if (!self.native || !self.native) {
        return;
    }

    self._forget();
};

/* --- data --- */

/**
 *  See {iotdb.bridge.Bridge#push} for documentation.
 */
ITachIRBridge.prototype.push = function (pushd, done) {
    var self = this;
    if (!self.native) {
        done(new Error("not connected"));
        return;
    }

    self._validate_push(pushd);

    if (!self.connectd.data_out) {
        done(new Error("'data_out' not implemented"));
        return;
    }

    logger.info({
        method: "push",
        pushd: pushd
    }, "push");

    var paramd = {
        rawd: {},
        cookd: pushd,
        scratchd: self.scratchd,
    };
    self.connectd.data_out(paramd);

    var irs = paramd.rawd.irs;
    if (!irs) {
        done();
        return;
    }

    var count = irs.length;

    irs.map(function(ir) {
        var qitem = {
            run: function () {
                self._itach().send({
                    ir: ir,
                    module: "3"
                }, function callback(error) {
                    if (error) {
                        console.log("#", error);
                    }
                });

                self.queue.finished(qitem);
            },
            coda: function() {
                if (--count === 0) {
                    done();
                }
            },
        };
        self.queue.add(qitem);
    });
};

/**
 *  See {iotdb.bridge.Bridge#pull} for documentation.
 */
ITachIRBridge.prototype.pull = function () {
    var self = this;
    if (!self.native) {
        return;
    }
};

/* --- state --- */

/**
 *  See {iotdb.bridge.Bridge#meta} for documentation.
 */
ITachIRBridge.prototype.meta = function () {
    var self = this;
    if (!self.native) {
        return;
    }

    return {
        "iot:thing-id": _.id.thing_urn.unique("ITachIR", self.initd.mac.replace(/:/g, '')),
        "schema:name": "ITachIR",

        // "iot:thing-number": self.initd.number,
        // "iot:device-id": _.id.thing_urn.unique("ITachIR", self.native.uuid),
        // "schema:manufacturer": "",
        // "schema:model": "",
    };
};

/**
 *  See {iotdb.bridge.Bridge#reachable} for documentation.
 */
ITachIRBridge.prototype.reachable = function () {
    return this.native !== null;
};

/**
 *  See {iotdb.bridge.Bridge#configure} for documentation.
 */
ITachIRBridge.prototype.configure = function (app) {};

/* -- internals -- */
var _itachd = {};

/**
 *  If you need a singleton to access the library
 */
ITachIRBridge.prototype._itach = function () {
    var self = this;
    var ip = self.initd.host;

    if (!_itachd[ip]) {
        _itachd[ip] = new itach({
            host: ip,
        });
    };

    return _itachd[ip];
};

/*
 *  API
 */
exports.Bridge = ITachIRBridge;

<|endoftext|>


<commit_before>describe("Hilo DOM", function () {
  it('should return empty when selecting nothing', function() {
    expect(Hilo("").length).toEqual(0);
  });

  it('should return a (specialized) DOM Node List when passed a string', function () {
    var $elm, elmArr = [], _i, _j, dElm, dElmArr = [];

    $elm = Hilo('div');

    for (_i = 0; _i < $elm.length; _i++) {
      elmArr[_i] = $elm[_i];
    }

    dElm = Hilo('div');

    for (_j = 0; _j < dElm.length; _j++) {
      dElmArr[_j] = dElm[_j];
    }

    expect(elmArr).toEqual(dElmArr);
  });
});

describe("DOM fx", function () {
  it('.hide() should set HTMLElement.style.display to none', function () {
    var el;
    el = document.getElementsByTagName('div')[0];
    Hilo('div').hide();
    expect(el.style.display).toEqual('none');
  });
  it('.show() should set HTMLElement.style.display apart from none', function () {
    var el;
    Hilo('div').show();
    el = document.getElementsByTagName('div')[0];
    expect(el.style.display).not.toEqual('none');
  });
  it('.disappear() should set HTMLElement.style.visibility to "hidden"', function () {
    var el;
    el = document.getElementsByTagName('div')[0];
    Hilo('div').disappear();
    expect(el.style.visibility).toEqual('hidden');
  });
  it('.appear() should set HTMLElement.style.visibility to "visible"', function () {
    var el;
    Hilo('div').appear();
    el = document.getElementsByTagName('div')[0];
    expect(el.style.visibility).toEqual('visible');
  });
});

describe("DOM Methods", function () {
  describe('.html()', function () {
    it("should set the innerHTML of an element", function () {
      var el = document.createElement('div')
        , he = $.create('div')
        , innerContent = 'Hello World';

      el.innerHTML = innerContent;
      he.html(innerContent);

      return el.innerHTML === he[0].innerHTML;
    });
    it("should return the innerHTML when no content is passed", function() {
      var el = document.createElement('div')
        , he
        , innerContent;

      el.innerHTML = innerContent;

      he = Hilo(el);

      return he.html() === innerContent;
    });
  });
  describe('.append()', function() {
    it('should append content', function () {
      var el = document.createElement('div');

      el.innerHTML = "Hello";

      Hilo(el).append(" World");

      expect(el.innerHTML).toEqual("Hello World");
    });
    it('should handle empty parameter', function () {
      var el = document.createElement('div');

      el.innerHTML = "Hello World";

      Hilo(el).append("");

      expect(el.innerHTML).toEqual("Hello World");
    });
  });
  describe('.prepend()', function() {
    it('should prepend content', function () {
      var el = document.createElement('div');

      el.innerHTML = "World";

      Hilo(el).prepend("Hello ");

      expect(el.innerHTML).toEqual("Hello World");
    });
    it('should handle empty parameter', function () {
      var el = document.createElement('div');

      el.innerHTML = "Hello World";

      Hilo(el).prepend("");

      expect(el.innerHTML).toEqual("Hello World");
    });
  });
  describe('.attr()', function() {
    it('should set an attribute', function() {
      var el = document.createElement('div');

      Hilo(el).attr("hidden", "yes");

      expect(el.getAttribute("hidden")).toEqual("yes");
    });
    it('should get an attribute', function() {
      var el = document.createElement('div');

      el.setAttribute("shown", "yes");

      expect(Hilo(el).attr("shown")).toEqual("yes");
    });
    it('should return null in case of empty parameter', function() {
      var el = document.createElement('div');

      el.setAttribute("shown", "yes");

      expect(Hilo(el).attr("")).toEqual(null);
    });
  });
  describe('.addClass()', function() {
    it('should add a class', function () {
      var el = document.createElement('div');
      Hilo(el).addClass('box');
      return el.className.split('box').length > 1;
    });
    it("should accept an array", function() {
      var el = document.createElement('div')
        , classes = ['box', 'big', 'red'];

      Hilo(el).addClass(classes);

      function hasClass (s, name) {
        return s.className.split(name).length > 1;
      }

      return hasClass(el, 'box') && hasClass(el, 'big') && hasClass(el, 'red');
    });
    it("should accept a string of separated values", function() {
      var el = document.createElement('div')
        , classes = 'box big red';

      Hilo(el).addClass(classes);

      function hasClass (s, name) {
        return s.className.split(name).length > 1;
      }

      return hasClass(el, 'box') && hasClass(el, 'big') && hasClass(el, 'red');
    });
  });
  describe('.removeClass()', function() {
    it('should remove a class', function () {
      var el = document.createElement('div');
      el.className += 'box';
      Hilo(el).removeClass('box');
      return el.className.split('box').length === 1;
    });
    it("should accept an array", function() {
      var el = document.createElement('div')
        , classes = ['box', 'big', 'red'];

      el.className += 'box big blue red';

      Hilo(el).removeClass(classes);

      function hasClass (s, name) {
        return s.className.split(name).length > 1;
      }

      return !(hasClass(el, 'box') || hasClass(el, 'big') || hasClass(el, 'red'));
    });
    it("should accept a string of separated values", function() {
      var el = document.createElement('div')
        , classes = 'box big red';

      el.className += 'box big blue red';

      Hilo(el).removeClass(classes);

      function hasClass (s, name) {
        return s.className.split(name).length > 1;
      }

      return !(hasClass(el, 'box') && hasClass(el, 'big') && hasClass(el, 'red'));
    });
  });
  describe('.css()', function () {
    it('should set css of an element', function () {
      var el = document.createElement('div')
        , styl = el.style
        , prop = 'background-color'
        , val = 'green';

      Hilo(el).css(prop, val);

      expect(el.style['backgroundColor']).toEqual(val);
    });
    it('should set multiple css props. at one', function () {
      var el = document.createElement('div')
        , props = {
          'background-color': 'green',
          'color': 'red',
          'margin-top': 6
        };

      Hilo(el).css(props);

      expect(el.style.backgroundColor).toEqual('green');
      expect(el.style.color).toEqual('red');
      expect(el.style.marginTop).toEqual('6px');
    });
    it('should get css val of prop. of an element', function () {
      var el = document.createElement('div')
        , styl = el.style
        , prop = 'margin'
        , val = '10px';

      el.style[prop] = val;

      expect(Hilo(el).css(prop)).toEqual(val);
    });
  });
  describe('.empty()', function() {
    it('should set innerHTML to ""', function() {
      var el = document.createElement("div");

      el.innerHTML = "
Lorem ipsum dolor sit amet";

      Hilo(el).empty();

      expect(el.innerHTML).toEqual("");
    });
  });
  describe('.parent()', function () {
    it('should get the parent element', function () {
      var parent = document.createElement("div")
        , child = document.createElement("span");

      child.innerHTML = "Hello World!";

      parent.appendChild(child);

      expect(Hilo(child).parent()[0]).toEqual(parent);
    });
  });
  describe('.parents()', function () {
    it('should get the parent elements of all elements', function () {
      var parent1 = document.createElement("div")
        , child1 = document.createElement("span")
        , parent2 = document.createElement("div")
        , child2 = document.createElement("span");

      parent1.appendChild(child1);
      parent2.appendChild(child2);

      expect(Hilo([child1, child2]).parents().get()).toEqual([parent1, parent2]);
    });
  });
});<commit_msg>Update test specs: DOM<commit_after>describe("Hilo DOM", function () {
  it('should return empty when selecting nothing', function() {
    expect(Hilo("").length).toEqual(0);
  });

  it('should return a (specialized) DOM Node List when passed a string', function () {
    var $elm, elmArr = [], _i, _j, dElm, dElmArr = [];

    $elm = Hilo('div');

    for (_i = 0; _i < $elm.length; _i++) {
      elmArr[_i] = $elm[_i];
    }

    dElm = Hilo('div');

    for (_j = 0; _j < dElm.length; _j++) {
      dElmArr[_j] = dElm[_j];
    }

    expect(elmArr).toEqual(dElmArr);
  });
});

describe("DOM fx", function () {
  it('.hide() should set HTMLElement.style.display to none', function () {
    var el;
    el = document.getElementsByTagName('div')[0];
    Hilo('div').hide();
    expect(el.style.display).toEqual('none');
  });
  it('.show() should set HTMLElement.style.display apart from none', function () {
    var el;
    Hilo('div').show();
    el = document.getElementsByTagName('div')[0];
    expect(el.style.display).not.toEqual('none');
  });
  it('.disappear() should set HTMLElement.style.visibility to "hidden"', function () {
    var el;
    el = document.getElementsByTagName('div')[0];
    Hilo('div').disappear();
    expect(el.style.visibility).toEqual('hidden');
  });
  it('.appear() should set HTMLElement.style.visibility to "visible"', function () {
    var el;
    Hilo('div').appear();
    el = document.getElementsByTagName('div')[0];
    expect(el.style.visibility).toEqual('visible');
  });
});

describe("DOM Methods", function () {
  describe('.html()', function () {
    it("should set the innerHTML of an element", function () {
      var el = document.createElement('div')
        , he = Hilo.create('div')
        , innerContent = 'Hello World';

      el.innerHTML = innerContent;
      he.html(innerContent);

      return el.innerHTML === he[0].innerHTML;
    });
    it("should return the innerHTML when no content is passed", function() {
      var el = document.createElement('div')
        , he
        , innerContent;

      el.innerHTML = innerContent;

      he = Hilo(el);

      return he.html() === innerContent;
    });
  });
  describe('.append()', function() {
    it('should append content', function () {
      var el = document.createElement('div');

      el.innerHTML = "Hello";

      Hilo(el).append(" World");

      expect(el.innerHTML).toEqual("Hello World");
    });
    it('should handle empty parameter', function () {
      var el = document.createElement('div');

      el.innerHTML = "Hello World";

      Hilo(el).append("");

      expect(el.innerHTML).toEqual("Hello World");
    });
  });
  describe('.prepend()', function() {
    it('should prepend content', function () {
      var el = document.createElement('div');

      el.innerHTML = "World";

      Hilo(el).prepend("Hello ");

      expect(el.innerHTML).toEqual("Hello World");
    });
    it('should handle empty parameter', function () {
      var el = document.createElement('div');

      el.innerHTML = "Hello World";

      Hilo(el).prepend("");

      expect(el.innerHTML).toEqual("Hello World");
    });
  });
  describe('.attr()', function() {
    it('should set an attribute', function() {
      var el = document.createElement('div');

      Hilo(el).attr("hidden", "yes");

      expect(el.getAttribute("hidden")).toEqual("yes");
    });
    it('should get an attribute', function() {
      var el = document.createElement('div');

      el.setAttribute("shown", "yes");

      expect(Hilo(el).attr("shown")).toEqual("yes");
    });
    it('should return null in case of empty parameter', function() {
      var el = document.createElement('div');

      el.setAttribute("shown", "yes");

      expect(Hilo(el).attr("")).toEqual(null);
    });
  });
  describe('.addClass()', function() {
    it('should add a class', function () {
      var el = document.createElement('div');
      Hilo(el).addClass('box');
      return el.className.split('box').length > 1;
    });
    it("should accept an array", function() {
      var el = document.createElement('div')
        , classes = ['box', 'big', 'red'];

      Hilo(el).addClass(classes);

      function hasClass (s, name) {
        return s.className.split(name).length > 1;
      }

      return hasClass(el, 'box') && hasClass(el, 'big') && hasClass(el, 'red');
    });
    it("should accept a string of separated values", function() {
      var el = document.createElement('div')
        , classes = 'box big red';

      Hilo(el).addClass(classes);

      function hasClass (s, name) {
        return s.className.split(name).length > 1;
      }

      return hasClass(el, 'box') && hasClass(el, 'big') && hasClass(el, 'red');
    });
  });
  describe('.removeClass()', function() {
    it('should remove a class', function () {
      var el = document.createElement('div');
      el.className += 'box';
      Hilo(el).removeClass('box');
      return el.className.split('box').length === 1;
    });
    it("should accept an array", function() {
      var el = document.createElement('div')
        , classes = ['box', 'big', 'red'];

      el.className += 'box big blue red';

      Hilo(el).removeClass(classes);

      function hasClass (s, name) {
        return s.className.split(name).length > 1;
      }

      return !(hasClass(el, 'box') || hasClass(el, 'big') || hasClass(el, 'red'));
    });
    it("should accept a string of separated values", function() {
      var el = document.createElement('div')
        , classes = 'box big red';

      el.className += 'box big blue red';

      Hilo(el).removeClass(classes);

      function hasClass (s, name) {
        return s.className.split(name).length > 1;
      }

      return !(hasClass(el, 'box') && hasClass(el, 'big') && hasClass(el, 'red'));
    });
  });
  describe('.css()', function () {
    it('should set css of an element', function () {
      var el = document.createElement('div')
        , styl = el.style
        , prop = 'background-color'
        , val = 'green';

      Hilo(el).css(prop, val);

      expect(el.style['backgroundColor']).toEqual(val);
    });
    it('should set multiple css props. at one', function () {
      var el = document.createElement('div')
        , props = {
          'background-color': 'green',
          'color': 'red',
          'margin-top': 6
        };

      Hilo(el).css(props);

      expect(el.style.backgroundColor).toEqual('green');
      expect(el.style.color).toEqual('red');
      expect(el.style.marginTop).toEqual('6px');
    });
    it('should get css val of prop. of an element', function () {
      var el = document.createElement('div')
        , styl = el.style
        , prop = 'margin'
        , val = '10px';

      el.style[prop] = val;

      expect(Hilo(el).css(prop)).toEqual(val);
    });
  });
  describe('.empty()', function() {
    it('should set innerHTML to ""', function() {
      var el = document.createElement("div");

      el.innerHTML = "
Lorem ipsum dolor sit amet";

      Hilo(el).empty();

      expect(el.innerHTML).toEqual("");
    });
  });
  describe('.parent()', function () {
    it('should get the parent element', function () {
      var parent = document.createElement("div")
        , child = document.createElement("span");

      child.innerHTML = "Hello World!";

      parent.appendChild(child);

      expect(Hilo(child).parent()[0]).toEqual(parent);
    });
  });
  describe('.parents()', function () {
    it('should get the parent elements of all elements', function () {
      var parent1 = document.createElement("div")
        , child1 = document.createElement("span")
        , parent2 = document.createElement("div")
        , child2 = document.createElement("span");

      parent1.appendChild(child1);
      parent2.appendChild(child2);

      expect(Hilo([child1, child2]).parents().get()).toEqual([parent1, parent2]);
    });
  });
});<|endoftext|>


<commit_before>describe('The Mox library', function () {

  beforeEach(function () {
    angular.module('test', []);
    angular.module('test2', []);
  });

  describe('module()', function () {
    it('should pass the module functions to angular-mock.module', function () {
      spyOn(angular.mock.module, 'apply').and.callThrough();

      var configFn = function ($provide) {};
      mox.module('test', configFn, 'test2').run();
      expect(angular.mock.module.apply).toHaveBeenCalledWith(window, ['test', configFn, 'test2']);
    });

    it('should initialize the injector', function () {
      spyOn(angular.mock, 'inject').and.callThrough();
      mox.module('test', function ($provide) {}, 'test2').run();
      expect(angular.mock.inject).toHaveBeenCalled();
    });

  });
});
<commit_msg>Added spec for mockConstants<commit_after>describe('The Mox library', function () {

  beforeEach(function () {
    angular.module('test', ['test1a'])
      .constant('constant', 'c1');
    angular.module('test1a', []);
    angular.module('test2', []);
  });

  describe('module()', function () {
    it('should pass the module functions to angular-mock.module', function () {
      spyOn(angular.mock.module, 'apply').and.callThrough();

      var configFn = function ($provide) {};
      mox.module('test', configFn, 'test2').run();
      expect(angular.mock.module.apply).toHaveBeenCalledWith(window, ['test', configFn, 'test2']);
    });

    it('should initialize the injector', function () {
      spyOn(angular.mock, 'inject').and.callThrough();
      mox.module('test', function ($provide) {}, 'test2').run();
      expect(angular.mock.inject).toHaveBeenCalled();
    });

  });

  describe('mockConstants()', function () {
    it('should mock a constant which is mocked for the same module as the original constant', function () {
      mox
        .module('test')
        .mockConstants('constant', 'newConstant')
        .run();

      expect(mox.inject('constant')).toEqual('newConstant');
    });
  });
});
<|endoftext|>


<commit_before>describe('setValue', () => {
    const input = 'input[name="a"]'

    it('should reset value before setting it', async function () {
        await this.client.setValue(input, 'b').setValue(input, 'c');
        (await this.client.getValue(input)).should.be.equal('c')
    })

    it('allow number as value', async function () {
        await this.client.setValue(input, 11);
        (await this.client.getValue(input)).should.be.equal('11')
    })

    describe('is able to use unicode keys to', () => {
        it('understand complex characters and key modifiers', async function () {
            await this.client.setValue(input, [
                'Shift', '1', 'NULL', // !
                'Shift', '2', '3', '4', 'NULL', // @#$
                'Shift', '5', '6', 'NULL', // %^
                'Shift', '7', 'NULL', // &
                'Shift', '8', '9', '0' // *()
            ]);
            (['!@#$%^&*()', '!"§$%&/()=']).should.contain(await this.client.getValue(input))
        })

        it('use the numpad', async function () {
            await this.client.setValue(input, ['Numpad 0', 'Numpad 1', 'Numpad 2']);
            (await this.client.getValue(input)).should.be.equal('012')
        })
    })

    /* @see https://en.wikipedia.org/wiki/List_of_Unicode_characters
     * @see https://en.wikibooks.org/wiki/Unicode/Character_reference
     */
    describe('supports unicode planes', () => {
        it('supports BMP', async function () {
            await this.client.setValue(input, '') // For BMP plane, try F021 character
            (await this.client.getValue(input)).should.be.equal('')
        })

        // As of 2015-11-01, on its version 2.20, "ChromeDriver only supports characters in the BMP".
        // TODO: Move down or remove this return as ChromeDriver supports more planes
        if(process.env._BROWSER === 'chrome') {
            return
        }

        it('supports SMP', async function () {
            await this.client.setValue(input, '😱' // For SMP plane, try 1F631 character
            (await this.client.getValue(input)).should.be.equal('😱')
        })

        it('supports SIP', async function () {
            await this.client.setValue(input, '鬒' // For SIP, try 2FA0
            (await this.client.getValue(input)).should.be.equal('鬒')
        })

        it('supports PUA', async function () {
            await this.client.setValue(input, '󴺜' // For PUA, try F4E9C
            (await this.client.getValue(input)).should.be.equal('󴺜')
        })
    })
})
<commit_msg>eslintfix<commit_after>describe('setValue', () => {
    const input = 'input[name="a"]'

    it('should reset value before setting it', async function () {
        await this.client.setValue(input, 'b').setValue(input, 'c');
        (await this.client.getValue(input)).should.be.equal('c')
    })

    it('allow number as value', async function () {
        await this.client.setValue(input, 11);
        (await this.client.getValue(input)).should.be.equal('11')
    })

    describe('is able to use unicode keys to', () => {
        it('understand complex characters and key modifiers', async function () {
            await this.client.setValue(input, [
                'Shift', '1', 'NULL', // !
                'Shift', '2', '3', '4', 'NULL', // @#$
                'Shift', '5', '6', 'NULL', // %^
                'Shift', '7', 'NULL', // &
                'Shift', '8', '9', '0' // *()
            ]);
            (['!@#$%^&*()', '!"§$%&/()=']).should.contain(await this.client.getValue(input))
        })

        it('use the numpad', async function () {
            await this.client.setValue(input, ['Numpad 0', 'Numpad 1', 'Numpad 2']);
            (await this.client.getValue(input)).should.be.equal('012')
        })
    })

    /* @see https://en.wikipedia.org/wiki/List_of_Unicode_characters
     * @see https://en.wikibooks.org/wiki/Unicode/Character_reference
     */
    describe('supports unicode planes', () => {
        it('supports BMP', async function () {
            await this.client.setValue(input, ''); // For BMP plane, try F021 character
            (await this.client.getValue(input)).should.be.equal('')
        })

        // As of 2015-11-01, on its version 2.20, "ChromeDriver only supports characters in the BMP".
        // TODO: Move down or remove this return as ChromeDriver supports more planes
        if (process.env._BROWSER === 'chrome') {
            return
        }

        it('supports SMP', async function () {
            await this.client.setValue(input, '😱'); // For SMP plane, try 1F631 character
            (await this.client.getValue(input)).should.be.equal('😱')
        })

        it('supports SIP', async function () {
            await this.client.setValue(input, '鬒'); // For SIP, try 2FA0
            (await this.client.getValue(input)).should.be.equal('鬒')
        })

        it('supports PUA', async function () {
            await this.client.setValue(input, '󴺜'); // For PUA, try F4E9C
            (await this.client.getValue(input)).should.be.equal('󴺜')
        })
    })
})
<|endoftext|>


<commit_before>var fs = require('fs'),
	path = require('path'),
	os = require('os'),
	wrench = require('wrench'),
	colors = require('colors'),
	TU = require('../lib/testUtils'),
	CONST = require('../../Alloy/common/constants'),
	_ = require('../../Alloy/lib/alloy/underscore')._,
	platforms = require('../../platforms/index');

var TIMEOUT_COMPILE = 10000;
var GEN_FOLDER = '_generated';

var alloyRoot = path.join(__dirname,'..','..'),
	paths = {
		apps: path.join(alloyRoot,'test','apps'),
		harness: path.join(alloyRoot,'test','projects','Harness')
	},
	compilerDirectives = (function() {
		var cds = [];
		_.each(_.keys(platforms), function(p) {
			cds.push('OS_' + p.toUpperCase());
		});
		cds.concat(_.pluck(CONST.DEPLOY_TYPES,'key'));
		return cds;
	})(),
	cdRegex = new RegExp('(?:' + compilerDirectives.join('|') + ')');

// The alloy command test suite
describe('alloy compile', function() {
	TU.addMatchers();

	// Iterate through each test app and make sure it compiles for all platforms
	_.each(wrench.readdirSyncRecursive(paths.apps), function(file) {
		// are we testing only a specific app?
		if (process.env.app && file !== process.env.app) { return; }

		// TODO: Stop skipping the ui/navwindow test when TiSDK 3.1.3 is in the HarnessTemplate
		//       tiapp.xml. We skip it now because it purposely fails compilation on any SDK below
		//       TiSDK 3.1.3, where Ti.UI.iOS.NavigationWindow was introduced.
		if (file === 'ui/navwindow') { return; }

		describe(file.yellow, function() {
			var indexJs = path.join(paths.apps,file,'controllers','index.js');
			if (!path.existsSync(indexJs) || indexJs.indexOf(GEN_FOLDER) !== -1) { return; }

			it('preparing test app', function() {
				TU.asyncExecTest('jake app:setup dir=' + file + ' quiet=1', { timeout: 10000 });
			});

			_.each(platforms, function(platform,k) {
				describe(('[' + platform.platform + ']').cyan, function () {
					it('compiles without critical error',
						function() {
							TU.asyncExecTest(
								'alloy compile ' + paths.harness + ' --config platform=' + platform.platform, {
								test: function() {
									// Make sure there were no compile errors
									expect(this.output.error).toBeFalsy();
								},
								timeout: TIMEOUT_COMPILE
							}
						);
					});

					it('leaves no compiler directives in generated code', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy'),
							path.join(hrDir,platform.titaniumFolder,'alloy')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}
								var content = fs.readFileSync(fullpath, 'utf8');
								expect(cdRegex.test(content)).toBeFalsy();
							});
						});
					});

					it('has no undefined style entries', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy','styles'),
							path.join(hrDir,platform.titaniumFolder,'alloy','styles')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}

								// TODO: Can no longer require() the styles since they
								//       are preprocessed for runtime now. Find a better
								//       way than this lazy text check to verify that
								//       there's no undefined keys in the styles.
								expect(fs.readFileSync(fullpath,'utf8').indexOf('undefined')).toEqual(-1);
								// var json = require(fullpath);
								// expect(json).toHaveNoUndefinedStyles();
							});
						});
					});

					var genFolder = path.join(paths.apps,file,GEN_FOLDER,platform.platform);
					if (!fs.existsSync(genFolder)) { return; }
					var hrFolder = path.join(paths.harness, 'Resources', platform.titaniumFolder);
					var files = wrench.readdirSyncRecursive(genFolder);

					os.platform() === 'darwin' && _.each(files, function(gFile) {
						var goodFile = path.join(genFolder,gFile);
						if (!fs.statSync(goodFile).isFile()) { return; }
						var newFile = path.join(hrFolder,gFile);

						it ('generated a ' + gFile.yellow + ' file', function() {
							expect(fs.existsSync(newFile)).toBeTruthy();
						});

						it('matches known good generated code for ' + gFile.yellow, function () {
							var goodFileContents = fs.readFileSync(goodFile, 'utf8');
							var newFileContents = fs.readFileSync(newFile, 'utf8');
							expect(goodFileContents === newFileContents).toBeTruthy();
						});
					});
				});
			});
		});
	});
});
<commit_msg>remove testing/ALOY-818 from automated testing<commit_after>var fs = require('fs'),
	path = require('path'),
	os = require('os'),
	wrench = require('wrench'),
	colors = require('colors'),
	TU = require('../lib/testUtils'),
	CONST = require('../../Alloy/common/constants'),
	_ = require('../../Alloy/lib/alloy/underscore')._,
	platforms = require('../../platforms/index');

var TIMEOUT_COMPILE = 10000;
var GEN_FOLDER = '_generated';

var alloyRoot = path.join(__dirname,'..','..'),
	paths = {
		apps: path.join(alloyRoot,'test','apps'),
		harness: path.join(alloyRoot,'test','projects','Harness')
	},
	compilerDirectives = (function() {
		var cds = [];
		_.each(_.keys(platforms), function(p) {
			cds.push('OS_' + p.toUpperCase());
		});
		cds.concat(_.pluck(CONST.DEPLOY_TYPES,'key'));
		return cds;
	})(),
	cdRegex = new RegExp('(?:' + compilerDirectives.join('|') + ')');

// The alloy command test suite
describe('alloy compile', function() {
	TU.addMatchers();

	// Iterate through each test app and make sure it compiles for all platforms
	_.each(wrench.readdirSyncRecursive(paths.apps), function(file) {
		// are we testing only a specific app?
		if (process.env.app && file !== process.env.app) { return; }

		// TODO: Stop skipping the ui/navwindow test when TiSDK 3.1.3 is in the HarnessTemplate
		//       tiapp.xml. We skip it now because it purposely fails compilation on any SDK below
		//       TiSDK 3.1.3, where Ti.UI.iOS.NavigationWindow was introduced.
		if (file === 'ui/navwindow' || file === 'testing/ALOY-818') { return; }

		describe(file.yellow, function() {
			var indexJs = path.join(paths.apps,file,'controllers','index.js');
			if (!path.existsSync(indexJs) || indexJs.indexOf(GEN_FOLDER) !== -1) { return; }

			it('preparing test app', function() {
				TU.asyncExecTest('jake app:setup dir=' + file + ' quiet=1', { timeout: 10000 });
			});

			_.each(platforms, function(platform,k) {
				describe(('[' + platform.platform + ']').cyan, function () {
					it('compiles without critical error',
						function() {
							TU.asyncExecTest(
								'alloy compile ' + paths.harness + ' --config platform=' + platform.platform, {
								test: function() {
									// Make sure there were no compile errors
									expect(this.output.error).toBeFalsy();
								},
								timeout: TIMEOUT_COMPILE
							}
						);
					});

					it('leaves no compiler directives in generated code', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy'),
							path.join(hrDir,platform.titaniumFolder,'alloy')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}
								var content = fs.readFileSync(fullpath, 'utf8');
								expect(cdRegex.test(content)).toBeFalsy();
							});
						});
					});

					it('has no undefined style entries', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy','styles'),
							path.join(hrDir,platform.titaniumFolder,'alloy','styles')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}

								// TODO: Can no longer require() the styles since they
								//       are preprocessed for runtime now. Find a better
								//       way than this lazy text check to verify that
								//       there's no undefined keys in the styles.
								expect(fs.readFileSync(fullpath,'utf8').indexOf('undefined')).toEqual(-1);
								// var json = require(fullpath);
								// expect(json).toHaveNoUndefinedStyles();
							});
						});
					});

					var genFolder = path.join(paths.apps,file,GEN_FOLDER,platform.platform);
					if (!fs.existsSync(genFolder)) { return; }
					var hrFolder = path.join(paths.harness, 'Resources', platform.titaniumFolder);
					var files = wrench.readdirSyncRecursive(genFolder);

					os.platform() === 'darwin' && _.each(files, function(gFile) {
						var goodFile = path.join(genFolder,gFile);
						if (!fs.statSync(goodFile).isFile()) { return; }
						var newFile = path.join(hrFolder,gFile);

						it ('generated a ' + gFile.yellow + ' file', function() {
							expect(fs.existsSync(newFile)).toBeTruthy();
						});

						it('matches known good generated code for ' + gFile.yellow, function () {
							var goodFileContents = fs.readFileSync(goodFile, 'utf8');
							var newFileContents = fs.readFileSync(newFile, 'utf8');
							expect(goodFileContents === newFileContents).toBeTruthy();
						});
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var sinon = require('sinon');
var Gremlin = require('../lib/gremlin');
var GraphWrapper = require('../lib/graph-wrapper');

suite('graph-wrapper', function() {
  var gremlin;
  var graph;
  var g;
  var sandbox;

  suiteSetup(function() {
    gremlin = new Gremlin();
  });

  setup(function() {
    var TinkerGraphFactory = gremlin.java.import('com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory');
    graph = TinkerGraphFactory.createTinkerGraphSync();
    g = new GraphWrapper(gremlin, graph);
    sandbox = sinon.sandbox.create();
  });

  teardown(function() {
    sandbox.restore();
  });

  test('Non ThreadedTransactionalGraph instances do not start unique transactions', function() {
    graph.newTransactionSync = sandbox.spy();
    g.addVertex(null);
    assert(!graph.newTransactionSync.called);
  });

  test('ThreadedTransactionalGraph starts unique transactions', function() {
    var fakeTxn = {
      addVertex: sandbox.stub()
    };
    var fakeGraph = {
      newTransactionSync: sandbox.stub().returns(fakeTxn)
    };
    var fakeGremlin = {
      isType: sandbox.stub()
        .withArgs(fakeGraph, 'com.tinkerpop.blueprints.ThreadedTransactionalGraph')
        .returns(true),
      toList: function () {},
      toListSync: function () {},
      toJSON: function () {},
      toJSONSync: function () {},
    };
    var g2 = new GraphWrapper(fakeGremlin, fakeGraph);

    // should start a new transaction
    g2.addVertex(null);

    // should re-use the existing transaction
    g2.addVertex(null);

    assert(fakeGremlin.isType.calledOnce);
    assert(fakeGraph.newTransactionSync.calledOnce);
    assert(fakeTxn.addVertex.calledTwice);
  });

  test('addEdge(id, v1, v2)', function (done) {
    g.v(1, 2, function (err, pipe) {
      if (err) return done(err);

      pipe.next(function (err, v1) {
        if (err) return done(err);

        pipe.next(function (err, v2) {
          if (err) return done(err);

          g.addEdge(null, v1, v2, 'buddy', function (err, e) {
            if (err) return done(err);

            var data = g.toJSONSync(e)[0];
            assert(data._id === '0');
            assert(data._label === 'buddy');

            done();
          });
        });
      });
    });
  });

  test('getEdge', function (done) {
    g.getEdge('7', function (err, e) {
      if (err) return done(err);

      var data = g.toJSONSync(e)[0];
      assert(data._id === '7');
      assert(data._label === 'knows');
      done();
    });
  });

  test('removeEdge', function (done) {
    g.getEdge('7', function (err, e) {
      if (err) return done(err);

      g.removeEdge(e, function (err) {
        if (err) return done(err);

        g.getEdge('7', function (err, e) {
          if (err) return done(err);

          assert(!e);

          done();
        });
      });
    });
  });

  test('v(id) with single id', function (done) {
    g.v(2, function (err, data) {
      if (err) return done(err);
      assert(data.toString() === 'v[2]');
      done();
    });
  });

  test('v(id...) with id list', function (done) {
    g.v(2, 4, function (err, pipe) {
      pipe.toJSON(function (err, data) {
        if (err) return done(err);
        assert(data.length === 2);
        done();
      });
    });
  });

  test('v(id...) with id array', function (done) {
    g.v([2, 4], function (err, pipe) {
      pipe.toJSON(function (err, data) {
        if (err) return done(err);
        assert(data.length === 2);
        done();
      });
    });
  });

  test('v(id) with invalid id', function (done) {
    g.v(99, function (err, data) {
      if (err) return done(err);
      assert(!data);
      done();
    });
  });
});
<commit_msg> - don't use done(err) convention<commit_after>'use strict';

var assert = require('assert');
var sinon = require('sinon');
var Gremlin = require('../lib/gremlin');
var GraphWrapper = require('../lib/graph-wrapper');

suite('graph-wrapper', function() {
  var gremlin;
  var graph;
  var g;
  var sandbox;

  suiteSetup(function() {
    gremlin = new Gremlin();
  });

  setup(function() {
    var TinkerGraphFactory = gremlin.java.import('com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory');
    graph = TinkerGraphFactory.createTinkerGraphSync();
    g = new GraphWrapper(gremlin, graph);
    sandbox = sinon.sandbox.create();
  });

  teardown(function() {
    sandbox.restore();
  });

  test('Non ThreadedTransactionalGraph instances do not start unique transactions', function() {
    graph.newTransactionSync = sandbox.spy();
    g.addVertex(null);
    assert(!graph.newTransactionSync.called);
  });

  test('ThreadedTransactionalGraph starts unique transactions', function() {
    var fakeTxn = {
      addVertex: sandbox.stub()
    };
    var fakeGraph = {
      newTransactionSync: sandbox.stub().returns(fakeTxn)
    };
    var fakeGremlin = {
      isType: sandbox.stub()
        .withArgs(fakeGraph, 'com.tinkerpop.blueprints.ThreadedTransactionalGraph')
        .returns(true),
      toList: function () {},
      toListSync: function () {},
      toJSON: function () {},
      toJSONSync: function () {},
    };
    var g2 = new GraphWrapper(fakeGremlin, fakeGraph);

    // should start a new transaction
    g2.addVertex(null);

    // should re-use the existing transaction
    g2.addVertex(null);

    assert(fakeGremlin.isType.calledOnce);
    assert(fakeGraph.newTransactionSync.calledOnce);
    assert(fakeTxn.addVertex.calledTwice);
  });

  test('addEdge(id, v1, v2)', function (done) {
    g.v(1, 2, function (err, pipe) {
      assert(!err && pipe);

      pipe.next(function (err, v1) {
        assert(!err && v1);

        pipe.next(function (err, v2) {
          assert(!err && v2);

          g.addEdge(null, v1, v2, 'buddy', function (err, e) {
            assert(!err);

            var data = g.toJSONSync(e)[0];
            assert(data._id === '0');
            assert(data._label === 'buddy');

            done();
          });
        });
      });
    });
  });

  test('getEdge(id)', function (done) {
    g.getEdge('7', function (err, e) {
      assert(!err && e);

      var data = g.toJSONSync(e)[0];
      assert(data._id === '7');
      assert(data._label === 'knows');
      done();
    });
  });

  test('removeEdge(e)', function (done) {
    g.getEdge('7', function (err, e) {
      assert(!err && e);

      g.removeEdge(e, function (err) {
        assert(!err);

        g.getEdge('7', function (err, e) {
          assert(!err && !e);

          done();
        });
      });
    });
  });

  test('v(id) with single id', function (done) {
    g.v(2, function (err, data) {
      assert(!err && data.toString() === 'v[2]');
      done();
    });
  });

  test('v(id...) with id list', function (done) {
    g.v(2, 4, function (err, pipe) {
      pipe.toJSON(function (err, data) {
        assert(!err && data.length === 2);
        done();
      });
    });
  });

  test('v(id...) with id array', function (done) {
    g.v([2, 4], function (err, pipe) {
      assert(!err && pipe);
      pipe.toJSON(function (err, data) {
        assert(!err && data.length === 2);
        done();
      });
    });
  });

  test('v(id) with invalid id', function (done) {
    g.v(99, function (err, data) {
      assert(!err && !data);
      done();
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('assert');

function validateRemainingLength(value) {
    var maxMessageLength = 268435455;
    if (value > maxMessageLength) {
        return Error('max message length exceeded');
    }
    return undefined;
}

function existy(value) {
    return value !== null && value !== undefined;
}

function dispatch() {
    var funcs = arguments;

    return function(target) {
        for (var funcIndex in funcs) {
            var func = funcs[funcIndex];
            var ret = func.apply(null, [target]);
            if (existy(ret)) {
                return ret;
            }
        }
        return undefined;
    }
}

function encodeRemainingLength(value) {

    var dispatcher = dispatch(validateRemainingLength, encode);

    return dispatcher(value);

    function encode(value) {
        var buffer = new Buffer(0);
        do {
            var digit = value % 128;
            value = parseInt(value / 128);
            if (value > 0) {
                digit = digit | 0xFF;
            }
            var next = new Buffer(1);
            next.writeUInt8(digit, 0);
            buffer = Buffer.concat([buffer, next])
        }
        while (value > 0);
        return buffer;
    }
}

function decodeRemainingLength(buffer) {
    var multiplier = 1;
    var value = 0;
    var index = 0;
    var digit;
    do {
        if (index === buffer.length)
            return Error('malformed remaining length')
        digit = buffer.readUInt8(index++);
        value += (digit & 127) * multiplier;
        multiplier *= 128;
    }
    while ((digit & 128) !== 0);
    return value;
}

function remainingLengthByteCount(value) {
    var dispatcher = dispatch(validateRemainingLength, count);
    return dispatcher(value);

    function count(value) {
        return Math.ceil(Math.log(value) / Math.log(128));
    }
}

describe('MQTT Special Functions', function() {

    describe('Encoding remaining length', function() {

        function expectEncoding(value, expectedValues) {
            var result = encodeRemainingLength(value);
            assert.equal(result.length, expectedValues.length);
            for (var i = 0; i < expectedValues.length; i++) {
                assert.equal(result.readUInt8(i), expectedValues[i]);
            }
        }

        it('encoding 127 returns a 1 byte Buffer', function() {
            expectEncoding(127, [0x7F]);
        });

        it('encoding 128 x 127 returns a 2 byte Buffer', function() {
            expectEncoding(128 * 127, [0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 127 returns a 3 byte Buffer', function() {
            expectEncoding(128 * 128 * 127, [0xFF, 0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 128 x 127 returns a 4 byte Buffer', function() {
            expectEncoding(128 * 128 * 128 * 127, [0xFF, 0xFF, 0xFF, 0x7F]);
        });

        it('encoding a number greater than 128x128x128x127 throws an error', function() {
            var error = encodeRemainingLength(128 * 128 * 128 * 128);
            assert.equal(error.message, 'max message length exceeded');
        });
    });

    describe('Decoding remaining length', function() {

        var oneByteUpperLimit = 128 - 1;
        var twoByteUpperLimit = 128 * 128 - 1;
        var threeByteUpperLimit = 128 * 128 * 128 - 1;
        var fourByteUpperLimit = 128 * 128 * 128 * 128 - 1;

        function expectDecoding(value, expectedValue) {
            var buffer = new Buffer(value.length);
            for (var i = 0; i < value.length; i++) {
                buffer.writeUInt8(value[i], i);
            }
            var result = decodeRemainingLength(buffer);
            assert.equal(result, expectedValue);
        }

        it('decodes 0x7F as one byte upper limit', function() {
            expectDecoding([0x7F], oneByteUpperLimit);
        });

        it('decodes 0xFF 0x7F as two byte upper limit', function() {
            expectDecoding([0xFF, 0x7F], twoByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0x7F as three byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0x7F], threeByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0xFF 0x7F as four byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0xFF, 0x7F], fourByteUpperLimit);
        });

        it('decoding a buffer greater than the four byte upper limit throws an error', function() {
            var error = decodeRemainingLength(new Buffer([0xFF, 0xFF, 0xFF, 0xFF]))
            assert.equal(error.message, 'malformed remaining length');
        });

        it('remainingLengthByteCount returns 1', function() {
            assert.equal(1, remainingLengthByteCount(oneByteUpperLimit));
        });

        it('remainLengthByteCount returns 2', function() {
            assert.equal(2, remainingLengthByteCount(twoByteUpperLimit));
        });

        it('remainingLengthByteCount returns 2', function() {
            assert.equal(3, remainingLengthByteCount(threeByteUpperLimit));
        });

        it('remainingLengthByteCount returns 4', function() {
            assert.equal(4, remainingLengthByteCount(fourByteUpperLimit));
        });

        it('remainingLengthByteCount returns error when number is greater than fourByteUpperLimit', function() {
            assert.ok(remainingLengthByteCount(fourByteUpperLimit + 1) instanceof Error);
        });
    });

});
<commit_msg>tidying formatting<commit_after>var assert = require('assert');

function validateRemainingLength(value) {
    var maxMessageLength = 268435455;
    if (value > maxMessageLength) {
        return Error('max message length exceeded');
    }
    return undefined;
}

function existy(value) {
    return value !== null && value !== undefined;
}

function dispatch() {
    var funcs = arguments;

    return function(target) {
        for (var funcIndex in funcs) {
            var func = funcs[funcIndex];
            var ret = func.apply(null, [target]);
            if (existy(ret)) {
                return ret;
            }
        }
        return undefined;
    }
}

function encodeRemainingLength(value) {

    var dispatcher = dispatch(validateRemainingLength, encode);

    return dispatcher(value);

    function encode(value) {
        var buffer = new Buffer(0);
        do {
            var digit = value % 128;
            value = parseInt(value / 128);
            if (value > 0) {
                digit = digit | 0xFF;
            }
            var next = new Buffer(1);
            next.writeUInt8(digit, 0);
            buffer = Buffer.concat([buffer, next])
        }
        while (value > 0);
        return buffer;
    }
}

function decodeRemainingLength(buffer) {
    var multiplier = 1;
    var value = 0;
    var index = 0;
    var digit;
    do {
        if (index === buffer.length)
            return Error('malformed remaining length')
        digit = buffer.readUInt8(index++);
        value += (digit & 127) * multiplier;
        multiplier *= 128;
    }
    while ((digit & 128) !== 0);
    return value;
}

function remainingLengthByteCount(value) {
    var dispatcher = dispatch(validateRemainingLength, count);
    return dispatcher(value);

    function count(value) {
        return Math.ceil(Math.log(value) / Math.log(128));
    }
}

describe('MQTT Special Functions', function() {

    describe('Encoding remaining length', function() {

        function expectEncoding(value, expectedValues) {
            var result = encodeRemainingLength(value);
            assert.equal(result.length, expectedValues.length);
            for (var i = 0; i < expectedValues.length; i++) {
                assert.equal(result.readUInt8(i), expectedValues[i]);
            }
        }

        it('encoding 127 returns a 1 byte Buffer', function() {
            expectEncoding(127, [0x7F]);
        });

        it('encoding 128 x 127 returns a 2 byte Buffer', function() {
            expectEncoding(128 * 127, [0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 127 returns a 3 byte Buffer', function() {
            expectEncoding(128 * 128 * 127, [0xFF, 0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 128 x 127 returns a 4 byte Buffer', function() {
            expectEncoding(128 * 128 * 128 * 127, [0xFF, 0xFF, 0xFF, 0x7F]);
        });

        it('encoding a number greater than 128x128x128x127 throws an error', function() {
            var error = encodeRemainingLength(128 * 128 * 128 * 128);
            assert.equal(error.message, 'max message length exceeded');
        });
    });

    describe('Decoding remaining length', function() {

        var oneByteUpperLimit = 128 - 1;
        var twoByteUpperLimit = 128 * 128 - 1;
        var threeByteUpperLimit = 128 * 128 * 128 - 1;
        var fourByteUpperLimit = 128 * 128 * 128 * 128 - 1;

        function expectDecoding(value, expectedValue) {
            var buffer = new Buffer(value.length);
            for (var i = 0; i < value.length; i++) {
                buffer.writeUInt8(value[i], i);
            }
            var result = decodeRemainingLength(buffer);
            assert.equal(result, expectedValue);
        }

        it('decodes 0x7F as one byte upper limit', function() {
            expectDecoding([0x7F], oneByteUpperLimit);
        });

        it('decodes 0xFF 0x7F as two byte upper limit', function() {
            expectDecoding([0xFF, 0x7F], twoByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0x7F as three byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0x7F], threeByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0xFF 0x7F as four byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0xFF, 0x7F], fourByteUpperLimit);
        });

        it('decoding a buffer greater than the four byte upper limit throws an error', function() {
            var error = decodeRemainingLength(new Buffer([0xFF, 0xFF, 0xFF, 0xFF]))
assert.equal(error.message, 'malformed remaining length');
        });

        it('remainingLengthByteCount returns 1', function() {
            assert.equal(1, remainingLengthByteCount(oneByteUpperLimit));
        });

        it('remainLengthByteCount returns 2', function() {
            assert.equal(2, remainingLengthByteCount(twoByteUpperLimit));
        });

        it('remainingLengthByteCount returns 2', function() {
            assert.equal(3, remainingLengthByteCount(threeByteUpperLimit));
        });

        it('remainingLengthByteCount returns 4', function() {
            assert.equal(4, remainingLengthByteCount(fourByteUpperLimit));
        });

        it('remainingLengthByteCount returns error when number is greater than fourByteUpperLimit', function() {
            assert.ok(remainingLengthByteCount(fourByteUpperLimit + 1) instanceof Error);
        });
    });

});
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var utils = require('formio-utils');

module.exports = [
  function() {
    return {
      restrict: 'E',
      replace: true,
      scope: true,
      template:
      '
' +
        'This component should:' +
        '<select class="form-control input-md" ng-model="_boolean">' +
          '<option ng-repeat="item in _booleans track by $index" value="{{item.value}}">{{item.label}}</option>' +
        '</select>' +
        '
When the form component:' +
        '<select class="form-control input-md" ng-model="_component">' +
          '<option ng-repeat="item in _components track by $index" value="{{item.key}}">{{item.label}}</option>' +
        '</select>' +
        '
Has the value:' +
        '<input type="text" class="form-control input-md" ng-model="_searchValue">' +
      '
',
      controller: [
        '$scope',
        function(
          $scope
        ) {
          // Default the current components conditional logic.
          $scope.component = $scope.component || {};
          $scope.component.conditional = $scope.component.conditional || {};

          // The available logic functions.
          $scope._booleans = [
            {value: '', label: ''},
            {value: true, label: 'Display'},
            {value: false, label: 'Hide'}
          ];

          // Filter the list of available form components for conditional logic.
          $scope._components = _.get($scope, 'form.components') || [];
          $scope._components = utils.flattenComponents($scope._components);
          // Remove non-input/button fields because they don't make sense.
          $scope._components = _.reject($scope._components, function(c) {
            return !c.input || (c.type === 'button');
          });

          // Add default item to the components list.
          $scope._components.unshift('');

          // Default and watch the show logic.
          $scope.component.conditional.show = $scope.component.conditional.show || null;
          $scope._boolean = $scope.component.conditional.show;
          $scope.$watch('_boolean', function(newVal) {
            $scope.component.conditional.show = newVal || false;
          });

          // Default and watch the when logic.
          $scope.component.conditional.when = $scope.component.conditional.when || null;
          $scope._component = $scope.component.conditional.when;
          $scope.$watch('_component', function(newVal) {
            $scope.component.conditional.when = newVal;
          });

          // Default and watch the search logic.
          $scope.component.conditional.eq = $scope.component.conditional.eq || '';
          $scope._searchValue = $scope.component.conditional.eq;
          $scope.$watch('_searchValue', function(newVal) {
            $scope.component.conditional.eq = newVal;
          });
        }
      ]
    };
  }
];
<commit_msg>Adding the accordion options to conditional form fields, for simple and advanced.<commit_after>'use strict';

var _ = require('lodash');
var utils = require('formio-utils');

module.exports = [
  function() {
    return {
      restrict: 'E',
      scope: true,
      template: '' +
        '<uib-accordion>' +
          '<uib-accordion-group heading="Simple" is-open="status.simple">' +
            'This component should:' +
            '<select class="form-control input-md" ng-model="_boolean">' +
            '<option ng-repeat="item in _booleans track by $index" value="{{item.value}}">{{item.label}}</option>' +
            '</select>' +
            '
When the form component:' +
            '<select class="form-control input-md" ng-model="_component">' +
            '<option ng-repeat="item in _components track by $index" value="{{item.key}}">{{item.label}}</option>' +
            '</select>' +
            '
Has the value:' +
            '<input type="text" class="form-control input-md" ng-model="_searchValue">' +
          '</uib-accordion-group>' +
          '<uib-accordion-group heading="Advanced" is-open="status.advanced">' +
            '<textarea class="form-control" rows="5" id="custom" name="custom" ng-model="component.customConditional" placeholder="/*** Example Code ***/\nshow = (data[\'mykey\'] > 1);">{{ component.validate.custom }}</textarea>' +
            '' +
            '
Enter custom conditional code.
' +
            '
You must assign the show variable as either true or false.
' +
            '
The global variable data is provided, and allows you to access the data of any form component.
' +
            '' +
          '</uib-accordion-group>' +
        '</uib-accordion>',
      controller: [
        '$scope',
        function(
          $scope
        ) {
          // Default the current components conditional logic.
          $scope.component = $scope.component || {};
          $scope.component.conditional = $scope.component.conditional || {};

          // The available logic functions.
          $scope._booleans = [
            {value: '', label: ''},
            {value: true, label: 'Display'},
            {value: false, label: 'Hide'}
          ];

          // Filter the list of available form components for conditional logic.
          $scope._components = _.get($scope, 'form.components') || [];
          $scope._components = utils.flattenComponents($scope._components);
          // Remove non-input/button fields because they don't make sense.
          $scope._components = _.reject($scope._components, function(c) {
            return !c.input || (c.type === 'button');
          });

          // Add default item to the components list.
          $scope._components.unshift('');

          // Default and watch the show logic.
          $scope.component.conditional.show = $scope.component.conditional.show || null;
          $scope._boolean = $scope.component.conditional.show;
          $scope.$watch('_boolean', function(newVal) {
            $scope.component.conditional.show = newVal || false;
          });

          // Default and watch the when logic.
          $scope.component.conditional.when = $scope.component.conditional.when || null;
          $scope._component = $scope.component.conditional.when;
          $scope.$watch('_component', function(newVal) {
            $scope.component.conditional.when = newVal;
          });

          // Default and watch the search logic.
          $scope.component.conditional.eq = $scope.component.conditional.eq || '';
          $scope._searchValue = $scope.component.conditional.eq;
          $scope.$watch('_searchValue', function(newVal) {
            $scope.component.conditional.eq = newVal;
          });

          // Track the status of the accordion panels open state.
          $scope.status = {
            simple: !$scope.component.customConditional,
            advanced: !!$scope.component.customConditional
          };
        }
      ]
    };
  }
];
<|endoftext|>


<commit_before>/**
 * Baobab Monkey Unit Tests
 * =========================
 */
import assert from 'assert';
import Baobab, {monkey} from '../../src/baobab';
import {MonkeyDefinition} from '../../src/monkey';
import type from '../../src/type';
import _ from 'lodash';

const noop = Function.prototype;

const getExampleState = () => ({
  data: {
    messages: [
      {from: 'John', message: 'Hey'},
      {from: 'Jack', message: 'Ho'}
    ],
    fromJohn: monkey({
      cursors: {
        messages: ['data', 'messages']
      },
      get: function({messages}) {
        return _.filter(messages, {from: 'John'});
      }
    })
  }
});

describe('Monkeys', function() {

  it('the monkey definition type should work correctly.', function() {
    const validObject = {cursors: {a: ['one']}, get: noop},
          validArray = [['one'], noop],
          invalidObject = {hello: 'world'},
          invalidArray = ['so crisp!'];

    assert.strictEqual(type.monkeyDefinition(validObject), 'object');
    assert.strictEqual(type.monkeyDefinition(validArray), 'array');
    assert.strictEqual(type.monkeyDefinition(invalidObject), null);
    assert.strictEqual(type.monkeyDefinition(invalidArray), null);
  });

  it('should be possible to create monkey definitions from objects.', function() {
    const objectNode = monkey({cursors: {a: ['one']}, get: noop}),
          arrayNode = monkey([['one'], noop]);

    assert(objectNode instanceof MonkeyDefinition);
    assert(arrayNode instanceof MonkeyDefinition);

    assert.throws(function() {
      monkey({hello: 'world'});
    }, /invalid/);
  });

  it('should be possible to create monkeys at instantiation.', function() {
    const tree = new Baobab(getExampleState());

    assert.deepEqual(
      tree.get('data', 'fromJohn'),
      [{from: 'John', message: 'Hey'}]
    );
  });

  it('should be possible to create monkeys using a shorthand.', function() {
    const tree = new Baobab({
      data: {
        messages: [
          {from: 'John', message: 'Hey'},
          {from: 'Jack', message: 'Ho'}
        ],
        greeting: 'Hello',
        custom: monkey(
          ['data', 'messages'],
          ['data', 'greeting'],
          function(messages, greeting) {
            return greeting + ' ' + messages[0].from;
          }
        )
      }
    });

    assert.strictEqual(tree.get('data', 'custom'), 'Hello John');
  });

  it('computed data should be immutable.', function() {
    const tree = new Baobab(getExampleState()),
          computedData = tree.get('data', 'fromJohn');

    assert.isFrozen(computedData);
  });

  it('should be possible to access data from beyond monkeys.', function() {
    const tree = new Baobab(getExampleState());

    assert.strictEqual(
      tree.get('data', 'fromJohn', 0, 'message'),
      'Hey'
    );
  });

  it('monkeys should update when their dependencies update.', function() {
    const tree = new Baobab(getExampleState());

    assert.deepEqual(
      tree.get('data', 'fromJohn'),
      [{from: 'John', message: 'Hey'}]
    );

    tree.push(['data', 'messages'], {from: 'John', message: 'Success!'});

    assert.deepEqual(
      tree.get('data', 'fromJohn'),
      [{from: 'John', message: 'Hey'}, {from: 'John', message: 'Success!'}]
    );
  });

  it('monkeys should be able to work with dynamic paths.', function() {
    const tree = new Baobab(
      {
        list: [{id: 1, name: 'John'}],
        greeting: monkey({
          cursors: {
            person: ['list', {id: 1}]
          },
          get({person: {name}}) {
            return `Hello ${name}`;
          }
        })
      }
    );

    assert.strictEqual(tree.get('greeting'), 'Hello John');

    tree.set(['list', 0, 'name'], 'Jack')

    assert.strictEqual(tree.get('greeting'), 'Hello Jack');
  });

  it('cursors with a monkey in the path should work correctly.', function(done) {
    const tree = new Baobab(getExampleState()),
          cursor = tree.select('data', 'fromJohn');

    cursor.on('update', e => done());

    assert.deepEqual(
      cursor.get(),
      [{from: 'John', message: 'Hey'}]
    );

    tree.push(['data', 'messages'], {from: 'John', message: 'Success!'});

    assert.deepEqual(
      cursor.get(),
      [{from: 'John', message: 'Hey'}, {from: 'John', message: 'Success!'}]
    );
  });

  it('cursors should be able to listen to beyond monkeys.', function() {
    const tree = new Baobab(getExampleState()),
          cursor = tree.select('data', 'fromJohn', 0, 'message');

    assert.strictEqual(
      cursor.get(),
      'Hey'
    );
  });

  it('getting a higher key should correctly solve computed data.', function() {
    const tree = new Baobab(getExampleState());

    assert.deepEqual(
      tree.get(),
      {
        data: {
          messages: [
            {from: 'John', message: 'Hey'},
            {from: 'Jack', message: 'Ho'}
          ],
          fromJohn: [{from: 'John', message: 'Hey'}]
        }
      }
    );

    assert.deepEqual(
      tree.get('data'),
      {
        messages: [
          {from: 'John', message: 'Hey'},
          {from: 'Jack', message: 'Ho'}
        ],
        fromJohn: [{from: 'John', message: 'Hey'}]
      }
    );
  });

  it('should be possible to serialize the tree or some of its parts.', function() {
    const tree = new Baobab(getExampleState());

    assert.deepEqual(
      tree.serialize(),
      {
        data: {
          messages: [
            {from: 'John', message: 'Hey'},
            {from: 'Jack', message: 'Ho'}
          ]
        }
      }
    );

    assert.deepEqual(
      tree.serialize('data'),
      {
        messages: [
          {from: 'John', message: 'Hey'},
          {from: 'Jack', message: 'Ho'}
        ]
      }
    );

    assert.deepEqual(
      tree.select('data').serialize(),
      {
        messages: [
          {from: 'John', message: 'Hey'},
          {from: 'Jack', message: 'Ho'}
        ]
      }
    );
  });

  it('should work recursively.', function(done) {
    const inc = x => x + 1;

    const tree = new Baobab({
      data: {
        number: 1
      },
      computed: {
        one: monkey(['data', 'number'], inc),
        two: monkey(['computed', 'one'], inc)
      }
    });

    assert.strictEqual(tree.get('computed', 'one'), 2);
    assert.strictEqual(tree.get('computed', 'two'), 3);

    tree.select('data', 'number').on('update', () => {
      assert.strictEqual(tree.get('computed', 'one'), 6);
      assert.strictEqual(tree.get('computed', 'two'), 7);
      done();
    });

    tree.set(['data', 'number'], 5);
  });

  it('recursivity should take updates into account.', function() {
    let count = 0;

    const tree = new Baobab({
      rows: [1, 2, 3, 4, 5],
      visibleRows: {start: 0, end: 0},
      rowLength: monkey([
        ['rows'],
        function(rows) {
          return rows.length;
        }
      ]),
      specialRows: monkey([
        ['rows'],
        function(rows) {
          return rows;
        }
      ]),
      visibleRowsData: monkey([
        ['specialRows'],
        ['visibleRows'],
        function(specialRows, visibleRows) {
          count++;
          return specialRows.slice(visibleRows.start, visibleRows.end);
        }
      ]),
    }, {asynchronous: false});

    tree.get('visibleRowsData');
    tree.select('visibleRows').set({start:1, end:4});
    tree.get('visibleRowsData');

    assert.strictEqual(count, 2);
  });

  it('data retrieved through facets should be immutable by default.', function() {
    const tree = new Baobab(getExampleState()),
          data = tree.get();

    assert.isFrozen(data.data);
    assert.isFrozen(data.data.fromJohn);
    assert.isFrozen(data.data.fromJohn[0]);

    const mutableTree = new Baobab(getExampleState(), {immutable: false}),
          mutableData = mutableTree.get();

    assert.isNotFrozen(mutableData.data);
    assert.isNotFrozen(mutableData.data.fromJohn);
    assert.isNotFrozen(mutableData.data.fromJohn[0]);
  });

  it('should warn the user when he attempts to update a path beneath a monkey.', function() {
    const tree = new Baobab(getExampleState());

    assert.throws(function() {
      tree.set(['data', 'fromJohn', 0, 'text'], 'Shawarma');
    }, /read-only/);
  });

  it('should be possible to add new monkeys at runtime.', function() {
    const tree = new Baobab(
      {
        data: {
          colors: ['yellow', 'blue', 'purple']
        }
      },
      {asynchronous: false}
    );

    const final = monkey(['data', 'colors'], cl => cl.filter(c => c.slice(-1)[0] === 'e')),
          leading = monkey(['data', 'colors'], cl => cl.filter(c => c[0] === 'y'));

    tree.set(['data', 'filtered'], final);

    assert.deepEqual(tree.get('data', 'filtered'), ['blue', 'purple']);

    tree.set(['data', 'computed', 'leader'], leading);

    assert.deepEqual(tree.get('data', 'computed', 'leader'), ['yellow']);
  });

  it('should be possible to replace monkeys at runtime.', function() {
    const tree = new Baobab(
      {
        data: {
          colors: ['yellow', 'blue'],
          selected: monkey(['data', 'colors'], c => c[0])
        }
      },
      {asynchronous: false}
    );

    assert.strictEqual(tree.get('data', 'selected'), 'yellow');

    tree.set(['data', 'selected'], monkey(['data', 'colors'], c => c[1]));

    assert.strictEqual(tree.get('data', 'selected'), 'blue');
  });
});
<commit_msg>Possibility to unset monkeys at runtime<commit_after>/**
 * Baobab Monkey Unit Tests
 * =========================
 */
import assert from 'assert';
import Baobab, {monkey} from '../../src/baobab';
import {MonkeyDefinition} from '../../src/monkey';
import type from '../../src/type';
import _ from 'lodash';

const noop = Function.prototype;

const getExampleState = () => ({
  data: {
    messages: [
      {from: 'John', message: 'Hey'},
      {from: 'Jack', message: 'Ho'}
    ],
    fromJohn: monkey({
      cursors: {
        messages: ['data', 'messages']
      },
      get: function({messages}) {
        return _.filter(messages, {from: 'John'});
      }
    })
  }
});

describe('Monkeys', function() {

  it('the monkey definition type should work correctly.', function() {
    const validObject = {cursors: {a: ['one']}, get: noop},
          validArray = [['one'], noop],
          invalidObject = {hello: 'world'},
          invalidArray = ['so crisp!'];

    assert.strictEqual(type.monkeyDefinition(validObject), 'object');
    assert.strictEqual(type.monkeyDefinition(validArray), 'array');
    assert.strictEqual(type.monkeyDefinition(invalidObject), null);
    assert.strictEqual(type.monkeyDefinition(invalidArray), null);
  });

  it('should be possible to create monkey definitions from objects.', function() {
    const objectNode = monkey({cursors: {a: ['one']}, get: noop}),
          arrayNode = monkey([['one'], noop]);

    assert(objectNode instanceof MonkeyDefinition);
    assert(arrayNode instanceof MonkeyDefinition);

    assert.throws(function() {
      monkey({hello: 'world'});
    }, /invalid/);
  });

  it('should be possible to create monkeys at instantiation.', function() {
    const tree = new Baobab(getExampleState());

    assert.deepEqual(
      tree.get('data', 'fromJohn'),
      [{from: 'John', message: 'Hey'}]
    );
  });

  it('should be possible to create monkeys using a shorthand.', function() {
    const tree = new Baobab({
      data: {
        messages: [
          {from: 'John', message: 'Hey'},
          {from: 'Jack', message: 'Ho'}
        ],
        greeting: 'Hello',
        custom: monkey(
          ['data', 'messages'],
          ['data', 'greeting'],
          function(messages, greeting) {
            return greeting + ' ' + messages[0].from;
          }
        )
      }
    });

    assert.strictEqual(tree.get('data', 'custom'), 'Hello John');
  });

  it('computed data should be immutable.', function() {
    const tree = new Baobab(getExampleState()),
          computedData = tree.get('data', 'fromJohn');

    assert.isFrozen(computedData);
  });

  it('should be possible to access data from beyond monkeys.', function() {
    const tree = new Baobab(getExampleState());

    assert.strictEqual(
      tree.get('data', 'fromJohn', 0, 'message'),
      'Hey'
    );
  });

  it('monkeys should update when their dependencies update.', function() {
    const tree = new Baobab(getExampleState());

    assert.deepEqual(
      tree.get('data', 'fromJohn'),
      [{from: 'John', message: 'Hey'}]
    );

    tree.push(['data', 'messages'], {from: 'John', message: 'Success!'});

    assert.deepEqual(
      tree.get('data', 'fromJohn'),
      [{from: 'John', message: 'Hey'}, {from: 'John', message: 'Success!'}]
    );
  });

  it('monkeys should be able to work with dynamic paths.', function() {
    const tree = new Baobab(
      {
        list: [{id: 1, name: 'John'}],
        greeting: monkey({
          cursors: {
            person: ['list', {id: 1}]
          },
          get({person: {name}}) {
            return `Hello ${name}`;
          }
        })
      }
    );

    assert.strictEqual(tree.get('greeting'), 'Hello John');

    tree.set(['list', 0, 'name'], 'Jack')

    assert.strictEqual(tree.get('greeting'), 'Hello Jack');
  });

  it('cursors with a monkey in the path should work correctly.', function(done) {
    const tree = new Baobab(getExampleState()),
          cursor = tree.select('data', 'fromJohn');

    cursor.on('update', e => done());

    assert.deepEqual(
      cursor.get(),
      [{from: 'John', message: 'Hey'}]
    );

    tree.push(['data', 'messages'], {from: 'John', message: 'Success!'});

    assert.deepEqual(
      cursor.get(),
      [{from: 'John', message: 'Hey'}, {from: 'John', message: 'Success!'}]
    );
  });

  it('cursors should be able to listen to beyond monkeys.', function() {
    const tree = new Baobab(getExampleState()),
          cursor = tree.select('data', 'fromJohn', 0, 'message');

    assert.strictEqual(
      cursor.get(),
      'Hey'
    );
  });

  it('getting a higher key should correctly solve computed data.', function() {
    const tree = new Baobab(getExampleState());

    assert.deepEqual(
      tree.get(),
      {
        data: {
          messages: [
            {from: 'John', message: 'Hey'},
            {from: 'Jack', message: 'Ho'}
          ],
          fromJohn: [{from: 'John', message: 'Hey'}]
        }
      }
    );

    assert.deepEqual(
      tree.get('data'),
      {
        messages: [
          {from: 'John', message: 'Hey'},
          {from: 'Jack', message: 'Ho'}
        ],
        fromJohn: [{from: 'John', message: 'Hey'}]
      }
    );
  });

  it('should be possible to serialize the tree or some of its parts.', function() {
    const tree = new Baobab(getExampleState());

    assert.deepEqual(
      tree.serialize(),
      {
        data: {
          messages: [
            {from: 'John', message: 'Hey'},
            {from: 'Jack', message: 'Ho'}
          ]
        }
      }
    );

    assert.deepEqual(
      tree.serialize('data'),
      {
        messages: [
          {from: 'John', message: 'Hey'},
          {from: 'Jack', message: 'Ho'}
        ]
      }
    );

    assert.deepEqual(
      tree.select('data').serialize(),
      {
        messages: [
          {from: 'John', message: 'Hey'},
          {from: 'Jack', message: 'Ho'}
        ]
      }
    );
  });

  it('should work recursively.', function(done) {
    const inc = x => x + 1;

    const tree = new Baobab({
      data: {
        number: 1
      },
      computed: {
        one: monkey(['data', 'number'], inc),
        two: monkey(['computed', 'one'], inc)
      }
    });

    assert.strictEqual(tree.get('computed', 'one'), 2);
    assert.strictEqual(tree.get('computed', 'two'), 3);

    tree.select('data', 'number').on('update', () => {
      assert.strictEqual(tree.get('computed', 'one'), 6);
      assert.strictEqual(tree.get('computed', 'two'), 7);
      done();
    });

    tree.set(['data', 'number'], 5);
  });

  it('recursivity should take updates into account.', function() {
    let count = 0;

    const tree = new Baobab({
      rows: [1, 2, 3, 4, 5],
      visibleRows: {start: 0, end: 0},
      rowLength: monkey([
        ['rows'],
        function(rows) {
          return rows.length;
        }
      ]),
      specialRows: monkey([
        ['rows'],
        function(rows) {
          return rows;
        }
      ]),
      visibleRowsData: monkey([
        ['specialRows'],
        ['visibleRows'],
        function(specialRows, visibleRows) {
          count++;
          return specialRows.slice(visibleRows.start, visibleRows.end);
        }
      ]),
    }, {asynchronous: false});

    tree.get('visibleRowsData');
    tree.select('visibleRows').set({start:1, end:4});
    tree.get('visibleRowsData');

    assert.strictEqual(count, 2);
  });

  it('data retrieved through facets should be immutable by default.', function() {
    const tree = new Baobab(getExampleState()),
          data = tree.get();

    assert.isFrozen(data.data);
    assert.isFrozen(data.data.fromJohn);
    assert.isFrozen(data.data.fromJohn[0]);

    const mutableTree = new Baobab(getExampleState(), {immutable: false}),
          mutableData = mutableTree.get();

    assert.isNotFrozen(mutableData.data);
    assert.isNotFrozen(mutableData.data.fromJohn);
    assert.isNotFrozen(mutableData.data.fromJohn[0]);
  });

  it('should warn the user when he attempts to update a path beneath a monkey.', function() {
    const tree = new Baobab(getExampleState());

    assert.throws(function() {
      tree.set(['data', 'fromJohn', 0, 'text'], 'Shawarma');
    }, /read-only/);
  });

  it('should be possible to add new monkeys at runtime.', function() {
    const tree = new Baobab(
      {
        data: {
          colors: ['yellow', 'blue', 'purple']
        }
      },
      {asynchronous: false}
    );

    const final = monkey(['data', 'colors'], cl => cl.filter(c => c.slice(-1)[0] === 'e')),
          leading = monkey(['data', 'colors'], cl => cl.filter(c => c[0] === 'y'));

    tree.set(['data', 'filtered'], final);

    assert.deepEqual(tree.get('data', 'filtered'), ['blue', 'purple']);

    tree.set(['data', 'computed', 'leader'], leading);

    assert.deepEqual(tree.get('data', 'computed', 'leader'), ['yellow']);
  });

  it('should be possible to replace monkeys at runtime.', function() {
    const tree = new Baobab(
      {
        data: {
          colors: ['yellow', 'blue'],
          selected: monkey(['data', 'colors'], c => c[0])
        }
      },
      {asynchronous: false}
    );

    assert.strictEqual(tree.get('data', 'selected'), 'yellow');

    tree.set(['data', 'selected'], monkey(['data', 'colors'], c => c[1]));

    assert.strictEqual(tree.get('data', 'selected'), 'blue');

    tree.set(['data', 'colors', 1], 'purple');

    assert.strictEqual(tree.get('data', 'selected'), 'purple');
  });

  it('should be possible to drop monkeys somehow.', function() {
    const tree = new Baobab(
      {
        data: {
          colors: ['yellow', 'blue'],
          selected: monkey(['data', 'colors'], c => c[0])
        }
      },
      {asynchronous: false}
    );

    tree.unset(['data', 'selected']);

    assert.deepEqual(
      tree.get('data'),
      {colors: ['yellow', 'blue']}
    );
  });
});
<|endoftext|>


<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var helpers = require('yeoman-generator').test;

describe('Ionic Framework Generator', function () {
    beforeEach(function (done) {
        helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
            if (err) {
                return done(err);
            }

            this.app = helpers.createGenerator('ionic:app', [
                '../../app'
            ]);
            done();
        }.bind(this));
    });

    it('creates expected files', function (done) {
        this.timeout(20000);
        var expected = [
            // add files you expect to exist here.
            '.jshintrc',
            '.editorconfig'
        ];

        helpers.mockPrompt(this.app, {
            compass: false,
            plugins: []
        });
        this.app.options['skip-install'] = true;
        this.app.init = function () {};
        this.app.run({}, function () {
            helpers.assertFiles(expected);
            done();
        });
    });
});
<commit_msg>test(creation): Mock template app list prompt<commit_after>/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var helpers = require('yeoman-generator').test;

describe('Ionic Framework Generator', function () {
    beforeEach(function (done) {
        helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
            if (err) {
                return done(err);
            }

            this.app = helpers.createGenerator('ionic:app', [
                '../../app'
            ]);
            done();
        }.bind(this));
    });

    it('creates expected files', function (done) {
        this.timeout(20000);
        var expected = [
            // add files you expect to exist here.
            '.jshintrc',
            '.editorconfig'
        ];

        helpers.mockPrompt(this.app, {
            compass: false,
            plugins: [],
            starter: 'Blank'
        });
        this.app.options['skip-install'] = true;
        this.app.init = function () {};
        this.app.run({}, function () {
            helpers.assertFiles(expected);
            done();
        });
    });
});
<|endoftext|>


<commit_before>/*global describe, beforeEach, it */
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;

describe('rkgttr generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('rkgttr:app', [
        '../../app'
      ]);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = [
      // add files you expect to exist here.
      '.jshintrc',
      '.editorconfig'
    ];

    helpers.mockPrompt(this.app, {
      'someOption': true
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});
<commit_msg>updated to succeed tests<commit_after>/*global describe, beforeEach, it */
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;

describe('rkgttr generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('rkgttr:app', [
        '../../app'
      ]);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = [

    ];

    helpers.mockPrompt(this.app, {
      'someOption': true
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});
<|endoftext|>