<commit_before>
var simpleEvents = require('nodeunit').testCase;
var file = '../../lib/eventemitter2';
var EventEmitter2;

if(typeof require !== 'undefined') {
  EventEmitter2 = require(file).EventEmitter2;
}
else {
  EventEmitter2 = window.EventEmitter2;
}

module.exports = simpleEvents({

  '1. Add two listeners on a single event and emit the event.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA() { test.ok(true, 'The event was raised'); }
    function functionB() { test.ok(true, 'The event was raised'); }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2');

    test.expect(2);
    test.done();

  },
  '2. Add two listeners on a single event and emit the event twice.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA() { test.ok(true, 'The event was raised'); }
    function functionB() { test.ok(true, 'The event was raised'); }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2');
    emitter.emit('test2');

    test.expect(4);
    test.done();

  },
  '3. Add two listeners on a single event and emit the event with a parameter.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA(value1) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The event was raised');
    }

    function functionB(value1) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The event was raised');
    }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2', 'Hello, Node');

    test.expect(4);
    test.done();

  },
  '4. Add two listeners on an single event and emit the event twice with a parameter.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA(value1) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The event was raised');
    }

    function functionB(value1) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The event was raised');
    }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2', 'Hello, Node1');
    emitter.emit('test2', 'Hello, Node2');

    test.expect(8);
    test.done();

  },
  '5. Add two listeners on an single event and emit the event twice with multiple parameters.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA(value1, value2, value3) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The value named "value1" is OK');
      test.equal(typeof value2, 'string', 'The value named "value2" is OK');
      test.equal(typeof value3, 'string', 'The value named "value3" is OK');
    }

    function functionB(value1, value2, value3) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The value named "value1" is OK');
      test.equal(typeof value2, 'string', 'The value named "value2" is OK');
      test.equal(typeof value3, 'string', 'The value named "value3" is OK');
    }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2', 'Hello, Node1', 'Hello, Node2', 'Hello, Node3');
    emitter.emit('test2', 'Hello, Node1', 'Hello, Node2', 'Hello, Node3');

    test.expect(16);
    test.done();

  },
  '6. Check return values of emit.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA() { test.ok(true, 'The event was raised'); }

    emitter.on('test6', functionA);

    test.ok(emitter.emit('test6'), 'emit should return true after calling a listener');
    test.ok(!emitter.emit('other'), 'emit should return false when no listener was called');

    emitter.onAny(functionA);
    test.ok(emitter.emit('other'), 'emit should return true after calling an onAny() listener');

    test.expect(5);
    test.done();
  },

  '7. Check return values of wildcardEmitter.emit.': function (test) {
    var emitter = new EventEmitter2({ verbose: true, wildcard: true });
    function functionA() { test.ok(true, 'The event was raised'); }

    emitter.on('test7', functionA);
    emitter.on('wildcard.*', functionA);

    test.ok(emitter.emit('test7'), 'emit should return true after calling a listener');
    test.ok(emitter.emit('wildcard.7'), 'emit should return true after calling a wildcard listener');
    test.ok(!emitter.emit('other7'), 'emit should return false when no listener was called');
    test.ok(!emitter.emit('other.7'), 'emit should return false when no wildcard listener was called');

    test.expect(6);
    test.done();
  },

});

<commit_msg>Extended test coverage for emit method;<commit_after>
var simpleEvents = require('nodeunit').testCase;
var file = '../../lib/eventemitter2';
var EventEmitter2;

if(typeof require !== 'undefined') {
  EventEmitter2 = require(file).EventEmitter2;
}
else {
  EventEmitter2 = window.EventEmitter2;
}

module.exports = simpleEvents({

  '1. Add two listeners on a single event and emit the event.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA() { test.ok(true, 'The event was raised'); }
    function functionB() { test.ok(true, 'The event was raised'); }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2');

    test.expect(2);
    test.done();

  },
  '2. Add two listeners on a single event and emit the event twice.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA() { test.ok(true, 'The event was raised'); }
    function functionB() { test.ok(true, 'The event was raised'); }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2');
    emitter.emit('test2');

    test.expect(4);
    test.done();

  },
  '3. Add two listeners on a single event and emit the event with a parameter.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA(value1) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The event was raised');
    }

    function functionB(value1) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The event was raised');
    }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2', 'Hello, Node');

    test.expect(4);
    test.done();

  },
  '4. Add two listeners on an single event and emit the event twice with a parameter.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA(value1) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The event was raised');
    }

    function functionB(value1) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The event was raised');
    }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2', 'Hello, Node1');
    emitter.emit('test2', 'Hello, Node2');

    test.expect(8);
    test.done();

  },
  '5. Add two listeners on an single event and emit the event twice with multiple parameters.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA(value1, value2, value3) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The value named "value1" is OK');
      test.equal(typeof value2, 'string', 'The value named "value2" is OK');
      test.equal(typeof value3, 'string', 'The value named "value3" is OK');
    }

    function functionB(value1, value2, value3) {
      test.ok(true, 'The event was raised');
      test.equal(typeof value1, 'string', 'The value named "value1" is OK');
      test.equal(typeof value2, 'string', 'The value named "value2" is OK');
      test.equal(typeof value3, 'string', 'The value named "value3" is OK');
    }

    emitter.on('test2', functionA);
    emitter.on('test2', functionB);

    emitter.emit('test2', 'Hello, Node1', 'Hello, Node2', 'Hello, Node3');
    emitter.emit('test2', 'Hello, Node1', 'Hello, Node2', 'Hello, Node3');

    test.expect(16);
    test.done();

  },
  '6. Check return values of emit.': function (test) {

    var emitter = new EventEmitter2({ verbose: true });

    function functionA() { test.ok(true, 'The event was raised'); }

    emitter.on('test6', functionA);

    test.ok(emitter.emit('test6'), 'emit should return true after calling a listener');
    test.ok(!emitter.emit('other'), 'emit should return false when no listener was called');

    emitter.onAny(functionA);
    test.ok(emitter.emit('other'), 'emit should return true after calling an onAny() listener');

    test.expect(5);
    test.done();
  },

  '7. Check return values of wildcardEmitter.emit.': function (test) {
    var emitter = new EventEmitter2({ verbose: true, wildcard: true });
    function functionA() { test.ok(true, 'The event was raised'); }

    emitter.on('test7', functionA);
    emitter.on('wildcard.*', functionA);

    test.ok(emitter.emit('test7'), 'emit should return true after calling a listener');
    test.ok(emitter.emit('wildcard.7'), 'emit should return true after calling a wildcard listener');
    test.ok(!emitter.emit('other7'), 'emit should return false when no listener was called');
    test.ok(!emitter.emit('other.7'), 'emit should return false when no wildcard listener was called');

    test.expect(6);
    test.done();
  },

  '8. Emit event with more than 2 arguments': function (test) {
    var emitter = new EventEmitter2({ verbose: true });

    emitter.on('test', function(x,y,z){
      test.equal(x, 1);
      test.equal(y, 2);
      test.equal(z, 3);
    });

    emitter.emit('test', 1, 2, 3);
    test.expect(3);
    test.done();
  }
});

<|endoftext|>


<commit_before>define(['ID'], function(ID) {
  describe("ID", function() {
    var id;

    beforeEach(function() {
      id = ID.create("test");
    });

    describe("#compareTo", function() {
      it("should return 1 if it is greater than other ID", function() {
        var otherId = ID.create("test");
        for (var i = 0; i < ID._BYTE_SIZE; i++) {
          otherId._bytes[i] = 0x00;
          if (id._bytes[i] !== 0x00) {
            break;
          }
        }
        expect(id.compareTo(otherId)).toBe(1);
      });

      it("should return -1 if it is smaller than other ID", function() {
        var otherId = ID.create("test");
        for (var i = 0; i < ID._BYTE_SIZE; i++) {
          otherId._bytes[i] = 0xff;
          if (id._bytes[i] !== 0xff) {
            break;
          }
        }
        expect(id.compareTo(otherId)).toBe(-1);
      });

      it("should return 0 if it is equal to other ID", function() {
        var otherId = ID.create("test");
        expect(id.compareTo(otherId)).toBe(0);
      });
    });

    describe("#equals", function() {
      it("should be equal to the same ID", function() {
        var otherId = ID.create("test");
        expect(id.equals(otherId)).toBeTruthy();
      });

      it("should not be equal to different ID", function() {
        var otherId = ID.create("other");
        expect(id.equals(otherId)).toBeFalsy();
      });

      it("should have reflexivity rule", function() {
        expect(id.equals(id)).toBeTruthy();
      });

      it("should have symmetry rule", function() {
        var otherId = ID.create("test");
        expect(id.equals(otherId)).toBeTruthy();
        expect(otherId.equals(id)).toBeTruthy();

        otherId = ID.create("other");
        expect(id.equals(otherId)).toBeFalsy();
        expect(otherId.equals(id)).toBeFalsy();
      });

      it("should have transitivity rule", function() {
        var otherId1 = ID.create("test");
        var otherId2 = ID.create("test");
        expect(id.equals(otherId1)).toBeTruthy();
        expect(otherId1.equals(otherId2)).toBeTruthy();
        expect(id.equals(otherId2)).toBeTruthy();
      });
    });

    describe("#toHexString", function() {
      it("should generate hex string", function() {
        var id = new ID([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                         0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                         0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
                         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f]);
        expect(id.toHexString()).toBe("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
      });
    });

    describe("#fromHexString", function() {
      it("should generate hex string", function() {
        var id = ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
        var otherId = new ID([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                              0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                              0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
                              0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f]);
        expect(id).toEqualId(otherId);
      });

      it("should throw error if invalid string passed", function() {
        expect(function() { ID.fromHexString(""); }).toThrowError();
        expect(function() { ID.fromHexString("ffffffff"); }).toThrowError();
        expect(function() {
          ID.fromHexString("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
        }).toThrowError();
      });
    });

    describe("#isInInterval", function() {
      var smallerId, largerId;

      beforeEach(function() {
        smallerId = ID.create("test");
        largerId = ID.create("test");
        for (var i = 0; i < ID._BYTE_SIZE; i++) {
          smallerId._bytes[i] = 0x00;
          if (id._bytes[i] !== 0x00) {
            break;
          }
        }
        for (var i = 0; i < ID._BYTE_SIZE; i++) {
          largerId._bytes[i] = 0xff;
          if (id._bytes[i] !== 0xff) {
            break;
          }
        }
      });

      it("should return true if id is in interval between two other IDs", function() {
        expect(id.isInInterval(smallerId, largerId)).toBeTruthy();
      });

      it("should return false if id is not in interval between two other IDs", function() {
        expect(id.isInInterval(largerId, smallerId)).toBeFalsy();
        expect(smallerId.isInInterval(id, largerId)).toBeFalsy();
      });

      it("should understand ID space is ring", function() {
        expect(largerId.isInInterval(id, smallerId)).toBeTruthy();
        expect(smallerId.isInInterval(largerId, id)).toBeTruthy();
      });
    });

    describe("#addPowerOfTwo", function() {
      it("should return ID added power of two", function() {
        id = ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
        expect(id.addPowerOfTwo(0)).toEqualId(
          ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e20"));
        expect(id.addPowerOfTwo(1)).toEqualId(
          ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e21"));
        expect(id.addPowerOfTwo(16)).toEqualId(
          ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1e1e1f"));
        expect(id.addPowerOfTwo(255)).toEqualId(
          ID.fromHexString("800102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"));
        expect(ID.fromHexString("800102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
               .addPowerOfTwo(255)).toEqualId(id);
        expect(ID.fromHexString("00000000000000000000000000000000ffffffffffffffffffffffffffffffff")
               .addPowerOfTwo(0)).toEqualId(
                 ID.fromHexString("0000000000000000000000000000000100000000000000000000000000000000"));
      });
    });
  });
});
<commit_msg>Add test cases to IDSpec.js.<commit_after>define(['ID'], function(ID) {
  describe("ID", function() {
    var id;

    beforeEach(function() {
      id = ID.create("test");
    });

    describe("#compareTo", function() {
      it("should return 1 if it is greater than other ID", function() {
        var otherId = ID.create("test");
        for (var i = 0; i < ID._BYTE_SIZE; i++) {
          otherId._bytes[i] = 0x00;
          if (id._bytes[i] !== 0x00) {
            break;
          }
        }
        expect(id.compareTo(otherId)).toBe(1);
      });

      it("should return -1 if it is smaller than other ID", function() {
        var otherId = ID.create("test");
        for (var i = 0; i < ID._BYTE_SIZE; i++) {
          otherId._bytes[i] = 0xff;
          if (id._bytes[i] !== 0xff) {
            break;
          }
        }
        expect(id.compareTo(otherId)).toBe(-1);
      });

      it("should return 0 if it is equal to other ID", function() {
        var otherId = ID.create("test");
        expect(id.compareTo(otherId)).toBe(0);
      });
    });

    describe("#equals", function() {
      it("should be equal to the same ID", function() {
        var otherId = ID.create("test");
        expect(id.equals(otherId)).toBeTruthy();
      });

      it("should not be equal to different ID", function() {
        var otherId = ID.create("other");
        expect(id.equals(otherId)).toBeFalsy();
      });

      it("should have reflexivity rule", function() {
        expect(id.equals(id)).toBeTruthy();
      });

      it("should have symmetry rule", function() {
        var otherId = ID.create("test");
        expect(id.equals(otherId)).toBeTruthy();
        expect(otherId.equals(id)).toBeTruthy();

        otherId = ID.create("other");
        expect(id.equals(otherId)).toBeFalsy();
        expect(otherId.equals(id)).toBeFalsy();
      });

      it("should have transitivity rule", function() {
        var otherId1 = ID.create("test");
        var otherId2 = ID.create("test");
        expect(id.equals(otherId1)).toBeTruthy();
        expect(otherId1.equals(otherId2)).toBeTruthy();
        expect(id.equals(otherId2)).toBeTruthy();
      });
    });

    describe("#toHexString", function() {
      it("should generate hex string", function() {
        var id = new ID([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                         0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                         0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
                         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f]);
        expect(id.toHexString()).toBe("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
      });
    });

    describe("#fromHexString", function() {
      it("should generate hex string", function() {
        var id = ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
        var otherId = new ID([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                              0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                              0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
                              0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f]);
        expect(id).toEqualId(otherId);
      });

      it("should throw error if invalid string passed", function() {
        expect(function() { ID.fromHexString(""); }).toThrowError();
        expect(function() { ID.fromHexString("ffffffff"); }).toThrowError();
        expect(function() {
          ID.fromHexString("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
        }).toThrowError();
      });
    });

    describe("#isInInterval", function() {
      var smallerId, largerId;

      beforeEach(function() {
        smallerId = ID.create("test");
        largerId = ID.create("test");
        for (var i = 0; i < ID._BYTE_SIZE; i++) {
          smallerId._bytes[i] = 0x00;
          if (id._bytes[i] !== 0x00) {
            break;
          }
        }
        for (var i = 0; i < ID._BYTE_SIZE; i++) {
          largerId._bytes[i] = 0xff;
          if (id._bytes[i] !== 0xff) {
            break;
          }
        }
      });

      it("should return true if id is in interval between two other IDs", function() {
        expect(id.isInInterval(smallerId, largerId)).toBeTruthy();
      });

      it("should return false if id is not in interval between two other IDs", function() {
        expect(id.isInInterval(largerId, smallerId)).toBeFalsy();
        expect(smallerId.isInInterval(id, largerId)).toBeFalsy();
      });

      it("should understand ID space is ring", function() {
        expect(largerId.isInInterval(id, smallerId)).toBeTruthy();
        expect(smallerId.isInInterval(largerId, id)).toBeTruthy();
      });

      it("should appropriately process max and min IDs", function() {
        var minId = ID.fromHexString("0000000000000000000000000000000000000000000000000000000000000000");
        var maxId = ID.fromHexString("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");

        expect(minId.isInInterval(smallerId, largerId)).toBeFalsy();
        expect(maxId.isInInterval(smallerId, largerId)).toBeFalsy();
        expect(minId.isInInterval(largerId, smallerId)).toBeTruthy();
        expect(maxId.isInInterval(largerId, smallerId)).toBeTruthy();
      });

      it("should return false if from or to are same as the sample", function() {
        expect(smallerId.isInInterval(smallerId, largerId)).toBeFalsy();
        expect(smallerId.isInInterval(largerId, smallerId)).toBeFalsy();
        expect(largerId.isInInterval(smallerId, largerId)).toBeFalsy();
        expect(largerId.isInInterval(largerId, largerId)).toBeFalsy();
      });
    });

    describe("#addPowerOfTwo", function() {
      it("should return ID added power of two", function() {
        id = ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
        expect(id.addPowerOfTwo(0)).toEqualId(
          ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e20"));
        expect(id.addPowerOfTwo(1)).toEqualId(
          ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e21"));
        expect(id.addPowerOfTwo(16)).toEqualId(
          ID.fromHexString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1e1e1f"));
        expect(id.addPowerOfTwo(255)).toEqualId(
          ID.fromHexString("800102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"));
        expect(ID.fromHexString("800102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
               .addPowerOfTwo(255)).toEqualId(id);
        expect(ID.fromHexString("00000000000000000000000000000000ffffffffffffffffffffffffffffffff")
               .addPowerOfTwo(0)).toEqualId(
                 ID.fromHexString("0000000000000000000000000000000100000000000000000000000000000000"));
      });
    });
  });
});
<|endoftext|>


<commit_before>import { define, html, dispatch } from '../../src';
import render, { update } from '../../src/render';

const resolveRaf = fn => new Promise((resolve) => {
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      Promise.resolve()
        .then(fn)
        .then(resolve);
    });
  });
});

const resolveTimeout = fn => new Promise((resolve) => {
  setTimeout(() => {
    Promise.resolve()
      .then(fn)
      .then(resolve);
  }, 250);
});

describe('render:', () => {
  define('test-render', {
    value: 0,
    property: '',
    render: ({ value }) => (host, shadowRoot) => {
      shadowRoot.innerHTML = `<div>${value}</div>`;
    },
  });

  const tree = test(`
    <test-render></test-render>
  `);

  it('throws if an argument is not a function', () => {
    expect(() => {
      define('test-render-throws', {
        render: {},
      });
    }).toThrow();
  });

  it('renders content', done => tree(el => resolveRaf(() => {
    expect(el.shadowRoot.children[0].textContent).toBe('0');
    done();
  })));

  it('updates content', done => tree(el => resolveRaf(() => {
    el.value = 1;
    return resolveRaf(() => {
      expect(el.shadowRoot.children[0].textContent).toBe('1');
      done();
    });
  })));

  it('does not render when element is out of the document', done => tree((el) => {
    const fragment = document.createDocumentFragment();
    fragment.appendChild(el);

    return resolveRaf(() => {
      expect(el.shadowRoot.innerHTML).toBe('');
      done();
    });
  }));

  it('does not render if getter does not change', done => tree(el => resolveRaf(() => {
    el.property = 'new value';
    return resolveRaf(() => {
      expect(el.shadowRoot.children[0].textContent).toBe('0');
      done();
    });
  })));

  it('renders content on direct call', () => tree((el) => {
    el.render();
    expect(el.shadowRoot.children[0].textContent).toBe('0');
  }));

  it('does not re-create shadow DOM', done => tree((el) => {
    const shadowRoot = el.shadowRoot;
    const parent = el.parentElement;
    parent.removeChild(el);

    return resolveRaf(() => {
      parent.appendChild(el);
      expect(el.shadowRoot).toBe(shadowRoot);
      done();
    });
  }));

  it('defer next update tasks after threshold', (done) => {
    define('test-render-long', {
      value: '',
      render: ({ value }) => (host, shadowRoot) => {
        const now = performance.now();
        while (performance.now() - now < 20);

        shadowRoot.innerHTML = `<div>${value}</div>`;
      },
    });

    test(`

        <test-render-long value="one"></test-render-long>
        <test-render-long value="two"></test-render-long>

    `)(el => new Promise((resolve) => {
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
            const [one, two] = el.children;
            expect(one.shadowRoot.children[0].textContent).toBe('one');
            expect(two.shadowRoot.children[0].textContent).toBe('two');
            expect(two.shadowRoot.children.length).toBe(1);
            resolve();
            done();
          });
        });
      });
    }));
  });

  it('update function catches error inside of the passed function', (done) => {
    define('test-render-throws-in-render', {
      render: () => {
        throw Error();
      },
    });

    test('<test-render-throws-in-render></test-render-throws-in-render>')((el) => {
      expect(() => {
        dispatch(el, '@invlidate', { bubbling: true, composed: true });
        update();
      }).toThrow();
      requestAnimationFrame(done);
    });
  });

  it('update function catches error inside of the passed function', (done) => {
    define('test-render-throws-in-callback', {
      render: () => () => { throw Error('example error'); },
    });

    test('<test-render-throws-in-callback></test-render-throws-in-callback>')((el) => {
      dispatch(el, '@invlidate', { bubbling: true, composed: true });
      update().catch((e) => {
        expect(e instanceof Error).toBe(true);
      });
    });

    requestAnimationFrame(done);
  });

  describe('shady css custom property scope', () => {
    const TestShadyChild = {
      value: 0,
      render: ({ value }) => html`
        ${value}

      `,
    };

    const TestShadyParent = {
      active: false,
      render: ({ active }) => html`
        <test-shady-child class="${{ active }}"></test-shady-child>

      `.define({ TestShadyChild }),
    };

    define('test-shady-parent', TestShadyParent);

    const shadyTree = test(`
      <test-shady-parent></test-shady-parent>
    `);

    it('should set custom property', done => shadyTree(el => resolveTimeout(() => {
      const { color } = window.getComputedStyle(el.shadowRoot.children[0].shadowRoot.children[0]);
      expect(color).toBe('rgb(255, 0, 0)');
      done();
    })));

    it('should update custom property', done => shadyTree(el => resolveTimeout(() => {
      el.active = true;
      return resolveTimeout(() => {
        const { color } = window.getComputedStyle(el.shadowRoot.children[0].shadowRoot.children[0]);
        expect(color).toBe('rgb(0, 0, 255)');
        done();
      });
    })));
  });

  it('renders elements in parent slot', (done) => {
    const TestRenderParentSlot = {
      render: () => html`<slot></slot>`,
    };

    define('test-render-parent-slot', TestRenderParentSlot);

    const slotTree = test(`
      <test-render-parent-slot>
        <test-render></test-render>
      </test-render-parent-slot>
    `);

    slotTree(el => resolveRaf(() => {
      expect(el.children[0].shadowRoot.children[0].textContent).toBe('0');
      done();
    }));
  });

  it('throws error for duplicate render', () => {
    const hybrids = {
      renderOne: render(() => () => {}),
      renderTwo: render(() => () => {}),
    };

    const el = document.createElement('div');

    expect(() => {
      hybrids.renderOne.connect(el, 'renderOne');
      hybrids.renderTwo.connect(el, 'renderTwo');
    }).toThrow();
  });
});
<commit_msg>test: add shadycss test case for render factory<commit_after>import { define, html, dispatch } from '../../src';
import render, { update } from '../../src/render';

const resolveRaf = fn => new Promise((resolve) => {
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      Promise.resolve()
        .then(fn)
        .then(resolve);
    });
  });
});

const resolveTimeout = fn => new Promise((resolve) => {
  setTimeout(() => {
    Promise.resolve()
      .then(fn)
      .then(resolve);
  }, 250);
});

describe('render:', () => {
  define('test-render', {
    value: 0,
    property: '',
    render: ({ value }) => (host, shadowRoot) => {
      shadowRoot.innerHTML = `<div>${value}</div>`;
    },
  });

  const tree = test(`
    <test-render></test-render>
  `);

  it('throws if an argument is not a function', () => {
    expect(() => {
      define('test-render-throws', {
        render: {},
      });
    }).toThrow();
  });

  it('renders content', done => tree(el => resolveRaf(() => {
    expect(el.shadowRoot.children[0].textContent).toBe('0');
    done();
  })));

  it('updates content', done => tree(el => resolveRaf(() => {
    el.value = 1;
    return resolveRaf(() => {
      expect(el.shadowRoot.children[0].textContent).toBe('1');
      done();
    });
  })));

  it('does not render when element is out of the document', done => tree((el) => {
    const fragment = document.createDocumentFragment();
    fragment.appendChild(el);

    return resolveRaf(() => {
      expect(el.shadowRoot.innerHTML).toBe('');
      done();
    });
  }));

  it('does not render if getter does not change', done => tree(el => resolveRaf(() => {
    el.property = 'new value';
    return resolveRaf(() => {
      expect(el.shadowRoot.children[0].textContent).toBe('0');
      done();
    });
  })));

  it('renders content on direct call', () => tree((el) => {
    el.render();
    expect(el.shadowRoot.children[0].textContent).toBe('0');
  }));

  it('does not re-create shadow DOM', done => tree((el) => {
    const shadowRoot = el.shadowRoot;
    const parent = el.parentElement;
    parent.removeChild(el);

    return resolveRaf(() => {
      parent.appendChild(el);
      expect(el.shadowRoot).toBe(shadowRoot);
      done();
    });
  }));

  it('defer next update tasks after threshold', (done) => {
    define('test-render-long', {
      value: '',
      render: ({ value }) => (host, shadowRoot) => {
        const now = performance.now();
        while (performance.now() - now < 20);

        shadowRoot.innerHTML = `<div>${value}</div>`;
      },
    });

    test(`

        <test-render-long value="one"></test-render-long>
        <test-render-long value="two"></test-render-long>

    `)(el => new Promise((resolve) => {
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
            const [one, two] = el.children;
            expect(one.shadowRoot.children[0].textContent).toBe('one');
            expect(two.shadowRoot.children[0].textContent).toBe('two');
            expect(two.shadowRoot.children.length).toBe(1);
            resolve();
            done();
          });
        });
      });
    }));
  });

  it('update function catches error inside of the passed function', (done) => {
    define('test-render-throws-in-render', {
      render: () => {
        throw Error();
      },
    });

    test('<test-render-throws-in-render></test-render-throws-in-render>')((el) => {
      expect(() => {
        dispatch(el, '@invlidate', { bubbling: true, composed: true });
        update();
      }).toThrow();
      requestAnimationFrame(done);
    });
  });

  it('update function catches error inside of the passed function', (done) => {
    define('test-render-throws-in-callback', {
      render: () => () => { throw Error('example error'); },
    });

    test('<test-render-throws-in-callback></test-render-throws-in-callback>')((el) => {
      dispatch(el, '@invlidate', { bubbling: true, composed: true });
      update().catch((e) => {
        expect(e instanceof Error).toBe(true);
      });
    });

    requestAnimationFrame(done);
  });

  describe('shady css custom property scope', () => {
    const TestShadyChild = {
      value: 0,
      render: ({ value }) => html`
        ${value}

      `,
    };

    const TestShadyParent = {
      active: false,
      render: ({ active }) => html`
        <test-shady-child class="${{ active }}"></test-shady-child>

      `.define({ TestShadyChild }),
    };

    define('test-shady-parent', TestShadyParent);

    const shadyTree = test(`
      <test-shady-parent></test-shady-parent>
    `);

    it('should set custom property', done => shadyTree(el => resolveTimeout(() => {
      const { color } = window.getComputedStyle(el.shadowRoot.children[0].shadowRoot.children[0]);
      expect(color).toBe('rgb(255, 0, 0)');
      done();
    })));

    it('should update custom property', done => shadyTree(el => resolveTimeout(() => {
      el.active = true;
      return resolveTimeout(() => {
        const { color } = window.getComputedStyle(el.shadowRoot.children[0].shadowRoot.children[0]);
        expect(color).toBe('rgb(0, 0, 255)');
        done();
      });
    })));
  });

  it('renders elements in parent slot', (done) => {
    const TestRenderParentSlot = {
      render: () => html`<slot></slot>`,
    };

    define('test-render-parent-slot', TestRenderParentSlot);

    const slotTree = test(`
      <test-render-parent-slot>
        <test-render></test-render>
      </test-render-parent-slot>
    `);

    slotTree(el => resolveRaf(() => {
      expect(el.children[0].shadowRoot.children[0].textContent).toBe('0');
      done();
    }));
  });

  it('throws error for duplicate render', () => {
    const hybrids = {
      renderOne: render(() => () => {}),
      renderTwo: render(() => () => {}),
    };

    const el = document.createElement('div');

    expect(() => {
      hybrids.renderOne.connect(el, 'renderOne');
      hybrids.renderTwo.connect(el, 'renderTwo');
    }).toThrow();
  });

  describe('shadyCSS polyfill', () => {
    const shadyCSSApplied = typeof window.ShadyCSS === 'object';

    beforeAll(() => {
      if (!shadyCSSApplied) {
        window.ShadyCSS = {
          prepareTemplate: template => template,
          styleElement: jasmine.createSpy(),
          styleSubtree: jasmine.createSpy(),
        };
      } else {
        spyOn(window.ShadyCSS, 'styleElement');
        spyOn(window.ShadyCSS, 'styleSubtree');
      }
    });

    afterAll(() => {
      if (!shadyCSSApplied) {
        delete window.ShadyCSS;
      }
    });

    it('uses styleElement and styleSubtree', done => tree(() => resolveTimeout(() => {
      expect(window.ShadyCSS.styleElement).toHaveBeenCalled();
      expect(window.ShadyCSS.styleSubtree).toHaveBeenCalled();
      done();
    })));
  });
});
<|endoftext|>


<commit_before>/* global describe, it */

import 'should';
import path from 'path';
import binSpecialParser from '../../src/special/bin';

describe('bin special parser', () => {
  it('should ignore when filename is not supported', () => {
    const result = binSpecialParser('content', 'not-supported.txt', [], '/root/dir');
    result.should.deepEqual([]);
  });

  function testBinSpecialParser(filename, serializer) {
    function testScript(script, dependencies) {
      const content = serializer(script);
      const deps = dependencies || ['binary-package'];
      const result = binSpecialParser(content, filename, deps, __dirname);
      return result;
    }

    it('should detect packages used in scripts', () =>
      testScript('binary-entry --argument').should.deepEqual(['binary-package']));

    it('should detect packages used as `.bin` path', () =>
      testScript('./node_modules/.bin/binary-entry').should.deepEqual(['binary-package']));

    it('should detect packages used as package path', () =>
      testScript('./node_modules/binary-package/bin/binary-exe').should.deepEqual(['binary-package']));

    it('should not report it when it is not used', () =>
      testScript('other-bin').should.deepEqual([]));

    it('should ignore detection when no scripts section', () =>
      testScript(false).should.deepEqual([]));

    it('should ignore the dependencies without bin entry', () =>
      testScript('no-binary', ['eslint-config-standard']).should.deepEqual([]));
  }

  describe('on `package.json`', () => {
    testBinSpecialParser(
      '/path/to/package.json',
      script => JSON.stringify(script ? { scripts: { t: script } } : {}));
  });

  describe('on `.travis.yml`', () => {
    testBinSpecialParser(
      '/path/to/.travis.yml',
      script => script ? `script:\n  - ${script}` : '');
  });
});
<commit_msg>Refactor the bin special parser test to data-driven + test helper pattern.<commit_after>/* global describe, it */

import 'should';
import parse from '../../src/special/bin';

const testCases = [
  {
    name: 'detect packages used in scripts',
    script: 'binary-entry --argument',
    dependencies: ['binary-package'],
    expected: ['binary-package'],
  },
  {
    name: 'detect packages used as `.bin` path',
    script: './node_modules/.bin/binary-entry',
    dependencies: ['binary-package'],
    expected: ['binary-package'],
  },
  {
    name: 'detect packages used as package path',
    script: './node_modules/binary-package/bin/binary-exe',
    dependencies: ['binary-package'],
    expected: ['binary-package'],
  },
  {
    name: 'not report it when it is not used',
    script: 'other-binary-entry',
    dependencies: ['binary-package'],
    expected: [],
  },
  {
    name: 'ignore detection when no scripts section',
    script: false,
    dependencies: ['binary-package'],
    expected: [],
  },
  {
    name: 'ignore the dependencies without bin entry',
    script: 'binary-entry',
    dependencies: ['eslint-config-standard'],
    expected: [],
  },
];

function testParser(testCase, content, filename) {
  const result = parse(content, filename, testCase.dependencies, __dirname);
  result.should.deepEqual(testCase.expected);
}

describe('bin special parser', () => {
  it('should ignore when filename is not supported', () => {
    const result = parse('content', 'not-supported.txt', [], '/root/dir');
    result.should.deepEqual([]);
  });

  describe('on `package.json`', () =>
    testCases.forEach(testCase =>
      it(`should ${testCase.name}`, () => {
        const content = testCase.script
          ? JSON.stringify({ scripts: { t: testCase.script } })
          : '{}';

        testParser(testCase, content, '/path/to/package.json');
      })));

  describe('on `.travis.yml`', () =>
    testCases.forEach(testCase =>
      it(`should ${testCase.name}`, () => {
        const content = testCase.script
          ? `script:\n  - ${testCase.script}`
          : '';

        testParser(testCase, content, '/path/to/.travis.yml');
      })));
});
<|endoftext|>


<commit_before>var LFSR = require('../index.js'),
    expect = require('chai').expect,
    utils = require('./utils.js'),
    bin = utils.bin,
    str = utils.str;

context('statistical', function() {
    utils.everyLength(function(n) {
        (function(n) {
            it('max length for n = ' + n + ' is ' + (Math.pow(2, n) - 1), function() {
                this.timeout(20000);

                var lfsr = new LFSR(n),
                    count = 0,
                    initial = lfsr.register;
                do {
                    lfsr.shift();
                    count++;
                } while (lfsr.register != initial);
                expect(count).to.equal(Math.pow(2, n) - 1);
            });
        })(n);
    });

    describe('distribution', function() {
        utils.everyLength(function(n) {
            (function(n) {
                it('evenly distributes bits for n = ' + n, function() {
                    var lfsr = new LFSR(),
                        occur = {'0': 0, '1': 0},
                        bit;
                    for (var i = 0; i < 100000; i++) {
                        bit = lfsr.shift();
                        occur[bit]++;
                    }
                    var ratio = occur['0'] / occur['1'];
                    expect(ratio).to.be.closeTo(1, 0.1);
                });
            })(n);
        });
    });
});
<commit_msg>increase timeout<commit_after>var LFSR = require('../index.js'),
    expect = require('chai').expect,
    utils = require('./utils.js'),
    bin = utils.bin,
    str = utils.str;

context('statistical', function() {
    utils.everyLength(function(n) {
        (function(n) {
            it('max length for n = ' + n + ' is ' + (Math.pow(2, n) - 1), function() {
                this.timeout(60000);

                var lfsr = new LFSR(n),
                    count = 0,
                    initial = lfsr.register;
                do {
                    lfsr.shift();
                    count++;
                } while (lfsr.register != initial);
                expect(count).to.equal(Math.pow(2, n) - 1);
            });
        })(n);
    });

    describe('distribution', function() {
        utils.everyLength(function(n) {
            (function(n) {
                it('evenly distributes bits for n = ' + n, function() {
                    var lfsr = new LFSR(),
                        occur = {'0': 0, '1': 0},
                        bit;
                    for (var i = 0; i < 100000; i++) {
                        bit = lfsr.shift();
                        occur[bit]++;
                    }
                    var ratio = occur['0'] / occur['1'];
                    expect(ratio).to.be.closeTo(1, 0.1);
                });
            })(n);
        });
    });
});
<|endoftext|>


<commit_before>import {readFile} from 'fs';
import test from 'ava';
import isPromise from 'is-promise';
import {processing, read} from './utils';
import beautify from '../src';

test('plugin beautify must be function', t => {
	t.plan(2);
	t.true(typeof beautify === 'function');
	t.true(typeof beautify() === 'function');
});

test('plugin beautify should return Error with use option sync', t => {
	const error = t.throws(() => {
		beautify()();
	}, TypeError);

	t.is(error.message, 'tree is not Array');
});

test('plugin beautify should return the passed value with use option sync', t => {
	const tree = [];

	t.deepEqual(tree, beautify()(tree));
});

test('processing with plugin beautify should not lost native api', async t => {
	t.plan(3);
	const fixture = '

\n\n

';
	t.true(
		Object.prototype.hasOwnProperty.call(
			await processing(fixture, [beautify({rules: {eof: false}})], {sync: true}).tree,
			'walk'
		)
	);
	t.true(
		Object.prototype.hasOwnProperty.call(
			await processing(fixture, [beautify({rules: {eof: false}})], {sync: true}).tree,
			'match'
		)
	);
	t.true(
		Object.prototype.hasOwnProperty.call(
			await processing(fixture, [beautify({rules: {eof: false}})], {sync: true}).tree,
			'processor'
		)
	);
});

test('processing with plugin beautify should return equal html', async t => {
	const fixture = '

\n\n

';
	t.deepEqual(fixture, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should removing trailing slash in self-closing', async t => {
	const fixture = '';
	const expected = '';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should removing empty attribute', async t => {
	const fixture = '';
	const expected = '';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}, mini: {removeAttribute: 'empty'}})])).html);
});

test('processing with plugin beautify should removes spaces at the equal sign', async t => {
	const fixture = '';
	const expected = '';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should return boolean attribute', async t => {
	const fixture = '<input type="email" required>';
	const expected = '<input type="email" required>';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should return trim attribute', async t => {
	const fixture = '';
	const expected = '';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should transform lower case attribute names', async t => {
	const fixture = '

';
	const expected = '

';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should transform lower case tag name', async t => {
	const fixture = '

';
	const expected = '

';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should return with indent', async t => {
	t.deepEqual(
		(await read('test/expected/output-indent.html')),
		(await processing(await read('test/fixtures/input-indent.html'), [beautify()])).html
	);
});

test('processing with plugin beautify and modules should return equal html using plugin posthtml-modules', async t => {
	t.deepEqual(
		(await read('test/expected/output-posthtml-modules.html')),
		(await processing(await read('test/fixtures/input-posthtml-modules.html'), [require('posthtml-modules')(), beautify()])).html
	);
});

test('processing with plugin beautify and include should return equal html using plugin posthtml-include', async t => {
	const expected = await read('test/expected/output-posthtml-include.html');
	const fixtures = (await processing(await read('test/fixtures/input-posthtml-include.html'), [require('posthtml-include')(), beautify()])).html;
	t.deepEqual(expected, fixtures);
});

test('processing with plugin beautify and include should return equal html which IE conditional comment', async t => {
	const expected = await read('test/expected/output-conditional-comment.html');
	const fixtures = (await processing(await read('test/fixtures/input-conditional-comment.html'), [require('posthtml-include')(), beautify()])).html;
	t.deepEqual(expected, fixtures);
});
<commit_msg>test: revrite check api to async<commit_after>import {readFile} from 'fs';
import test from 'ava';
import isPromise from 'is-promise';
import {processing, read} from './utils';
import beautify from '../src';

test('plugin beautify must be function', t => {
	t.plan(2);
	t.true(typeof beautify === 'function');
	t.true(typeof beautify() === 'function');
});

test('plugin beautify should return Error with use option sync', t => {
	const error = t.throws(() => {
		beautify()();
	}, TypeError);

	t.is(error.message, 'tree is not Array');
});

test('plugin beautify should return the passed value with use option sync', t => {
	const tree = [];

	t.deepEqual(tree, beautify()(tree));
});

test('processing with plugin beautify should not lost native api', async t => {
	t.plan(3);
	const fixture = '

\n\n

';
	t.true(
		Object.prototype.hasOwnProperty.call(
			(await processing(fixture, [beautify({rules: {eof: false}})])).tree,
			'walk'
		)
	);
	t.true(
		Object.prototype.hasOwnProperty.call(
			(await processing(fixture, [beautify({rules: {eof: false}})])).tree,
			'match'
		)
	);
	t.true(
		Object.prototype.hasOwnProperty.call(
			(await processing(fixture, [beautify({rules: {eof: false}})])).tree,
			'processor'
		)
	);
});

test('processing with plugin beautify should return equal html', async t => {
	const fixture = '

\n\n

';
	t.deepEqual(fixture, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should removing trailing slash in self-closing', async t => {
	const fixture = '';
	const expected = '';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should removing empty attribute', async t => {
	const fixture = '';
	const expected = '';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}, mini: {removeAttribute: 'empty'}})])).html);
});

test('processing with plugin beautify should removes spaces at the equal sign', async t => {
	const fixture = '';
	const expected = '';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should return boolean attribute', async t => {
	const fixture = '<input type="email" required>';
	const expected = '<input type="email" required>';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should return trim attribute', async t => {
	const fixture = '';
	const expected = '';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should transform lower case attribute names', async t => {
	const fixture = '

';
	const expected = '

';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should transform lower case tag name', async t => {
	const fixture = '

';
	const expected = '

';
	t.deepEqual(expected, (await processing(fixture, [beautify({rules: {eof: false}})])).html);
});

test('processing with plugin beautify should return with indent', async t => {
	t.deepEqual(
		(await read('test/expected/output-indent.html')),
		(await processing(await read('test/fixtures/input-indent.html'), [beautify()])).html
	);
});

test('processing with plugin beautify and modules should return equal html using plugin posthtml-modules', async t => {
	t.deepEqual(
		(await read('test/expected/output-posthtml-modules.html')),
		(await processing(await read('test/fixtures/input-posthtml-modules.html'), [require('posthtml-modules')(), beautify()])).html
	);
});

test('processing with plugin beautify and include should return equal html using plugin posthtml-include', async t => {
	const expected = await read('test/expected/output-posthtml-include.html');
	const fixtures = (await processing(await read('test/fixtures/input-posthtml-include.html'), [require('posthtml-include')(), beautify()])).html;
	t.deepEqual(expected, fixtures);
});

test('processing with plugin beautify and include should return equal html which IE conditional comment', async t => {
	const expected = await read('test/expected/output-conditional-comment.html');
	const fixtures = (await processing(await read('test/fixtures/input-conditional-comment.html'), [require('posthtml-include')(), beautify()])).html;
	t.deepEqual(expected, fixtures);
});
<|endoftext|>


<commit_before>/**
 * Created by bogdan on 5/6/16.
 */
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();

chai.use(chaiHttp);

describe("server", function() {

  it("should have a status of 404", function () {
    chai.request('http://localhost:1337')
        .get("/")
        .end(function(res){
          expect(res).to.have.status(404);
        });
  });

  // it("should return 'Hello, World!'", function () {
  //   chai.request('http://localhost:1337')
  //       .get("/")
  //       .end(function(err, res){
  //         res.body.should.be("Hello, Wold!");
  //       });
  // });

});
<commit_msg>two tests now working<commit_after>/**
 * Created by bogdan on 5/6/16.
 */
var chai = require('chai');
var chaiHttp = require('chai-http');
var expect = chai.expect;

chai.use(chaiHttp);

describe("server", function() {

  it("should have a status of 200", function (done) {
    chai.request('http://localhost:1337')
        .get("/")
        .end(function(err, res){
            expect(res).to.have.status(200);
            done();
        });
  });

  it("should return text/plain", function (done) {
    chai.request('http://localhost:1337')
        .get("/")
        .end(function(err, res){
          expect(res).to.have.header('content-type', 'text/plain');
          done();
        });
  });

  // it("should return 'Hello, World!", function (done) {
  //   chai.request('http://localhost:1337')
  //       .get("/")
  //       .end(function(err, res, body){
  //         var text = chai.load(body);
  //         expect(text).contains('Hello, World!');
  //         done();
  //       });
  // });

});
<|endoftext|>


<commit_before>var Db = require('../lib/db');
var config = require('./config.json');

module.exports = {
  init: init
};

function init() {
    var schema = config.schema || 'pgboss';
    var emptyJobsCommand = `truncate table ${schema}.job`;

    var db = new Db(config);

    return db.executeSql(emptyJobsCommand)
        .catch(error => console.error(error));
}<commit_msg>removed es6 template string in test helper for travis<commit_after>var Db = require('../lib/db');
var config = require('./config.json');

module.exports = {
  init: init
};

function init() {
    var schema = config.schema || 'pgboss';
    var emptyJobsCommand = 'truncate table ' + schema + '.job';

    var db = new Db(config);

    return db.executeSql(emptyJobsCommand)
        .catch(error => console.error(error));
}<|endoftext|>


<commit_before>
/*** Global Suite Setup and Tear Down ***/
var mongoose = require('mongoose');

/*** Setup ***/
before(function(done){
  chai                  = require('chai');
  should                = chai.should();
  expect                = chai.expect;
  User                  = mongoose.model('User');
  Post                  = mongoose.model('Post');
  FeedManager           = require('../model/feed_manager');
  FeedItem              = require('../model/feed_item');
  ActivityManager       = require('../model/activity_manager');
  UserConnectionManager = require('../model/user_connection_manager');
  helpers               = require('../lib/global_helpers');
  getObjectID           = helpers.getObjectID;
  containsObject        = helpers.containsObject;
  PostFixture           = require('./fixtures/posts.fixture');
  UserFixture           = require('./fixtures/users.fixture');
  ScenarioFixture = require('./fixtures/scenarios.fixture');
  Factory               = require('./factories');

  process.env.NODE_ENV = 'test';
  require('../app');
  done();
});

beforeEach(function(done){
  mongoose.connection.collections['users'].drop( function(err) {
    if (err && err.message != "ns not found" ) console.error(err);
    mongoose.connection.collections['posts'].drop( function(err) {
      if (err && err.message != "ns not found" ) console.error(err);
      done();
    });
  });
});

after(function(done){
  mongoose.models = {}
  mongoose.modelSchemas = {}
  mongoose.disconnect();
  done();
});

<commit_msg>Aligns (nit-pick commit)<commit_after>
/*** Global Suite Setup and Tear Down ***/
var mongoose = require('mongoose');

/*** Setup ***/
before(function(done){
  chai                  = require('chai');
  should                = chai.should();
  expect                = chai.expect;
  User                  = mongoose.model('User');
  Post                  = mongoose.model('Post');
  FeedManager           = require('../model/feed_manager');
  FeedItem              = require('../model/feed_item');
  ActivityManager       = require('../model/activity_manager');
  UserConnectionManager = require('../model/user_connection_manager');
  helpers               = require('../lib/global_helpers');
  getObjectID           = helpers.getObjectID;
  containsObject        = helpers.containsObject;
  PostFixture           = require('./fixtures/posts.fixture');
  UserFixture           = require('./fixtures/users.fixture');
  ScenarioFixture       = require('./fixtures/scenarios.fixture');
  Factory               = require('./factories');

  process.env.NODE_ENV = 'test';
  require('../app');
  done();
});

beforeEach(function(done){
  mongoose.connection.collections['users'].drop( function(err) {
    if (err && err.message != "ns not found" ) console.error(err);
    mongoose.connection.collections['posts'].drop( function(err) {
      if (err && err.message != "ns not found" ) console.error(err);
      done();
    });
  });
});

after(function(done){
  mongoose.models = {}
  mongoose.modelSchemas = {}
  mongoose.disconnect();
  done();
});

<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import SlidingPanelHeader from './slidingPanelHeader';
import { getClassNamesWithMods, getDataAttributes } from '../_helpers';

export default class SlidingPanel extends Component {
  constructor(props) {
    super(props);

    this.state = { isOverlayHidden: true, isActive: false };

    this.handleClickOverlay = this.handleClickOverlay.bind(this);
    this.handleActive = this.handleActive.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.handleTransitionEnd = this.handleTransitionEnd.bind(this);
  }

  static propTypes = {
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node,
    ]).isRequired,

    /**
     * When true, if the user clicks on the overaly, closes the panel.
     */
    closeOnOverlayClick: PropTypes.bool,

    /**
     * Hook that will be executed when trying to close a panel if exists.
     * If it returns false, the panel won't be closed.
     */
    onTryingToClose: PropTypes.func,

    /**
     * Data attributes. You can use it to set up any custom data-* attribute
     */
    dataAttrs: PropTypes.object,

    /**
     * You can provide set of custom modifications.
     */
    mods: PropTypes.arrayOf(PropTypes.string),

    /**
     * When defined, this function is triggered when the panel is closing.
     */
    onClose: PropTypes.func,

    /**
     * When defined, this custom node appears on the left part of the header
     */
    leftBlock: PropTypes.node,

    /**
     * When defined, this custom node appears on the right part of the header
     */
    rightBlock: PropTypes.node,

    /**
     * When defined, this function is triggered when the panel is opening.
     */
    onOpen: PropTypes.func,

    /**
     * Defines if the panel is open.
     */
    active: PropTypes.bool,

    /**
     * Defines title for header. Optional. If it's defined header will be shown.
     */
    title: PropTypes.string,
  }

  static defaultProps = {
    closeOnOverlayClick: true,
  }

  componentWillReceiveProps(newProps) {
    if (newProps.active !== this.state.isActive) {
      if (newProps.active) {
        this.handleActive();
      } else {
        this.handleClose();
      }
    }
  }

  componentDidMount() {
    const { active } = this.props;
    if (active) {
      this.handleActive();
    }

    this.panel.addEventListener('transitionend', this.handleTransitionEnd);

    this.closeButtons = this.panel.querySelectorAll('[data-rel="close"]');
    this.closeButtons.forEach(b => b.addEventListener('click', this.handleClose));
  }

  componentWillUnmount() {
    this.panel.removeEventListener('transitionend', this.handleTransitionEnd);
    this.closeButtons.forEach(b => b.removeEventListener('click', this.handleClose));
  }

  /**
   * Handles the click in the overlay.
   *
   * @method handleClickOverlay
   * @param {SyntheticEvent} e Click event trapped in the overlay element
   */
  handleClickOverlay(e) {
    if ((e.target === e.currentTarget) && this.props.closeOnOverlayClick) {
      this.handleClose();
    }
  }

  /**
   * Closes the panel.
   *
   * @method handleClose
   * @param {SyntheticEvent} e Click event trapped in the overlay element
   */
  handleClose() {
    const { onTryingToClose } = this.props;

    if (onTryingToClose && onTryingToClose() === false) {
      return;
    }

    this.setState({ isActive: false });
  }

  /**
   * Opens the panel
   *
   * @method handleActive
   */
  handleActive() {
    const { onOpen } = this.props;

    this.setState({ isOverlayHidden: false }, () => {
      setTimeout(() => {
        this.setState({ isActive: true }, () => {
          if (onOpen) {
            onOpen();
          }
        });
      }, 0);
    });
  }

  handleTransitionEnd(e) {
    const { onClose } = this.props;
    if (e.propertyName === 'transform') {
      this.setState({ isOverlayHidden: !this.state.isActive }, () => {
        if (this.state.isOverlayHidden && onClose) {
          onClose();
        }
      });
    }
  }

  render() {
    const {
      dataAttrs,
      children,
      title,
      leftBlock,
      rightBlock,
    } = this.props;

    const overlayMods = [];
    const panelMods = this.props.mods ? this.props.mods.slice() : [];

    if (this.state.isOverlayHidden) {
      overlayMods.push('hidden');
    }

    if (this.state.isActive) {
      panelMods.push('active');
    }

    const panelClass = 'ui-sliding-panel';
    const panelClassName = getClassNamesWithMods(panelClass, panelMods);

    const overlayClass = 'ui-sliding-panel-overlay';
    const overlayClassName = getClassNamesWithMods(overlayClass, overlayMods);

    return (

 { this.panel = e; }}
          {...getDataAttributes(dataAttrs)}
        >
          {title &&
            <SlidingPanelHeader
              leftBlock={leftBlock}
              rightBlock={rightBlock}
              title={title}
            />}

            {children}

    );
  }
}
<commit_msg>fixes NodeList to Array (#197)<commit_after>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import SlidingPanelHeader from './slidingPanelHeader';
import { getClassNamesWithMods, getDataAttributes } from '../_helpers';

export default class SlidingPanel extends Component {
  constructor(props) {
    super(props);

    this.state = { isOverlayHidden: true, isActive: false };

    this.handleClickOverlay = this.handleClickOverlay.bind(this);
    this.handleActive = this.handleActive.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.handleTransitionEnd = this.handleTransitionEnd.bind(this);
  }

  static propTypes = {
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node,
    ]).isRequired,

    /**
     * When true, if the user clicks on the overaly, closes the panel.
     */
    closeOnOverlayClick: PropTypes.bool,

    /**
     * Hook that will be executed when trying to close a panel if exists.
     * If it returns false, the panel won't be closed.
     */
    onTryingToClose: PropTypes.func,

    /**
     * Data attributes. You can use it to set up any custom data-* attribute
     */
    dataAttrs: PropTypes.object,

    /**
     * You can provide set of custom modifications.
     */
    mods: PropTypes.arrayOf(PropTypes.string),

    /**
     * When defined, this function is triggered when the panel is closing.
     */
    onClose: PropTypes.func,

    /**
     * When defined, this custom node appears on the left part of the header
     */
    leftBlock: PropTypes.node,

    /**
     * When defined, this custom node appears on the right part of the header
     */
    rightBlock: PropTypes.node,

    /**
     * When defined, this function is triggered when the panel is opening.
     */
    onOpen: PropTypes.func,

    /**
     * Defines if the panel is open.
     */
    active: PropTypes.bool,

    /**
     * Defines title for header. Optional. If it's defined header will be shown.
     */
    title: PropTypes.string,
  }

  static defaultProps = {
    closeOnOverlayClick: true,
  }

  componentWillReceiveProps(newProps) {
    if (newProps.active !== this.state.isActive) {
      if (newProps.active) {
        this.handleActive();
      } else {
        this.handleClose();
      }
    }
  }

  componentDidMount() {
    const { active } = this.props;
    if (active) {
      this.handleActive();
    }

    this.panel.addEventListener('transitionend', this.handleTransitionEnd);

    this.closeButtons = [].slice.call(this.panel.querySelectorAll('[data-rel="close"]'));
    this.closeButtons.forEach(b => b.addEventListener('click', this.handleClose));
  }

  componentWillUnmount() {
    this.panel.removeEventListener('transitionend', this.handleTransitionEnd);
    this.closeButtons.forEach(b => b.removeEventListener('click', this.handleClose));
  }

  /**
   * Handles the click in the overlay.
   *
   * @method handleClickOverlay
   * @param {SyntheticEvent} e Click event trapped in the overlay element
   */
  handleClickOverlay(e) {
    if ((e.target === e.currentTarget) && this.props.closeOnOverlayClick) {
      this.handleClose();
    }
  }

  /**
   * Closes the panel.
   *
   * @method handleClose
   * @param {SyntheticEvent} e Click event trapped in the overlay element
   */
  handleClose() {
    const { onTryingToClose } = this.props;

    if (onTryingToClose && onTryingToClose() === false) {
      return;
    }

    this.setState({ isActive: false });
  }

  /**
   * Opens the panel
   *
   * @method handleActive
   */
  handleActive() {
    const { onOpen } = this.props;

    this.setState({ isOverlayHidden: false }, () => {
      setTimeout(() => {
        this.setState({ isActive: true }, () => {
          if (onOpen) {
            onOpen();
          }
        });
      }, 0);
    });
  }

  handleTransitionEnd(e) {
    const { onClose } = this.props;
    if (e.propertyName === 'transform') {
      this.setState({ isOverlayHidden: !this.state.isActive }, () => {
        if (this.state.isOverlayHidden && onClose) {
          onClose();
        }
      });
    }
  }

  render() {
    const {
      dataAttrs,
      children,
      title,
      leftBlock,
      rightBlock,
    } = this.props;

    const overlayMods = [];
    const panelMods = this.props.mods ? this.props.mods.slice() : [];

    if (this.state.isOverlayHidden) {
      overlayMods.push('hidden');
    }

    if (this.state.isActive) {
      panelMods.push('active');
    }

    const panelClass = 'ui-sliding-panel';
    const panelClassName = getClassNamesWithMods(panelClass, panelMods);

    const overlayClass = 'ui-sliding-panel-overlay';
    const overlayClassName = getClassNamesWithMods(overlayClass, overlayMods);

    return (

 { this.panel = e; }}
          {...getDataAttributes(dataAttrs)}
        >
          {title &&
            <SlidingPanelHeader
              leftBlock={leftBlock}
              rightBlock={rightBlock}
              title={title}
            />}

            {children}

    );
  }
}
<|endoftext|>


<commit_before>var SmartLogic = {
  getToken: function() {
    tokenNeeded = !window.localStorage.getItem('ses_token')

    msInDay = 86400000
    tokenExpired = (Date.now() - window.localStorage.getItem('ses_issued')) / msInDay >= 14

    if ( refresh || (tokenNeeded || tokenExpired) ) {
      return $.get(
        '/ses-token/'
      ).then(function(response) {
          window.localStorage.setItem('ses_token', response.access_token);
          window.localStorage.setItem('ses_issued', Date.now());
      }).fail(function() {
          console.log('Failed to retrieve token');
      });
    };
  },
  buildServiceUrl: function(query) {
    return 'https://cloud.smartlogic.com/svc/0ef5d755-1f43-4a7e-8b06-7591bed8d453/ses/CombinedModel/hints/' + query + '.json?FILTER=AT=System:%20Legistar';
  }
};

/* Attaches autocomplete to the input div specified by the id passed */
function autocompleteSearchBar(element) {
  $(element).autocomplete({
    serviceUrl: SmartLogic.buildServiceUrl,
    ajaxSettings: {
      beforeSend: function (xhr) {
        SmartLogic.getToken();
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('Authorization', 'Bearer ' + window.localStorage.getItem('ses_token'));
      },
      data: {}
    },
    paramName: '',
    transformResult: function(response) {
      var res = JSON.parse(response);
      if (res.status_code == 500 || res.termHints.length < 1) {
        return {
          suggestions: ['No topics found']
        };
      } else {
        return {
          suggestions: $.map(res.termHints, function(d) {
              /* If the search term is an acronym, displays that as a part of the suggestion */
              var nature = '';
              if (d.values[0]['nature'] == 'NPT') {
                nature = d.values[0]['value'];
                nature = ' (' + nature + ')';
              }
              return {'value': d.name + nature, 'data': d.id};
            }
          )
        };
      }
    },
    onSelect: function(suggestion) {
      $.when(
        $.get('/topic/', { 'guid': suggestion.data })
      ).then(function(response) {
        if (response.status_code == 200) {
          var base = '/search/?q=';
          var url = base + response.subject_safe;
          window.location.href = url;
        };
      });
    },
    deferRequestBy: 100
  });
};
<commit_msg>removing reference to refresh parameter<commit_after>var SmartLogic = {
  getToken: function() {
    tokenNeeded = !window.localStorage.getItem('ses_token')

    msInDay = 86400000
    tokenExpired = (Date.now() - window.localStorage.getItem('ses_issued')) / msInDay >= 14

    if ( (tokenNeeded || tokenExpired) ) {
      return $.get(
        '/ses-token/'
      ).then(function(response) {
          window.localStorage.setItem('ses_token', response.access_token);
          window.localStorage.setItem('ses_issued', Date.now());
      }).fail(function() {
          console.log('Failed to retrieve token');
      });
    };
  },
  buildServiceUrl: function(query) {
    return 'https://cloud.smartlogic.com/svc/0ef5d755-1f43-4a7e-8b06-7591bed8d453/ses/CombinedModel/hints/' + query + '.json?FILTER=AT=System:%20Legistar';
  }
};

/* Attaches autocomplete to the input div specified by the id passed */
function autocompleteSearchBar(element) {
  $(element).autocomplete({
    serviceUrl: SmartLogic.buildServiceUrl,
    ajaxSettings: {
      beforeSend: function (xhr) {
        SmartLogic.getToken();
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('Authorization', 'Bearer ' + window.localStorage.getItem('ses_token'));
      },
      data: {}
    },
    paramName: '',
    transformResult: function(response) {
      var res = JSON.parse(response);
      if (res.status_code == 500 || res.termHints.length < 1) {
        return {
          suggestions: ['No topics found']
        };
      } else {
        return {
          suggestions: $.map(res.termHints, function(d) {
              /* If the search term is an acronym, displays that as a part of the suggestion */
              var nature = '';
              if (d.values[0]['nature'] == 'NPT') {
                nature = d.values[0]['value'];
                nature = ' (' + nature + ')';
              }
              return {'value': d.name + nature, 'data': d.id};
            }
          )
        };
      }
    },
    onSelect: function(suggestion) {
      $.when(
        $.get('/topic/', { 'guid': suggestion.data })
      ).then(function(response) {
        if (response.status_code == 200) {
          var base = '/search/?q=';
          var url = base + response.subject_safe;
          window.location.href = url;
        };
      });
    },
    deferRequestBy: 100
  });
};
<|endoftext|>