<commit_before>'use strict';

describe('uiSortable', function() {

  beforeEach(module(function($compileProvider) {
    if (typeof $compileProvider.debugInfoEnabled === 'function') {
      $compileProvider.debugInfoEnabled(false);
    }
  }));

  // Ensure the sortable angular module is loaded
  beforeEach(module('ui.sortable'));
  beforeEach(module('ui.sortable.testHelper'));

  var EXTRA_DY_PERCENTAGE, listContent, beforeLiElement, afterLiElement;

  beforeEach(inject(function (sortableTestHelper) {
    EXTRA_DY_PERCENTAGE = sortableTestHelper.EXTRA_DY_PERCENTAGE;
    listContent = sortableTestHelper.listContent;
    beforeLiElement = sortableTestHelper.extraElements && sortableTestHelper.extraElements.beforeLiElement;
    afterLiElement = sortableTestHelper.extraElements && sortableTestHelper.extraElements.afterLiElement;
  }));

  tests.description = 'Custom directive options related';
  function tests (useExtraElements) {

    var host;

    beforeEach(inject(function() {
      host = $('

');
      $('body').append(host);

      if (!useExtraElements) {
        beforeLiElement = afterLiElement = '';
      }
    }));

    afterEach(function() {
      host.remove();
      host = null;
    });

    it('should work when "ui-floating: false" option is used', function() {
      inject(function($compile, $rootScope) {
        var element;
        element = $compile(''.concat(
          '
',
          beforeLiElement,
          '
{{ item }}
',
          afterLiElement,
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': false
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element);

        var li = element.find('[ng-repeat]:eq(0)');
        var dy = (1 + EXTRA_DY_PERCENTAGE) * li.outerHeight();
        li.simulate('drag', { dy: dy });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dy = (1 + EXTRA_DY_PERCENTAGE) * li.outerHeight();
        li.simulate('drag', { dy: dy });
        expect($rootScope.items).toEqual(['Two', 'Three', 'One']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dy = (1 + EXTRA_DY_PERCENTAGE) * li.outerHeight();
        li.simulate('drag', { dy: dy });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        $(element).remove();
      });
    });

    it('should work when "ui-floating: true" option is used', function() {
      inject(function($compile, $rootScope) {
        var element;
        element = $compile(''.concat(
          '
',
          beforeEach,
          '
{{ item }}
',
          afterLiElement,
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': true
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element).append('

');

        var li = element.find('[ng-repeat]:eq(0)');
        var dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'Three', 'One']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx, moves: 5 });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        $(element).remove();
      });
    });

    it('should work when "ui-floating: \'auto\'" option is used and elements are "float"ing', function() {
      inject(function($compile, $rootScope) {
        var element;
        element = $compile(''.concat(
          '
',
          beforeEach,
          '
{{ item }}
',
          afterLiElement,
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': 'auto'
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element).append('

');

        var li = element.find('[ng-repeat]:eq(0)');
        var dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'Three', 'One']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx, moves: 5 });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        $(element).remove();
      });
    });

    it('should work when "ui-floating: \'auto\'" option is used and elements are "display: inline-block"', function() {
      inject(function($compile, $rootScope) {
        var element;
        element = $compile(''.concat(
          '
',
          beforeLiElement.replace('
', '
'),
          '
{{ item }}
',
          afterLiElement.replace('
', '
'),
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': 'auto'
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element);

        var li = element.find('[ng-repeat]:eq(0)');
        var dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'Three', 'One']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx, moves: 5 });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        $(element).remove();
      });
    });

    it('should properly reset deleted directive options', function() {
      inject(function($compile, $rootScope) {
        var element, logsElement;
        element = $compile(''.concat(
          '
',
          beforeLiElement,
          '
{{ item }}
',
          afterLiElement +
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': true
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element).append(logsElement);

        var sortableWidgetInstance = element.data('ui-sortable');

        expect(sortableWidgetInstance.floating).toBe(true);

        $rootScope.$digest();

        $rootScope.$apply(function() {
          $rootScope.opts = {};
        });

        var li = element.find('[ng-repeat]:eq(1)');
        var dy = (1 + EXTRA_DY_PERCENTAGE) * li.outerHeight();
        li.simulate('drag', { dy: dy });
        expect($rootScope.items).toEqual(['One', 'Three', 'Two']);
        expect($rootScope.items).toEqual(listContent(element));
        expect(sortableWidgetInstance.floating).toBe(false);

        $(element).remove();
        $(logsElement).remove();
      });
    });

  }

  [0, 1].forEach(function(useExtraElements){
    var testDescription = tests.description;

    if (useExtraElements) {
      testDescription += ' with extra elements';
    }

    describe(testDescription, function(){
      tests(useExtraElements);
    });
  });

});<commit_msg>test(directiveOptions): fix typos, correcting tests<commit_after>'use strict';

describe('uiSortable', function() {

  beforeEach(module(function($compileProvider) {
    if (typeof $compileProvider.debugInfoEnabled === 'function') {
      $compileProvider.debugInfoEnabled(false);
    }
  }));

  // Ensure the sortable angular module is loaded
  beforeEach(module('ui.sortable'));
  beforeEach(module('ui.sortable.testHelper'));

  var EXTRA_DY_PERCENTAGE, listContent, beforeLiElement, afterLiElement;

  beforeEach(inject(function (sortableTestHelper) {
    EXTRA_DY_PERCENTAGE = sortableTestHelper.EXTRA_DY_PERCENTAGE;
    listContent = sortableTestHelper.listContent;
    beforeLiElement = sortableTestHelper.extraElements && sortableTestHelper.extraElements.beforeLiElement;
    afterLiElement = sortableTestHelper.extraElements && sortableTestHelper.extraElements.afterLiElement;
  }));

  tests.description = 'Custom directive options related';
  function tests (useExtraElements) {

    var host;

    beforeEach(inject(function() {
      host = $('

');
      $('body').append(host);

      if (!useExtraElements) {
        beforeLiElement = afterLiElement = '';
      }
    }));

    afterEach(function() {
      host.remove();
      host = null;
    });

    it('should work when "ui-floating: false" option is used', function() {
      inject(function($compile, $rootScope) {
        var element;
        element = $compile(''.concat(
          '
',
          beforeLiElement,
          '
{{ item }}
',
          afterLiElement,
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': false
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element);

        var li = element.find('[ng-repeat]:eq(0)');
        var dy = (1 + EXTRA_DY_PERCENTAGE) * li.outerHeight();
        li.simulate('drag', { dy: dy });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dy = (1 + EXTRA_DY_PERCENTAGE) * li.outerHeight();
        li.simulate('drag', { dy: dy });
        expect($rootScope.items).toEqual(['Two', 'Three', 'One']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dy = (1 + EXTRA_DY_PERCENTAGE) * li.outerHeight();
        li.simulate('drag', { dy: dy });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        $(element).remove();
      });
    });

    it('should work when "ui-floating: true" option is used', function() {
      inject(function($compile, $rootScope) {
        var element;
        element = $compile(''.concat(
          '
',
          beforeLiElement.replace('
', '
'),
          '
{{ item }}
',
          afterLiElement.replace('
', '
'),
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': true
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element).append('

');

        var li = element.find('[ng-repeat]:eq(0)');
        var dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'Three', 'One']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx, moves: 5 });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        $(element).remove();
      });
    });

    it('should work when "ui-floating: \'auto\'" option is used and elements are "float"ing', function() {
      inject(function($compile, $rootScope) {
        var element;
        element = $compile(''.concat(
          '
',
          beforeLiElement.replace('
', '
'),
          '
{{ item }}
',
          afterLiElement.replace('
', '
'),
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': 'auto'
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element).append('

');

        var li = element.find('[ng-repeat]:eq(0)');
        var dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'Three', 'One']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx, moves: 5 });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        $(element).remove();
      });
    });

    it('should work when "ui-floating: \'auto\'" option is used and elements are "display: inline-block"', function() {
      inject(function($compile, $rootScope) {
        var element;
        element = $compile(''.concat(
          '
',
          beforeLiElement.replace('
', '
'),
          '
{{ item }}
',
          afterLiElement.replace('
', '
'),
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': 'auto'
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element);

        var li = element.find('[ng-repeat]:eq(0)');
        var dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx });
        expect($rootScope.items).toEqual(['Two', 'Three', 'One']);
        expect($rootScope.items).toEqual(listContent(element));

        li = element.find('[ng-repeat]:eq(1)');
        dx = (1 + EXTRA_DY_PERCENTAGE) * li.outerWidth();
        li.simulate('drag', { dx: dx, moves: 5 });
        expect($rootScope.items).toEqual(['Two', 'One', 'Three']);
        expect($rootScope.items).toEqual(listContent(element));

        $(element).remove();
      });
    });

    it('should properly reset deleted directive options', function() {
      inject(function($compile, $rootScope) {
        var element, logsElement;
        element = $compile(''.concat(
          '
',
          beforeLiElement,
          '
{{ item }}
',
          afterLiElement +
          '
'))($rootScope);
        $rootScope.$apply(function() {
          $rootScope.opts = {
            'ui-floating': true
          };
          $rootScope.items = ['One', 'Two', 'Three'];
        });

        host.append(element).append(logsElement);

        var sortableWidgetInstance = element.data('ui-sortable');

        expect(sortableWidgetInstance.floating).toBe(true);

        $rootScope.$digest();

        $rootScope.$apply(function() {
          $rootScope.opts = {};
        });

        var li = element.find('[ng-repeat]:eq(1)');
        var dy = (1 + EXTRA_DY_PERCENTAGE) * li.outerHeight();
        li.simulate('drag', { dy: dy });
        expect($rootScope.items).toEqual(['One', 'Three', 'Two']);
        expect($rootScope.items).toEqual(listContent(element));
        expect(sortableWidgetInstance.floating).toBe(false);

        $(element).remove();
        $(logsElement).remove();
      });
    });

  }

  [0, 1].forEach(function(useExtraElements){
    var testDescription = tests.description;

    if (useExtraElements) {
      testDescription += ' with extra elements';
    }

    describe(testDescription, function(){
      tests(useExtraElements);
    });
  });

});<|endoftext|>


<commit_before>var big = require('../')
var tape = require('tape')

function B () {
  return new Buffer([].slice.call(arguments))
}

function equal(t, a, b, message) {
  t.deepEqual(a.toJSON(), b.toJSON(), message)
}

function createTest(t, forward, reverse, mutate) {
  return function (a, b, c) {
    var r, r2

    equal(t, r = big[forward](a, b), c,
      r.inspect() + ' == ' + forward + '('+a.inspect()+', ' + b.inspect()+')')

    if(reverse)
      equal(t, r2 = big[reverse](r, b), a,
        r2.inspect() + ' == ' + reverse + '('+a.inspect()+', ' + b.inspect()+')')

    if(mutate) {
      var _a = new Buffer(a)

      equal(t, r = big[forward](_a, b, _a), c,
        _a.inspect() + ' == ' + forward + '('+a.inspect()+', ' + b.inspect()+', m)')

      if(reverse)
        equal(t, big[reverse](r, b, r), a,
          _a.inspect() + ' == ' + forward + '('+r.inspect()+', ' + b.inspect()+')')
    }
  }
}

tape('add/sub with mutate', function (t) {

  var test = createTest(t, 'add', 'sub', true)

  //simple
  test(B(0, 1),    B(1, 0),    B(1, 1))

  //carry
  test(B(0x80, 0), B(0x80, 0), B(0, 1))

  //carry
  test(B(0x80, 0), B(0x80, 0), B(0, 1))

  //two carries
  test(B(0x80, 0xff, 0), B(0x80, 0, 0), B(0, 0, 1))

  //xfffff + 0xffff == 0x1fffe
  test(B(0xff, 0xff, 0), B(0xff, 0xff, 0), B(0xfe, 0xff, 0x01))
  t.end()
})

tape('ADD - add two buffers', function (t) {
  var a = new Buffer([0x01, 0x02, 0x03])
  var b = new Buffer([0x04, 0x04, 0x06])
  var c = new Buffer([0x05, 0x06, 0x09])
  equal(t, big.add(a, b),      c)
  equal(t, big.subtract(c, b), a)
  equal(t, big.subtract(c, a), b)
  t.end()
})

tape('ADD - add with with carry', function (t) {
  var a = new Buffer([0xf0, 0x00, 0x00])
  var b = new Buffer([0x13, 0x07, 0x00])
  var c = new Buffer([0x03, 0x08, 0x00])
  equal(t, big.add(a, b),      c)
  equal(t, big.subtract(c, b), a)
  equal(t, big.subtract(c, a), b)
  t.end()
})

tape('add with carry2', function (t) {
  var a = new Buffer([0xf0, 0xff, 0x00])
  var b = new Buffer([0x13, 0x00, 0x00])
  var c = big.add(a, b)
  equal(t, c, new Buffer([0x03, 0x00, 0x01]))
  t.end()
})

tape('ADD - carry over', function (t) {
  var a = new Buffer([0xff, 0xff, 0xff])
  var b = new Buffer([0x01, 0x00, 0x00])
  var c = big.add(a, b, new Buffer(4))
  equal(t, c, new Buffer([0x00, 0x00, 0x00, 0x01]))
  t.end()
})

tape('multiply', function (t) {
  var a = new Buffer([0x01, 0x02, 0x03])
  var b = new Buffer([0x02, 0x00, 0x00])
  var c = new Buffer([0x02, 0x04, 0x06])
  equal(t, big.mul(a, b), c)
  t.end()
})

tape('multiply - carry', function (t) {
  var a = new Buffer([0x10, 0x00])
  var b = new Buffer([0x10, 0x00])
  var c = new Buffer([0x00, 0x01])
  equal(t, big.mul(a, b), c)
  t.end()
})

tape('multiply - carry2', function (t) {
  var a = new Buffer([0x00, 0x10])
  var b = new Buffer([0x00, 0x10])
  var c = new Buffer([0x00, 0x00, 0x00, 0x01])
  equal(t, big.mul(a, b, new Buffer(4)), c)
  t.end()
})

tape('multiply - carry3', function (t) {
  var a = new Buffer([0x10, 0x10])
  var b = new Buffer([0x10, 0x10])
  var c = new Buffer([0x00, 0x01, 0x02, 0x01])
  equal(t, big.mul(a, b, new Buffer(4)), c)
  t.end()
})

tape('multiply - carry3', function (t) {
  var a = new Buffer([0x12, 0x34])
  var b = new Buffer([0x56, 0x78])
  var c = new Buffer([0x0c, 0xee, 0x79, 0x18])
  equal(t, big.mul(a, b, new Buffer(4)), c)
  t.end()
})

tape('modInt', function (t) {
  var a = new Buffer([0, 0, 0x12, 0x34])
  equal(t, big.modInt(a, 0x13), new Buffer([0x11, 0, 0, 0]))
  t.end()
})

tape('modInt2', function (t) {
  var a = new Buffer([0, 0, 0, 0, 0x12, 0x34])
  equal(t, big.modInt(a, 0x130000), new Buffer([0, 0, 0x11, 0, 0, 0]))
  t.end()
})

tape('modInt3', function (t) {
  var a = new Buffer([0x12, 0x34, 0x56, 0x78, 0x9a, 0, 0, 0])
  equal(t, big.modInt(a, 0x123456), new Buffer([0xea, 0x47, 0x08, 0, 0, 0, 0, 0]))
  t.end()
})

tape('modInt4', function (t) {
  var a = B(0xab, 0x33, 0, 0)
  equal(t, big.modInt(a, 28), new Buffer([11, 0, 0, 0]))
  t.end()
})

tape('compare', function (t) {
  var a = B(0, 0, 0, 0, 1), b = B(0, 0, 0, 0, 2)
  t.equal(big.compare(a, b), -1)
  t.equal(big.compare(b, a), 1)
  t.equal(big.compare(a, a), 0)
  t.equal(big.compare(b, b), 0)
  var c = B(126, 99, 2, 0, 1, 2, 0x4a, 0xff), d = B(127, 99, 2, 0, 1, 2, 0x4a, 0xff)
  t.equal(big.compare(c, d), -1)
  t.equal(big.compare(d, c), 1)
  t.equal(big.compare(c, c), 0)
  t.equal(big.compare(d, d), 0)
  t.end()
})

tape('shift 1', function (t) {
  equal(t, big.shift(B(0, 1), 1), B(0, 2))
  equal(t, big.shift(B(0, 1), 2), B(0, 4))
  equal(t, big.shift(B(0, 1), 3), B(0, 8))
  equal(t, big.shift(B(1, 0), 3), B(8, 0))
  equal(t, big.shift(B(0x80, 0), 1), B(0, 1))
  t.end()
})
tape('shift 2, reverse', function (t) {
  equal(t, big.shift(B(0, 2), -1), B(0, 1))
  equal(t, big.shift(B(0, 4), -2), B(0, 1))
  equal(t, big.shift(B(0, 8), -3), B(0, 1))
  equal(t, big.shift(B(8, 0), -3), B(1, 0))
  equal(t, big.shift(B(0, 1), -1), B(0x80, 0))
  t.end()
})

tape('shift2', function (t) {
  equal(t, big.shift(B(0, 1, 0),  9), B(0, 0, 2))
  equal(t, big.shift(B(0, 1, 0), 10), B(0, 0, 4))
  equal(t, big.shift(B(0, 1, 0), 11), B(0, 0, 8))
  equal(t, big.shift(B(1, 0, 0), 11), B(0, 8, 0))
  equal(t, big.shift(B(0x80, 0, 0),  9), B(0, 0, 1))

  equal(t, big.shift(B(0, 0, 2), -17), B(1, 0, 0))
  equal(t, big.shift(B(0, 0, 4), -17), B(2, 0, 0))
  equal(t, big.shift(B(0, 0, 8), -17), B(4, 0, 0))
  equal(t, big.shift(B(0, 8, 0), -11), B(1, 0, 0))
  equal(t, big.shift(B(0, 0, 1), -9), B(0x80, 0, 0))
  t.end()
})

//it ought to be possible to do shift on the same buffer!

tape('shift - mutate', function (t) {
  function shift(a, b, n) {
    var _a = new Buffer(a), _b = new Buffer(b)
    big.shift(_a, n, _a)
    console.log(_a, b)
    equal(t, _a, b)
    big.shift(_a, -1*n, _a)
    console.log(_a, a)
    equal(t, _a, a)
  }
  shift(B(1), B(2), 1)
  shift(B(0x07, 0x00), B(0, 0x1c), 10)
  t.end()
})

tape('most significant bit', function (t) {
  t.equal(big.mostSignificantBit(B(1, 2, 3)), 18)
  t.equal(big.mostSignificantBit(B(1, 3)), 10)
  t.equal(big.mostSignificantBit(B(0x80)), 8)
  t.equal(big.mostSignificantBit(B(0, 0x80)), 16)
  t.equal(big.mostSignificantBit(B(0, 0, 0x80)), 24)
  t.equal(big.mostSignificantBit(B(0, 0, 0, 0x80)), 32)
  t.equal(big.mostSignificantBit(B(0, 0, 1)), 17)
  t.end()
})

tape('divide', function (t) {
  var q = new Buffer(10), r = new Buffer(10)
//  big.divide(B(0, 1, 22, 3, 4, 5), B(1, 53, 233, 234, 10), q, r)
//  var r = .r
  equal(t, big.divide(B(0x80), B(8)).remainder, B(0))
  equal(t, big.divide(B(0x80), B(7)).remainder, B(2))
  equal(t, big.divide(B(0, 0x80), B(7, 0)).remainder, B(1, 0))
  equal(t, big.divide(B(0x34, 0x12), B(0, 7)).remainder, B(0x34, 4))
  equal(t, big.divide(B(0x34, 0x12), B(7, 0)).remainder, B(5, 0))
  t.end()
})
<commit_msg>test new modInt api: return an int<commit_after>var big = require('../')
var tape = require('tape')

function B () {
  return new Buffer([].slice.call(arguments))
}

function equal(t, a, b, message) {
  t.deepEqual(a.toJSON(), b.toJSON(), message)
}

function createTest(t, forward, reverse, mutate) {
  return function (a, b, c) {
    var r, r2

    equal(t, r = big[forward](a, b), c,
      r.inspect() + ' == ' + forward + '('+a.inspect()+', ' + b.inspect()+')')

    if(reverse)
      equal(t, r2 = big[reverse](r, b), a,
        r2.inspect() + ' == ' + reverse + '('+a.inspect()+', ' + b.inspect()+')')

    if(mutate) {
      var _a = new Buffer(a)

      equal(t, r = big[forward](_a, b, _a), c,
        _a.inspect() + ' == ' + forward + '('+a.inspect()+', ' + b.inspect()+', m)')

      if(reverse)
        equal(t, big[reverse](r, b, r), a,
          _a.inspect() + ' == ' + forward + '('+r.inspect()+', ' + b.inspect()+')')
    }
  }
}

tape('add/sub with mutate', function (t) {

  var test = createTest(t, 'add', 'sub', true)

  //simple
  test(B(0, 1),    B(1, 0),    B(1, 1))

  //carry
  test(B(0x80, 0), B(0x80, 0), B(0, 1))

  //carry
  test(B(0x80, 0), B(0x80, 0), B(0, 1))

  //two carries
  test(B(0x80, 0xff, 0), B(0x80, 0, 0), B(0, 0, 1))

  //xfffff + 0xffff == 0x1fffe
  test(B(0xff, 0xff, 0), B(0xff, 0xff, 0), B(0xfe, 0xff, 0x01))
  t.end()
})

tape('ADD - add two buffers', function (t) {
  var a = new Buffer([0x01, 0x02, 0x03])
  var b = new Buffer([0x04, 0x04, 0x06])
  var c = new Buffer([0x05, 0x06, 0x09])
  equal(t, big.add(a, b),      c)
  equal(t, big.subtract(c, b), a)
  equal(t, big.subtract(c, a), b)
  t.end()
})

tape('ADD - add with with carry', function (t) {
  var a = new Buffer([0xf0, 0x00, 0x00])
  var b = new Buffer([0x13, 0x07, 0x00])
  var c = new Buffer([0x03, 0x08, 0x00])
  equal(t, big.add(a, b),      c)
  equal(t, big.subtract(c, b), a)
  equal(t, big.subtract(c, a), b)
  t.end()
})

tape('add with carry2', function (t) {
  var a = new Buffer([0xf0, 0xff, 0x00])
  var b = new Buffer([0x13, 0x00, 0x00])
  var c = big.add(a, b)
  equal(t, c, new Buffer([0x03, 0x00, 0x01]))
  t.end()
})

tape('ADD - carry over', function (t) {
  var a = new Buffer([0xff, 0xff, 0xff])
  var b = new Buffer([0x01, 0x00, 0x00])
  var c = big.add(a, b, new Buffer(4))
  equal(t, c, new Buffer([0x00, 0x00, 0x00, 0x01]))
  t.end()
})

tape('multiply', function (t) {
  var a = new Buffer([0x01, 0x02, 0x03])
  var b = new Buffer([0x02, 0x00, 0x00])
  var c = new Buffer([0x02, 0x04, 0x06])
  equal(t, big.mul(a, b), c)
  t.end()
})

tape('multiply - carry', function (t) {
  var a = new Buffer([0x10, 0x00])
  var b = new Buffer([0x10, 0x00])
  var c = new Buffer([0x00, 0x01])
  equal(t, big.mul(a, b), c)
  t.end()
})

tape('multiply - carry2', function (t) {
  var a = new Buffer([0x00, 0x10])
  var b = new Buffer([0x00, 0x10])
  var c = new Buffer([0x00, 0x00, 0x00, 0x01])
  equal(t, big.mul(a, b, new Buffer(4)), c)
  t.end()
})

tape('multiply - carry3', function (t) {
  var a = new Buffer([0x10, 0x10])
  var b = new Buffer([0x10, 0x10])
  var c = new Buffer([0x00, 0x01, 0x02, 0x01])
  equal(t, big.mul(a, b, new Buffer(4)), c)
  t.end()
})

tape('multiply - carry3', function (t) {
  var a = new Buffer([0x12, 0x34])
  var b = new Buffer([0x56, 0x78])
  var c = new Buffer([0x0c, 0xee, 0x79, 0x18])
  equal(t, big.mul(a, b, new Buffer(4)), c)
  t.end()
})

tape('modInt', function (t) {
  var a = new Buffer([0, 0, 0x12, 0x34])
  t.equal(big.modInt(a, 0x13), 0x11)
  t.end()
})

tape('modInt2', function (t) {
  var a = new Buffer([0, 0, 0, 0, 0x12, 0x34])
  t.equal(big.modInt(a, 0x130000), 0x110000)
  t.end()
})

tape('modInt3', function (t) {
  var a = new Buffer([0x12, 0x34, 0x56, 0x78, 0x9a, 0, 0, 0])
  t.equal(big.modInt(a, 0x123456), 0x0847ea)
  t.end()
})

tape('modInt4', function (t) {
  var a = B(0xab, 0x33, 0, 0)
  t.equal(big.modInt(a, 28), 11)
  t.end()
})

tape('compare', function (t) {
  var a = B(0, 0, 0, 0, 1), b = B(0, 0, 0, 0, 2)
  t.equal(big.compare(a, b), -1)
  t.equal(big.compare(b, a), 1)
  t.equal(big.compare(a, a), 0)
  t.equal(big.compare(b, b), 0)
  var c = B(126, 99, 2, 0, 1, 2, 0x4a, 0xff), d = B(127, 99, 2, 0, 1, 2, 0x4a, 0xff)
  t.equal(big.compare(c, d), -1)
  t.equal(big.compare(d, c), 1)
  t.equal(big.compare(c, c), 0)
  t.equal(big.compare(d, d), 0)
  t.end()
})

tape('shift 1', function (t) {
  equal(t, big.shift(B(0, 1), 1), B(0, 2))
  equal(t, big.shift(B(0, 1), 2), B(0, 4))
  equal(t, big.shift(B(0, 1), 3), B(0, 8))
  equal(t, big.shift(B(1, 0), 3), B(8, 0))
  equal(t, big.shift(B(0x80, 0), 1), B(0, 1))
  t.end()
})
tape('shift 2, reverse', function (t) {
  equal(t, big.shift(B(0, 2), -1), B(0, 1))
  equal(t, big.shift(B(0, 4), -2), B(0, 1))
  equal(t, big.shift(B(0, 8), -3), B(0, 1))
  equal(t, big.shift(B(8, 0), -3), B(1, 0))
  equal(t, big.shift(B(0, 1), -1), B(0x80, 0))
  t.end()
})

tape('shift2', function (t) {
  equal(t, big.shift(B(0, 1, 0),  9), B(0, 0, 2))
  equal(t, big.shift(B(0, 1, 0), 10), B(0, 0, 4))
  equal(t, big.shift(B(0, 1, 0), 11), B(0, 0, 8))
  equal(t, big.shift(B(1, 0, 0), 11), B(0, 8, 0))
  equal(t, big.shift(B(0x80, 0, 0),  9), B(0, 0, 1))

  equal(t, big.shift(B(0, 0, 2), -17), B(1, 0, 0))
  equal(t, big.shift(B(0, 0, 4), -17), B(2, 0, 0))
  equal(t, big.shift(B(0, 0, 8), -17), B(4, 0, 0))
  equal(t, big.shift(B(0, 8, 0), -11), B(1, 0, 0))
  equal(t, big.shift(B(0, 0, 1), -9), B(0x80, 0, 0))
  t.end()
})

//it ought to be possible to do shift on the same buffer!

tape('shift - mutate', function (t) {
  function shift(a, b, n) {
    var _a = new Buffer(a), _b = new Buffer(b)
    big.shift(_a, n, _a)
    console.log(_a, b)
    equal(t, _a, b)
    big.shift(_a, -1*n, _a)
    console.log(_a, a)
    equal(t, _a, a)
  }
  shift(B(1), B(2), 1)
  shift(B(0x07, 0x00), B(0, 0x1c), 10)
  t.end()
})

tape('most significant bit', function (t) {
  t.equal(big.mostSignificantBit(B(1, 2, 3)), 18)
  t.equal(big.mostSignificantBit(B(1, 3)), 10)
  t.equal(big.mostSignificantBit(B(0x80)), 8)
  t.equal(big.mostSignificantBit(B(0, 0x80)), 16)
  t.equal(big.mostSignificantBit(B(0, 0, 0x80)), 24)
  t.equal(big.mostSignificantBit(B(0, 0, 0, 0x80)), 32)
  t.equal(big.mostSignificantBit(B(0, 0, 1)), 17)
  t.end()
})

tape('divide', function (t) {
  var q = new Buffer(10), r = new Buffer(10)
//  big.divide(B(0, 1, 22, 3, 4, 5), B(1, 53, 233, 234, 10), q, r)
//  var r = .r
  equal(t, big.divide(B(0x80), B(8)).remainder, B(0))
  equal(t, big.divide(B(0x80), B(7)).remainder, B(2))
  equal(t, big.divide(B(0, 0x80), B(7, 0)).remainder, B(1, 0))
  equal(t, big.divide(B(0x34, 0x12), B(0, 7)).remainder, B(0x34, 4))
  equal(t, big.divide(B(0x34, 0x12), B(7, 0)).remainder, B(5, 0))
  t.end()
})
<|endoftext|>


<commit_before>import Board from '../../../../frontend/src/shogi/board';
import Piece from '../../../../frontend/src/shogi/piece';
import memo from 'memo-is';
import _ from 'lodash';

describe('black', () => {
  context('match the piece of coordinate', () => {
    context('exists movable coordinates', () => {
      var board = memo().is(() => {
        var _board = new Board;
        _board.setBoard(position());
        return(_board);
      });

      var position = memo().is(() => {
        return (
          [
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', 'L', '*'],
            ['*', '*', '*']
          ]
        );
      });

      it('change property of piece is movable', () => {
        var piece = new Piece({ type: 'L', x: 8, y: 5 });

        board().enhanceMovablePoint(piece);

        var movablePieces = board().board.map((row) => {
          return (
            row.filter((cell) => { return(cell.movable); })
          );
        });

        _.flattenDeep(movablePieces).should.eql(
          [
            new Piece({ type: '*', x: 8, y: 1, movable: true }),
            new Piece({ type: '*', x: 8, y: 2, movable: true }),
            new Piece({ type: '*', x: 8, y: 3, movable: true }),
            new Piece({ type: '*', x: 8, y: 4, movable: true }),
          ]
        );
      });
    });

    context('does not exist movable coordinates', () => {
      var board = memo().is(() => {
        var _board = new Board;
        _board.setBoard(position());
        return(_board);
      });

      var position = memo().is(() => {
        return (
          [
            ['*', 'L', '*'],
            ['*', '*', '*']
          ]
        );
      });

      it('does not change property of piece', () => {
        var piece = new Piece({ type: 'L', x: 8, y: 1 });

        board().enhanceMovablePoint(piece);

        var movablePieces = board().board.map((row) => {
          return (
            row.filter((cell) => { return(cell.movable); })
          );
        });

        _.flattenDeep(movablePieces).should.eql([]);
      });
    });

    context('other piece exists', () => {
      var board = memo().is(() => {
        var _board = new Board;
        _board.setBoard(position());
        return(_board);
      });

      var position = memo().is(() => {
        return (
          [
            ['*', '*', '*'],
            ['*', 'p', '*'],
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', 'L', '*'],
            ['*', '*', '*']
          ]
        );
      });

      it('change property of piece but not change property above other piece', () => {
        var piece = new Piece({ type: 'L', x: 8, y: 5 });

        board().enhanceMovablePoint(piece);

        var movablePieces = board().board.map((row) => {
          return (
            row.filter((cell) => { return(cell.movable); })
          );
        });

        _.flattenDeep(movablePieces).should.eql(
          [
            new Piece({ type: 'p', x: 8, y: 2, movable: true }),
            new Piece({ type: '*', x: 8, y: 3, movable: true }),
            new Piece({ type: '*', x: 8, y: 4, movable: true })
          ]
        );
      });
    });
  });

  context('mismatch the piece of coordinate', () => {
    var board = memo().is(() => {
      var _board = new Board;
      _board.setBoard(position());
      return(_board);
    });

    var position = memo().is(() => {
      return (
        [
          ['*', '*', '*'],
          ['*', 'L', '*']
        ]
      );
    });

    it('throw exception', () => {
      var piece = new Piece({ type: 'L', x: 7, y: 2 });

      (() => { return board().enhanceMovablePoint(piece); }).should.throw();
    });
  });

  context.skip('if move piece, king is taken', () => {
  });
});

describe('white', () => {
  context('match the piece of coordinate', () => {
    context('exists movable coordinates', () => {
    });

    context('does not exist movable coordinates', () => {
    });

    context('other piece exists', () => {
    });
  });

  context('mismatch the piece of coordinate', () => {
  });

  context.skip('if move piece, king is taken', () => {
  });
});
<commit_msg>Add test example of `match the piece of coordinate`<commit_after>import Board from '../../../../frontend/src/shogi/board';
import Piece from '../../../../frontend/src/shogi/piece';
import memo from 'memo-is';
import _ from 'lodash';

describe('black', () => {
  context('match the piece of coordinate', () => {
    context('exists movable coordinates', () => {
      var board = memo().is(() => {
        var _board = new Board;
        _board.setBoard(position());
        return(_board);
      });

      var position = memo().is(() => {
        return (
          [
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', 'L', '*'],
            ['*', '*', '*']
          ]
        );
      });

      it('change property of piece is movable', () => {
        var piece = new Piece({ type: 'L', x: 8, y: 5 });

        board().enhanceMovablePoint(piece);

        var movablePieces = board().board.map((row) => {
          return (
            row.filter((cell) => { return(cell.movable); })
          );
        });

        _.flattenDeep(movablePieces).should.eql(
          [
            new Piece({ type: '*', x: 8, y: 1, movable: true }),
            new Piece({ type: '*', x: 8, y: 2, movable: true }),
            new Piece({ type: '*', x: 8, y: 3, movable: true }),
            new Piece({ type: '*', x: 8, y: 4, movable: true }),
          ]
        );
      });
    });

    context('does not exist movable coordinates', () => {
      var board = memo().is(() => {
        var _board = new Board;
        _board.setBoard(position());
        return(_board);
      });

      var position = memo().is(() => {
        return (
          [
            ['*', 'L', '*'],
            ['*', '*', '*']
          ]
        );
      });

      it('does not change property of piece', () => {
        var piece = new Piece({ type: 'L', x: 8, y: 1 });

        board().enhanceMovablePoint(piece);

        var movablePieces = board().board.map((row) => {
          return (
            row.filter((cell) => { return(cell.movable); })
          );
        });

        _.flattenDeep(movablePieces).should.eql([]);
      });
    });

    context('other piece exists', () => {
      var board = memo().is(() => {
        var _board = new Board;
        _board.setBoard(position());
        return(_board);
      });

      var position = memo().is(() => {
        return (
          [
            ['*', '*', '*'],
            ['*', 'p', '*'],
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', 'L', '*'],
            ['*', '*', '*']
          ]
        );
      });

      it('change property of piece but not change property above other piece', () => {
        var piece = new Piece({ type: 'L', x: 8, y: 5 });

        board().enhanceMovablePoint(piece);

        var movablePieces = board().board.map((row) => {
          return (
            row.filter((cell) => { return(cell.movable); })
          );
        });

        _.flattenDeep(movablePieces).should.eql(
          [
            new Piece({ type: 'p', x: 8, y: 2, movable: true }),
            new Piece({ type: '*', x: 8, y: 3, movable: true }),
            new Piece({ type: '*', x: 8, y: 4, movable: true })
          ]
        );
      });
    });
  });

  context('mismatch the piece of coordinate', () => {
    var board = memo().is(() => {
      var _board = new Board;
      _board.setBoard(position());
      return(_board);
    });

    var position = memo().is(() => {
      return (
        [
          ['*', '*', '*'],
          ['*', 'L', '*']
        ]
      );
    });

    it('throw exception', () => {
      var piece = new Piece({ type: 'L', x: 7, y: 2 });

      (() => { return board().enhanceMovablePoint(piece); }).should.throw();
    });
  });

  context.skip('if move piece, king is taken', () => {
  });
});

describe('white', () => {
  context('match the piece of coordinate', () => {
    context('exists movable coordinates', () => {
      var board = memo().is(() => {
        var _board = new Board;
        _board.setBoard(position());
        return(_board);
      });

      var position = memo().is(() => {
        return (
          [
            ['*', '*', '*'],
            ['*', 'l', '*'],
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', '*', '*'],
            ['*', '*', '*']
          ]
        );
      });

      it('change property of piece is movable', () => {
        var piece = new Piece({ type: 'l', x: 8, y: 2 });

        board().enhanceMovablePoint(piece);

        var movablePieces = board().board.map((row) => {
          return (
            row.filter((cell) => { return(cell.movable); })
          );
        });

        _.flattenDeep(movablePieces).should.eql(
          [
            new Piece({ type: '*', x: 8, y: 3, movable: true }),
            new Piece({ type: '*', x: 8, y: 4, movable: true }),
            new Piece({ type: '*', x: 8, y: 5, movable: true }),
            new Piece({ type: '*', x: 8, y: 6, movable: true }),
          ]
        );
      });
    });

    context('does not exist movable coordinates', () => {
    });

    context('other piece exists', () => {
    });
  });

  context('mismatch the piece of coordinate', () => {
  });

  context.skip('if move piece, king is taken', () => {
  });
});
<|endoftext|>


<commit_before>/**
 * Created by Samuel on 6/4/2016.
 */

var assert = require('assert');
var short = require('../index');
var uuid = require('node-uuid');

var b90;

describe('short-uuid', function(){

    describe('new', function(){

        it('should contain a "new" function', function(){

            var b90;
            assert.ok(short.hasOwnProperty('new') && typeof short.new === 'function');

            assert.doesNotThrow(function(){
                b90 = short.new(short.constants.cookieBase90);
            }, "Calling new does not throw an error");

            assert.equal(typeof b90, 'object', "new returns an object");
        });
    });

    describe('constants', function(){

        it('should contain a "constants" object', function(){
            assert.ok(short.hasOwnProperty('constants') && typeof short.constants === 'object');
        });

        it('should contain constant values', function(){
            assert.equal(short.constants.flickrBase58, '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
            assert.equal(short.constants.cookieBase90, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()*+-./:<=>?@[]^_`{|}~");
        });
    });

    describe('operation', function(){

        var b90 = short.new(short.constants.cookieBase90);
        var b58 = short.b58;

        var uu, f58, f90;

        for (var i = 0; i < 10; i++) {
            uu = uuid.v4();

            f58 = b58.fromUUID(uu);
            f90 = b90.fromUUID(uu);

            it('should translate back from multiple bases', function(){

                assert.equal(b58.toUUID(f58), uu, 'Translated b58 matches original');
                assert.equal(b90.toUUID(f90), uu, 'Translated b90 matches original');
            });

        }

        it('should handle UUIDs that begin with zeros', function(){
            var someZeros = '00000000-a70c-4ebd-8f2b-540f7e709092';
            var allZeros = '00000000-0000-0000-0000-000000000000';

            assert.equal(someZeros, b58.toUUID(b58.fromUUID(someZeros)),'Supports starting zeroes');
            assert.equal(someZeros, b90.toUUID(b90.fromUUID(someZeros)),'Supports starting zeroes');

            assert.equal(allZeros, b58.toUUID(b58.fromUUID(allZeros)),'Supports starting zeroes');
            assert.equal(allZeros, b90.toUUID(b90.fromUUID(allZeros)),'Supports starting zeroes');
        });

    });

});<commit_msg>Use exposed UUID in testing<commit_after>/**
 * Created by Samuel on 6/4/2016.
 */

var assert = require('assert');
var short = require('../index');

var b90;

describe('short-uuid', function(){

    describe('new', function(){

        it('should contain a "new" function', function(){

            var b90;
            assert.ok(short.hasOwnProperty('new') && typeof short.new === 'function');

            assert.doesNotThrow(function(){
                b90 = short.new(short.constants.cookieBase90);
            }, "Calling new does not throw an error");

            assert.equal(typeof b90, 'object', "new returns an object");
        });
    });

    describe('constants', function(){

        it('should contain a "constants" object', function(){
            assert.ok(short.hasOwnProperty('constants') && typeof short.constants === 'object');
        });

        it('should contain constant values', function(){
            assert.equal(short.constants.flickrBase58, '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
            assert.equal(short.constants.cookieBase90, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()*+-./:<=>?@[]^_`{|}~");
        });
    });

    describe('operation', function(){

        var b90 = short.new(short.constants.cookieBase90);
        var b58 = short.b58;

        var uu, f58, f90;

        for (var i = 0; i < 10; i++) {
            uu = short.uuid();

            f58 = b58.fromUUID(uu);
            f90 = b90.fromUUID(uu);

            it('should translate back from multiple bases', function(){

                assert.equal(b58.toUUID(f58), uu, 'Translated b58 matches original');
                assert.equal(b90.toUUID(f90), uu, 'Translated b90 matches original');
            });

        }

        it('should handle UUIDs that begin with zeros', function(){
            var someZeros = '00000000-a70c-4ebd-8f2b-540f7e709092';
            var allZeros = '00000000-0000-0000-0000-000000000000';

            assert.equal(someZeros, b58.toUUID(b58.fromUUID(someZeros)),'Supports starting zeroes');
            assert.equal(someZeros, b90.toUUID(b90.fromUUID(someZeros)),'Supports starting zeroes');

            assert.equal(allZeros, b58.toUUID(b58.fromUUID(allZeros)),'Supports starting zeroes');
            assert.equal(allZeros, b90.toUUID(b90.fromUUID(allZeros)),'Supports starting zeroes');
        });

    });

});<|endoftext|>


<commit_before>const glob = require('glob')
const path = require('path')
const fs   = require('fs')
const test = require('tape')
const fixtures = require('./fixtures')
const pdf    = require('../lib')

process.env.TZ = 'Europe/Berlin'

const args = process.argv.slice(2)
if (args.length) {
  run(args.map((a) => path.join(__dirname, a)), true)
} else {
  glob(path.join(__dirname, 'pdfs/**/*.js'), function (err, files) {
    if (err) throw err
    run(files)
  })
}

// mock current time
const _Date = Date
Date = class extends _Date {
  constructor(year, month, day, hour, minute, second) {
    if (arguments.length === 0) {
      return new _Date(2015, 1, 19, 22, 33, 26)
    } else {
      return new _Date(year, month, day, hour, minute, second)
    }
  }
}

function run(files, force) {
  const f = fixtures.create()

  files.forEach(function(scriptPath) {
    const dirname  = path.dirname(scriptPath)
    const basename = path.basename(scriptPath, '.js')

    // ignore tests starting with _ and named `test`
    if (!force && (basename[0] === '_' || basename === 'test')) {
      return
    }

    const expectationPath = path.join(dirname, basename + '.pdf')
    const resultPath      = path.join(dirname, basename + '.result.pdf')

    const script = require(scriptPath)

    let doc = new pdf.Document({
      font:       f.font.afm.regular,
      padding:    script.padding >= 0 ? script.padding : 10,
      lineHeight: 1,
    })

    const newDoc = script(doc, f)
    if (newDoc) {
      doc = newDoc
    }

    const relativePath = path.relative(path.join(__dirname, 'pdfs'), dirname)
    test(path.join(relativePath, basename), function (t) {
      doc.info.id = '42'
      doc.info.creationDate = new Date(2015, 1, 19, 22, 33, 26)
      doc.info.producer = 'pdfjs tests (github.com/rkusa/pdfjs)'

      const w = fs.createWriteStream(resultPath)
      doc.pipe(w)

      doc.end().catch(err => {
        t.error(err)
      })

      w.on('close', () => {
        try {
          var result = fs.readFileSync(resultPath, 'binary')
          var expectation = fs.readFileSync(expectationPath, 'binary')
        } catch (err) {
          t.error(err)
        }

        t.ok(result === expectation, basename)
        t.end()
      })
    })
  })
}
<commit_msg>allow running single tests via npm run<commit_after>const glob = require('glob')
const path = require('path')
const fs   = require('fs')
const test = require('tape')
const fixtures = require('./fixtures')
const pdf    = require('../lib')

process.env.TZ = 'Europe/Berlin'

const args = process.argv.slice(2)
if (args.length) {
  run(args.map((a) => path.join(__dirname, '../', a)), true)
} else {
  glob(path.join(__dirname, 'pdfs/**/*.js'), function (err, files) {
    if (err) throw err
    run(files)
  })
}

// mock current time
const _Date = Date
Date = class extends _Date {
  constructor(year, month, day, hour, minute, second) {
    if (arguments.length === 0) {
      return new _Date(2015, 1, 19, 22, 33, 26)
    } else {
      return new _Date(year, month, day, hour, minute, second)
    }
  }
}

function run(files, force) {
  const f = fixtures.create()

  files.forEach(function(scriptPath) {
    const dirname  = path.dirname(scriptPath)
    const basename = path.basename(scriptPath, '.js')

    // ignore tests starting with _ and named `test`
    if (!force && (basename[0] === '_' || basename === 'test')) {
      return
    }

    const expectationPath = path.join(dirname, basename + '.pdf')
    const resultPath      = path.join(dirname, basename + '.result.pdf')

    const script = require(scriptPath)

    let doc = new pdf.Document({
      font:       f.font.afm.regular,
      padding:    script.padding >= 0 ? script.padding : 10,
      lineHeight: 1,
    })

    const newDoc = script(doc, f)
    if (newDoc) {
      doc = newDoc
    }

    const relativePath = path.relative(path.join(__dirname, 'pdfs'), dirname)
    test(path.join(relativePath, basename), function (t) {
      doc.info.id = '42'
      doc.info.creationDate = new Date(2015, 1, 19, 22, 33, 26)
      doc.info.producer = 'pdfjs tests (github.com/rkusa/pdfjs)'

      const w = fs.createWriteStream(resultPath)
      doc.pipe(w)

      doc.end().catch(err => {
        t.error(err)
      })

      w.on('close', () => {
        try {
          var result = fs.readFileSync(resultPath, 'binary')
          var expectation = fs.readFileSync(expectationPath, 'binary')
        } catch (err) {
          t.error(err)
        }

        t.ok(result === expectation, basename)
        t.end()
      })
    })
  })
}
<|endoftext|>


<commit_before>/*eslint func-names: 0*/
var Code = require('code');
var Lab = require('lab');
var WS = require('ws');
var JsonRpcWs = require('../');
var Browserify = require('browserify');
var Webdriver = require('selenium-webdriver');

Code.settings.truncateMessages = false;
var lab = exports.lab = Lab.script();

lab.experiment('json-rpc ws', function () {

    var server = JsonRpcWs.createServer();
    var client = JsonRpcWs.createClient();
    var browserParams;
    var delayBuffer = [];

    lab.before(function (done) {

        server.expose('reflect', function (params, reply) {

            reply(null, params || 'empty');
        });
        server.expose('delay', function (params, reply) {

            var last;
            if (delayBuffer.length > 0) {
                last = delayBuffer.pop();
                last[1](null, last[0][0]);
            }
            delayBuffer.push(arguments);
        });
        server.expose('error', function (params, reply) {

            reply('error', null);
        });
        server.expose('browserClient', function (params, reply) {

            reply(null, this.id);
        });

        server.start({ host: 'localhost', port: 8081 }, function () {

            client.connect('ws://localhost:8081', done);
        });
    });

    lab.after(function (done) {

        client.disconnect(function () {

            server.stop();
            done();
        });
    });

    lab.test('client has an id', function (done) {

        Code.expect(client.id).to.not.equal(undefined);
        done();
    });

    lab.test('reflecting handler', function (done) {

        client.send('reflect', ['test one'], function (error1, reply1) {

            Code.expect(error1).to.equal(undefined);
            Code.expect(reply1).to.have.length(1);
            Code.expect(reply1[0]).to.equal('test one');
            client.send('reflect', ['test two'], function (error2, reply2) {

                Code.expect(error2).to.equal(undefined);
                Code.expect(reply2).to.have.length(1);
                Code.expect(reply2[0]).to.equal('test two');
                client.send('reflect', null, function (error3, reply3) {

                    Code.expect(error3).to.equal(undefined);
                    Code.expect(reply3).to.equal('empty');
                    client.send('reflect', undefined, function (error3, reply3) {

                        Code.expect(error3).to.equal(undefined);
                        Code.expect(reply3).to.equal('empty');
                        done();
                    });
                });
            });
        });
    });

    lab.test('error reply', function (done) {

        client.send('error', null, function (error, reply) {

            Code.expect(reply).to.equal(undefined);
            Code.expect(error).to.equal('error');
            done();
        });
    });

    lab.test('delay handler', function (done) {

        var counter = 0;
        client.send('delay', ['test one'], function (error, reply) {

            Code.expect(counter).to.equal(0);
            counter = counter + 1;
            Code.expect(reply).to.equal('test one');
        });
        client.send('delay', ['test two'], function (error, reply) {

            Code.expect(counter).to.equal(1);
            Code.expect(reply).to.equal('test two');
            done();
        });
        client.send('delay', ['test three']);
    });

    lab.test('cannot register duplicate handler', function (done) {

        Code.expect(function () {

            server.expose('reflect', function (params, reply) {

                reply();
            });
        }).to.throw(Error);
        done();
    });

    lab.test('hasHandler', function (done) {

        Code.expect(server.hasHandler('reflect')).to.equal(true);
        Code.expect(server.hasHandler('nonexistant')).to.equal(false);
        done();
    });

    lab.test('connection Ids', function (done) {

        var connectionId;
        server.expose('saveConnection', function (params, reply) {

            Code.expect(this.id).to.not.equal(undefined);
            connectionId = this.id;
            reply(null, 'ok');
        });
        client.expose('info', function (params, reply) {

            Code.expect(params).to.equal(undefined);
            reply(null, 'info ok');
        });
        client.send('saveConnection', null, function () {

            Code.expect(connectionId).to.not.equal(undefined);
            Code.expect(server.getConnection(connectionId)).to.not.equal(undefined);
            server.send(connectionId, 'info', null, function (err, result) {

                Code.expect(result).to.equal('info ok');
                done();
            });
        });
    });
    lab.test('invalid connection id', function (done) {

        server.send(0, 'info', undefined); //No callback is ok
        server.send(0, 'info', undefined, function (err, result) {

            Code.expect(result).to.equal(undefined);
            Code.expect(err).to.include('code', 'message');
            Code.expect(err.code).to.equal(-32000);
            done();
        });
    });
    lab.test('invalid payloads do not throw exceptions', function (done) {

        //This is for code coverage in the message handler to make sure rogue messages won't take the server down.;
        var socket = WS.createConnection('ws://localhost:8081', function () {

            //TODO socket callbacks + socket.once('message') with response validation for each of these instead of this setTimeout nonsense
            socket.send('asdf\n');
            socket.send('{}\n');
            socket.send('{"jsonrpc":"2.0"}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect"}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":null}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":"asdf"}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":0}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":[0]}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "params":null}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":null, "params":null}\n');
            socket.send('{"jsonrpc":"2.0", "error":{"code": -32000, "message":"Server error"}}\n');
            socket.send('{"jsonrpc":"2.0", "id":"asdf", "result":"test"}\n');
            socket.send('[{"jsonrpc":"2.0", "result":"test"},{"jsonrpc":"2.0", "result":"rest"}]');
            setTimeout(done, 100);
        });
    });
    lab.test('client.send', function (done) {

        //No callback
        client.send('reflect', null); //Valid method
        client.send('nonexistant', null); //Unexposed method
        Code.expect(function () {

            client.send(1, null); //Invalid method
        }).to.throw(Error);
        done();
    });
    lab.test('client hangups', function (done) {

        var clientA = JsonRpcWs.createClient();
        var clientB = JsonRpcWs.createClient();
        //With and without callbacks;
        clientA.connect('ws://localhost:8081', function () {

            clientA.disconnect(function () {

                clientB.connect('ws://localhost:8081', function () {

                    clientB.disconnect();
                    done();
                });
            });

        });
    });
    lab.test('server.start without callback', function (done) {

        var serverA = JsonRpcWs.createServer();
        serverA.start({ port: 8082 });
        serverA.server.once('listening', done);
    });

    lab.test('errors', function (done) {

        var payload;
        payload = JsonRpcWs.Errors('parseError');
        Code.expect(payload.id).to.equal(undefined);
        Code.expect(payload.error).to.include('code', 'message');
        Code.expect(payload.error.data).to.equal(undefined);
        payload = JsonRpcWs.Errors('parseError', 'a');
        Code.expect(payload.id).to.equal('a');
        Code.expect(payload.error).to.include('code', 'message');
        Code.expect(payload.error.data).to.equal(undefined);
        payload = JsonRpcWs.Errors('parseError', 'b', { extra: 'data' });
        Code.expect(payload.id).to.equal('b');
        Code.expect(payload.error).to.include('code', 'message');
        Code.expect(payload.error.data).to.deep.equal({ extra: 'data' });
        done();
    });

    lab.experiment('browser', function () {

        var script;
        lab.before(function (done) {

            process.env.PATH = process.env.PATH + ':./node_modules/.bin';
            var b = Browserify();
            b.add('./browser_test.js');
            b.bundle(function (err, buf) {

                Code.expect(err).to.not.exist();
                script = buf.toString();
                done();
            });
        });

        lab.test('works in browser', function (done) {

            Code.expect(script).to.not.equal('');
            var driver = new Webdriver.Builder().forBrowser('phantomjs').build();
            driver.executeScript(script).then(function () {

                driver.executeAsyncScript(function () {

                    var callback = arguments[arguments.length - 1];
                    var socket = new WebSocket('ws://localhost:8081');
                    browserClient.connect('ws://localhost:8081', function () {

                        browserClient.send('browserClient', ['browser', 'client'], function (err, reply) {

                            callback([err, reply]);
                        });
                    });
                }).then(function (response) {

                    var err = response[0];
                    var browserId = response[1];
                    Code.expect(browserId).to.not.equal(undefined);
                    Code.expect(err).to.equal(null);
                    server.send(browserId, 'info', null, function (err, result) {

                        Code.expect(err).to.equal(undefined);
                        Code.expect(result).to.equal('browser');
                        driver.quit();
                        done();
                    });
                });
            });
        });

    });
});
<commit_msg>no more deep in code@3<commit_after>/*eslint func-names: 0*/
var Code = require('code');
var Lab = require('lab');
var WS = require('ws');
var JsonRpcWs = require('../');
var Browserify = require('browserify');
var Webdriver = require('selenium-webdriver');

Code.settings.truncateMessages = false;
var lab = exports.lab = Lab.script();

lab.experiment('json-rpc ws', function () {

    var server = JsonRpcWs.createServer();
    var client = JsonRpcWs.createClient();
    var browserParams;
    var delayBuffer = [];

    lab.before(function (done) {

        server.expose('reflect', function (params, reply) {

            reply(null, params || 'empty');
        });
        server.expose('delay', function (params, reply) {

            var last;
            if (delayBuffer.length > 0) {
                last = delayBuffer.pop();
                last[1](null, last[0][0]);
            }
            delayBuffer.push(arguments);
        });
        server.expose('error', function (params, reply) {

            reply('error', null);
        });
        server.expose('browserClient', function (params, reply) {

            reply(null, this.id);
        });

        server.start({ host: 'localhost', port: 8081 }, function () {

            client.connect('ws://localhost:8081', done);
        });
    });

    lab.after(function (done) {

        client.disconnect(function () {

            server.stop();
            done();
        });
    });

    lab.test('client has an id', function (done) {

        Code.expect(client.id).to.not.equal(undefined);
        done();
    });

    lab.test('reflecting handler', function (done) {

        client.send('reflect', ['test one'], function (error1, reply1) {

            Code.expect(error1).to.equal(undefined);
            Code.expect(reply1).to.have.length(1);
            Code.expect(reply1[0]).to.equal('test one');
            client.send('reflect', ['test two'], function (error2, reply2) {

                Code.expect(error2).to.equal(undefined);
                Code.expect(reply2).to.have.length(1);
                Code.expect(reply2[0]).to.equal('test two');
                client.send('reflect', null, function (error3, reply3) {

                    Code.expect(error3).to.equal(undefined);
                    Code.expect(reply3).to.equal('empty');
                    client.send('reflect', undefined, function (error3, reply3) {

                        Code.expect(error3).to.equal(undefined);
                        Code.expect(reply3).to.equal('empty');
                        done();
                    });
                });
            });
        });
    });

    lab.test('error reply', function (done) {

        client.send('error', null, function (error, reply) {

            Code.expect(reply).to.equal(undefined);
            Code.expect(error).to.equal('error');
            done();
        });
    });

    lab.test('delay handler', function (done) {

        var counter = 0;
        client.send('delay', ['test one'], function (error, reply) {

            Code.expect(counter).to.equal(0);
            counter = counter + 1;
            Code.expect(reply).to.equal('test one');
        });
        client.send('delay', ['test two'], function (error, reply) {

            Code.expect(counter).to.equal(1);
            Code.expect(reply).to.equal('test two');
            done();
        });
        client.send('delay', ['test three']);
    });

    lab.test('cannot register duplicate handler', function (done) {

        Code.expect(function () {

            server.expose('reflect', function (params, reply) {

                reply();
            });
        }).to.throw(Error);
        done();
    });

    lab.test('hasHandler', function (done) {

        Code.expect(server.hasHandler('reflect')).to.equal(true);
        Code.expect(server.hasHandler('nonexistant')).to.equal(false);
        done();
    });

    lab.test('connection Ids', function (done) {

        var connectionId;
        server.expose('saveConnection', function (params, reply) {

            Code.expect(this.id).to.not.equal(undefined);
            connectionId = this.id;
            reply(null, 'ok');
        });
        client.expose('info', function (params, reply) {

            Code.expect(params).to.equal(undefined);
            reply(null, 'info ok');
        });
        client.send('saveConnection', null, function () {

            Code.expect(connectionId).to.not.equal(undefined);
            Code.expect(server.getConnection(connectionId)).to.not.equal(undefined);
            server.send(connectionId, 'info', null, function (err, result) {

                Code.expect(result).to.equal('info ok');
                done();
            });
        });
    });
    lab.test('invalid connection id', function (done) {

        server.send(0, 'info', undefined); //No callback is ok
        server.send(0, 'info', undefined, function (err, result) {

            Code.expect(result).to.equal(undefined);
            Code.expect(err).to.include('code', 'message');
            Code.expect(err.code).to.equal(-32000);
            done();
        });
    });
    lab.test('invalid payloads do not throw exceptions', function (done) {

        //This is for code coverage in the message handler to make sure rogue messages won't take the server down.;
        var socket = WS.createConnection('ws://localhost:8081', function () {

            //TODO socket callbacks + socket.once('message') with response validation for each of these instead of this setTimeout nonsense
            socket.send('asdf\n');
            socket.send('{}\n');
            socket.send('{"jsonrpc":"2.0"}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect"}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":null}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":"asdf"}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":0}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":[0]}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "params":null}\n');
            socket.send('{"jsonrpc":"2.0", "method":"reflect", "id":null, "params":null}\n');
            socket.send('{"jsonrpc":"2.0", "error":{"code": -32000, "message":"Server error"}}\n');
            socket.send('{"jsonrpc":"2.0", "id":"asdf", "result":"test"}\n');
            socket.send('[{"jsonrpc":"2.0", "result":"test"},{"jsonrpc":"2.0", "result":"rest"}]');
            setTimeout(done, 100);
        });
    });
    lab.test('client.send', function (done) {

        //No callback
        client.send('reflect', null); //Valid method
        client.send('nonexistant', null); //Unexposed method
        Code.expect(function () {

            client.send(1, null); //Invalid method
        }).to.throw(Error);
        done();
    });
    lab.test('client hangups', function (done) {

        var clientA = JsonRpcWs.createClient();
        var clientB = JsonRpcWs.createClient();
        //With and without callbacks;
        clientA.connect('ws://localhost:8081', function () {

            clientA.disconnect(function () {

                clientB.connect('ws://localhost:8081', function () {

                    clientB.disconnect();
                    done();
                });
            });

        });
    });
    lab.test('server.start without callback', function (done) {

        var serverA = JsonRpcWs.createServer();
        serverA.start({ port: 8082 });
        serverA.server.once('listening', done);
    });

    lab.test('errors', function (done) {

        var payload;
        payload = JsonRpcWs.Errors('parseError');
        Code.expect(payload.id).to.equal(undefined);
        Code.expect(payload.error).to.include('code', 'message');
        Code.expect(payload.error.data).to.equal(undefined);
        payload = JsonRpcWs.Errors('parseError', 'a');
        Code.expect(payload.id).to.equal('a');
        Code.expect(payload.error).to.include('code', 'message');
        Code.expect(payload.error.data).to.equal(undefined);
        payload = JsonRpcWs.Errors('parseError', 'b', { extra: 'data' });
        Code.expect(payload.id).to.equal('b');
        Code.expect(payload.error).to.include('code', 'message');
        Code.expect(payload.error.data).to.equal({ extra: 'data' });
        done();
    });

    lab.experiment('browser', function () {

        var script;
        lab.before(function (done) {

            process.env.PATH = process.env.PATH + ':./node_modules/.bin';
            var b = Browserify();
            b.add('./browser_test.js');
            b.bundle(function (err, buf) {

                Code.expect(err).to.not.exist();
                script = buf.toString();
                done();
            });
        });

        lab.test('works in browser', function (done) {

            Code.expect(script).to.not.equal('');
            var driver = new Webdriver.Builder().forBrowser('phantomjs').build();
            driver.executeScript(script).then(function () {

                driver.executeAsyncScript(function () {

                    var callback = arguments[arguments.length - 1];
                    var socket = new WebSocket('ws://localhost:8081');
                    browserClient.connect('ws://localhost:8081', function () {

                        browserClient.send('browserClient', ['browser', 'client'], function (err, reply) {

                            callback([err, reply]);
                        });
                    });
                }).then(function (response) {

                    var err = response[0];
                    var browserId = response[1];
                    Code.expect(browserId).to.not.equal(undefined);
                    Code.expect(err).to.equal(null);
                    server.send(browserId, 'info', null, function (err, result) {

                        Code.expect(err).to.equal(undefined);
                        Code.expect(result).to.equal('browser');
                        driver.quit();
                        done();
                    });
                });
            });
        });

    });
});
<|endoftext|>


<commit_before>/**
 * test/index.js
 * Contains tests for client entry point.
 *
 * @author Francis Brito <fr.br94@gmail.com>
 * @license MIT
 */
/* global describe, it, before */
/* jshint expr:true */
'use strict';

require('should');

var Client = require('../').Client;

var they = it.bind(it);

var PH_TEST_SERVER = 'http://private-50d6dc-printhouse.apiary-mock.com/api';

describe('Client', function () {
    this.timeout(5 * 1000);

    describe('constructor', function () {
        it('should throw if no API key is provided.', function () {
            (function () {
               new Client();
            }).should.throw('No API key provided.');
        });

        it('should use default API endpoint if none is provided.', function () {
            var client = new Client('some api key');

            // NOTE: Accessing client's private API, so sort of breaking the rules here.
            client._endpoint.should.eql(Client.DEFAULT_API_URL);
        });

        it('should use latest API version if none is specified.', function () {
            var client = new Client('some api key');

            client._version.should.eql(Client.DEFAULT_API_VERSION);
        });
    });

    describe('methods', function () {
        they('should throw if API endpoint is not reachable.');
        they('should throw if API endpoint responds with a server error.');
    });

    describe('#getProducts', function () {
        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });

        it('should return a list of products.', function (next) {
            this.client.getProducts(function (err, products) {
                products.should.be.ok.and.be.an.Array;

                next();
            });
        });
    });

    describe('#getProductById', function () {
        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });

        it('should return a product.', function (next) {
            this.client.getProductById('id', function (err, product) {
                (!!product).should.be.ok;

                next();
            });
        });

        it('should return an error if no product with id `id` is found.'/*, function (next) {
            // NOTE: This case cannot be tested with current mock server.
            this.client.getProductById('-1', function (err) {
                (!!err).should.be.ok;
                err.message.should.eql('Unable to find product with such id.');

                next();
            });
        }*/);

        it('should throw if no `id` field is provided.', function () {
            var client = this.client;

            (function () {
                client.getProductById(null);
            }).should.throw('`id` is missing.');
        });
    });

    describe('#getPrintFiles', function () {

        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });

        it('should return a list of print files.', function (next) {
            this.client.getPrintFiles(function (err, files) {
                (!!files).should.be.ok;
                files.should.be.an.Array;

                next();
            });
        });
    });

    describe('#getPrintFileById', function () {
        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });

        it('should return a print file.', function (next) {
            this.client.getPrintFileById('id', function (err, file) {
                (!!file).should.be.ok;
                file.should.be.an.Object;

                next();
            });
        });

        it('should throw if no print file with id `id` is found.');

        it('should throw if no `id` field is provided.', function () {
            var client = this.client;

            (function () {
                client.getPrintFileById();
            }).should.throw('`id` is missing.');
        });
    });

    describe('#createPrintFile', function () {
        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });
    });

    describe('#getOrders', function () {});

    describe('#getOrderById', function () {
        it('should throw if no order with id `id` is found.');
        it('should throw if no `id` field is provided.');
    });

    describe('#createOrder', function () {
        it('should throw if no `fields` parameter is provided.');
    });

    describe('#updateOrder', function () {
        it('should throw if no order with id `id` is found.');
        it('should throw if no `id` field is provided.');
        it('should throw if order has already being confirmed.');
        it('should throw if no `fields` parameter is provided.');
    });

    describe('#confirmOrder', function () {
        it('should throw if no order with id `id` is found.');
        it('should throw if no `id` field is provided.');
        it('should throw if order was already confirmed.');
    });
});

/*
 * Helpers
 */
// function isACanvas(c) { return c.kind === 'Canvas'; }
// function every(array, predicate) { return array.every(predicate); }
<commit_msg>Remove trailing whitespace.<commit_after>/**
 * test/index.js
 * Contains tests for client entry point.
 *
 * @author Francis Brito <fr.br94@gmail.com>
 * @license MIT
 */
/* global describe, it, before */
/* jshint expr:true */
'use strict';

require('should');

var Client = require('../').Client;

var they = it.bind(it);

var PH_TEST_SERVER = 'http://private-50d6dc-printhouse.apiary-mock.com/api';

describe('Client', function () {
    this.timeout(5 * 1000);

    describe('constructor', function () {
        it('should throw if no API key is provided.', function () {
            (function () {
               new Client();
            }).should.throw('No API key provided.');
        });

        it('should use default API endpoint if none is provided.', function () {
            var client = new Client('some api key');

            // NOTE: Accessing client's private API, so sort of breaking the rules here.
            client._endpoint.should.eql(Client.DEFAULT_API_URL);
        });

        it('should use latest API version if none is specified.', function () {
            var client = new Client('some api key');

            client._version.should.eql(Client.DEFAULT_API_VERSION);
        });
    });

    describe('methods', function () {
        they('should throw if API endpoint is not reachable.');
        they('should throw if API endpoint responds with a server error.');
    });

    describe('#getProducts', function () {
        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });

        it('should return a list of products.', function (next) {
            this.client.getProducts(function (err, products) {
                products.should.be.ok.and.be.an.Array;

                next();
            });
        });
    });

    describe('#getProductById', function () {
        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });

        it('should return a product.', function (next) {
            this.client.getProductById('id', function (err, product) {
                (!!product).should.be.ok;

                next();
            });
        });

        it('should return an error if no product with id `id` is found.'/*, function (next) {
            // NOTE: This case cannot be tested with current mock server.
            this.client.getProductById('-1', function (err) {
                (!!err).should.be.ok;
                err.message.should.eql('Unable to find product with such id.');

                next();
            });
        }*/);

        it('should throw if no `id` field is provided.', function () {
            var client = this.client;

            (function () {
                client.getProductById(null);
            }).should.throw('`id` is missing.');
        });
    });

    describe('#getPrintFiles', function () {

        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });

        it('should return a list of print files.', function (next) {
            this.client.getPrintFiles(function (err, files) {
                (!!files).should.be.ok;
                files.should.be.an.Array;

                next();
            });
        });
    });

    describe('#getPrintFileById', function () {
        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });

        it('should return a print file.', function (next) {
            this.client.getPrintFileById('id', function (err, file) {
                (!!file).should.be.ok;
                file.should.be.an.Object;

                next();
            });
        });

        it('should throw if no print file with id `id` is found.');

        it('should throw if no `id` field is provided.', function () {
            var client = this.client;

            (function () {
                client.getPrintFileById();
            }).should.throw('`id` is missing.');
        });
    });

    describe('#createPrintFile', function () {
        before(function () {
            this.client = new Client('some api token', {
                endpoint: PH_TEST_SERVER
            });
        });

        it('should throw if no `fields` parameter is provided.');
    });

    describe('#getOrders', function () {});

    describe('#getOrderById', function () {
        it('should throw if no order with id `id` is found.');
        it('should throw if no `id` field is provided.');
    });

    describe('#createOrder', function () {
        it('should throw if no `fields` parameter is provided.');
    });

    describe('#updateOrder', function () {
        it('should throw if no order with id `id` is found.');
        it('should throw if no `id` field is provided.');
        it('should throw if order has already being confirmed.');
        it('should throw if no `fields` parameter is provided.');
    });

    describe('#confirmOrder', function () {
        it('should throw if no order with id `id` is found.');
        it('should throw if no `id` field is provided.');
        it('should throw if order was already confirmed.');
    });
});

/*
 * Helpers
 */
// function isACanvas(c) { return c.kind === 'Canvas'; }
// function every(array, predicate) { return array.every(predicate); }
<|endoftext|>


<commit_before>import { /*document, window,*/ body} from 'global';
import 'misc/polyfills';
import 'misc/dom4';
import it from 'tape';
import '../build/importVars';
/*it('should bind text', (t) => {
  t.plan(1);
  var { el, template } = load('../build/simpleText');
  var expectedText = 'some text';
  template.set('textvar', expectedText);
  t.equal(expectedText, el.textContent);
});
it('should bind html with content', (t) => {
  t.plan(2);
  var {el, template} = load('../build/simpleHtml');
  template.set('htmlvar', 'some link');
  var a = el.querySelector('a');
  t.equal('a', a.tagName.toLowerCase());
  t.equal('some link', a.textContent);
});
it('should bind attributes', (t) => {
  t.plan(1);
  var { el, template} = load('../build/simpleAttributes');
  var values = {
    action: 'mark',
    clear: '',
    clb: 'clb3187965',
    my: 0,
    type: 'question',
    state: 'R',
    refname: 'qid',
    canmark: 1,
    totalmarks: 2,
    Totalmarks: true,
    iClassName: ''
  };
  template.set(values);
  t.equal(el.getAttribute('class'), 'mark  action--mark action--need-auth test2');
});*/

it('should import vars, vars in attr tmpl', t => {
  t.plan(7);
  var { el, template} = load('../build/importVars');
  var v = {
    somewhere: 'somewhere',
    beginning: 'beginning',
    the: 'the',
    of: 'of',
    at: 'at',
    two: 'two',
    vars: 'vars',
    a: 'a'
  };
  var icon = require('./styles').icon;
  template.set(v);
  //t.equal(el.getAttribute('attr1'), icon + ' somewhere in the beginning');
  t.equal(el.getAttribute('attr1'), `${icon} ${v.somewhere} in the beginning`);
  t.equal(el.getAttribute('attr2'), `somewhere ${v.at} the end ${icon}`);
  t.equal(el.getAttribute('attr3'), `${v.somewhere} ${icon} in ${v.the} middle`);
  t.equal(el.getAttribute('attr4'), `${icon}-is ${v.a} part ${v.of} name in the ${v.beginning}`);
  t.equal(el.getAttribute('attr5'), `is ${v.a} part ${v.of} name ${v.at} the end-${icon}`);
  t.equal(el.getAttribute('attr6'), `is ${v.a} part ${v.of} name-${icon}-in ${v.the} middle`);
  t.equal(el.children[0].getAttribute('attr1'), `inside parent between ${v.two}${icon}${v.vars}`);
});
/*it('should bind component', (t) => {
  t.plan(1);
  var {
    el, template
  } = load('../build/simpleComponents');
  template.set('component1', true);
  console.log(template.get('component1'));
  t.equal('I am an component 1!', el.querySelector('h1').textContent);
});*/

function load(tmlpName) {
  body.innerHTML = '';
  var template = require(tmlpName);
  template.render(body);
  var el = body.childNodes[0];
  return {
    el, template
  };
}
<commit_msg>tested!<commit_after>import { /*document, window,*/ body} from 'global';
import 'misc/polyfills';
import 'misc/dom4';
import it from 'tape';
import '../build/importVars';
it('should bind text', (t) => {
  t.plan(1);
  var { el, template } = load('../build/simpleText');
  var expectedText = 'some text';
  template.set('textvar', expectedText);
  t.equal(expectedText, el.textContent);
});
it('should bind html with content', (t) => {
  t.plan(2);
  var {el, template} = load('../build/simpleHtml');
  template.set('htmlvar', 'some link');
  var a = el.querySelector('a');
  t.equal('a', a.tagName.toLowerCase());
  t.equal('some link', a.textContent);
});
it('should bind attributes', (t) => {
  t.plan(1);
  var { el, template} = load('../build/simpleAttributes');
  var values = {
    action: 'mark',
    clear: '',
    clb: 'clb3187965',
    my: 0,
    type: 'question',
    state: 'R',
    refname: 'qid',
    canmark: 1,
    totalmarks: 2,
    Totalmarks: true,
    iClassName: ''
  };
  template.set(values);
  t.equal(el.getAttribute('class'), 'mark  action--mark action--need-auth test2');
});

it('should import vars, vars in attr tmpl', t => {
  t.plan(7);
  var { el, template} = load('../build/importVars');
  var v = {
    somewhere: 'somewhere',
    beginning: 'beginning',
    the: 'the',
    of: 'of',
    at: 'at',
    two: 'two',
    vars: 'vars',
    a: 'a'
  };
  var icon = require('./styles').icon;
  template.set(v);
  t.equal(el.getAttribute('attr1'), `${icon} ${v.somewhere} in the beginning`);
  t.equal(el.getAttribute('attr2'), `somewhere ${v.at} the end ${icon}`);
  t.equal(el.getAttribute('attr3'), `${v.somewhere} ${icon} in ${v.the} middle`);
  t.equal(el.getAttribute('attr4'), `${icon}-is ${v.a} part ${v.of} name in the ${v.beginning}`);
  t.equal(el.getAttribute('attr5'), `is ${v.a} part ${v.of} name ${v.at} the end-${icon}`);
  t.equal(el.getAttribute('attr6'), `is ${v.a} part ${v.of} name-${icon}-in ${v.the} middle`);
  t.equal(el.children[0].getAttribute('attr1'), `inside parent between ${v.two}${icon}${v.vars}`);
});
it('should bind component', (t) => {
  t.plan(1);
  var { el, template } = load('../build/simpleComponents');
  template.set('component1', true);
  console.log(template.get('component1'));
  t.equal('I am an component 1!', el.querySelector('h1').textContent);
});

function load(tmlpName) {
  body.innerHTML = '';
  var template = require(tmlpName);
  template.render(body);
  var el = body.childNodes[0];
  return {
    el, template
  };
}
<|endoftext|>


<commit_before>const _ = require('lodash')
const async = require('async')
const entities = require('html-entities').AllHtmlEntities
const fs = require('fs')
const ical = require('ical')
const op = require('object-path')
const parseString = require('xml2js').parseString
const request = require('request')

const interval = 1000 * 60 * 15

var getNews = (news_url, callback) => {
    request.get({url: news_url, strictSSL: true, timeout: 1000}, (err, response, body) => {
        if(err) { return callback(err) }

        parseString(body, { trim: true, normalizeTags: true, ignoreAttrs: true }, (err, result) => {
            if(err) { return callback(err) }

            const rss = op.get(result, 'rss.channel.0.item')

            let news = []
            for (let i = 0; i < rss.length; i++) {
                news.push({
                    title: op.get(rss, [i, 'title', 0]),
                    date: new Date(op.get(rss, [i, 'pubdate', 0])),
                    text: op.get(rss, [i, 'description', 0]).replace('[…]', '...'),
                    url: op.get(rss, [i, 'link', 0])
                })
            }

            callback(null, news)
        })
    })
}

var getRooms = (rooms_url, callback) => {
    request.get({url: rooms_url, strictSSL: true, json: true, timeout: 1000}, (err, response, body) => {
        if(err) { return callback(err) }

        let rooms = []
        for (let i = 0; i < body.length; i++) {
            if(!op.has(body, [i, 'properties', 'calendar', 'values', 0, 'value'])) { continue }

            rooms.push({
                title: op.get(body, [i, 'displayname']),
                info: op.get(body, [i, 'displayinfo']),
                ical: op.get(body, [i, 'properties', 'calendar', 'values', 0, 'value']),
            })
        }

        callback(null, rooms)
    })
}

var doHarvest = () => {
    console.log('')

    getNews('http://www.artun.ee/?feed=newsticker', (err, news) => {
        if (err) { console.error(err) }

        sortedNews = _.sortBy(news, ['date'])

        fs.writeFile('./json/news.json', JSON.stringify(sortedNews, null, 3), 'utf8', () => {
            console.log((new Date()).toISOString(), `News: ${sortedNews.length}`);
        })
    })

    getRooms('https://eka.entu.ee/api/get_entity_list?only_public=true&full_info=true&entity_definition_keyname=room', (err, rooms) => {
        if (err) { console.error(err) }

        console.log((new Date()).toISOString(), `Rooms: ${rooms.length}`)

        var events = []
        async.each(rooms, (room, callback) => {
            ical.fromURL(room.ical, {}, function(err, data) {
                if(err) { return callback(err) }

                for (let k in data) {
                    if (!data.hasOwnProperty(k)) { continue }
                    if (op.get(data, [k, 'type']) !== 'VEVENT') { continue }

                    events.push({
                        title: room.title,
                        info: room.info,
                        start: op.get(data, [k, 'start']),
                        end: op.get(data, [k, 'end']),
                        summary: entities.decode(op.get(data, [k, 'summary'])),
                        description: entities.decode(op.get(data, [k, 'description']))
                    })
                }

                callback(null)
            })
        }, err => {
            if (err) { console.error(err) }

            sortedEvents = _.sortBy(events, ['start', 'end', 'title'])

            fs.writeFile('./json/events.json', JSON.stringify(sortedEvents, null, 3), 'utf8', () => {
                console.log((new Date()).toISOString(), `Events: ${sortedEvents.length}`)
            })
        })
    })
}

setInterval(doHarvest, interval)

doHarvest()
<commit_msg>Path fix<commit_after>const _ = require('lodash')
const async = require('async')
const entities = require('html-entities').AllHtmlEntities
const fs = require('fs')
const ical = require('ical')
const op = require('object-path')
const parseString = require('xml2js').parseString
const request = require('request')

const interval = 1000 * 60 * 15

var getNews = (news_url, callback) => {
    request.get({url: news_url, strictSSL: true, timeout: 1000}, (err, response, body) => {
        if(err) { return callback(err) }

        parseString(body, { trim: true, normalizeTags: true, ignoreAttrs: true }, (err, result) => {
            if(err) { return callback(err) }

            const rss = op.get(result, 'rss.channel.0.item')

            let news = []
            for (let i = 0; i < rss.length; i++) {
                news.push({
                    title: op.get(rss, [i, 'title', 0]),
                    date: new Date(op.get(rss, [i, 'pubdate', 0])),
                    text: op.get(rss, [i, 'description', 0]).replace('[…]', '...'),
                    url: op.get(rss, [i, 'link', 0])
                })
            }

            callback(null, news)
        })
    })
}

var getRooms = (rooms_url, callback) => {
    request.get({url: rooms_url, strictSSL: true, json: true, timeout: 1000}, (err, response, body) => {
        if(err) { return callback(err) }

        let rooms = []
        for (let i = 0; i < body.length; i++) {
            if(!op.has(body, [i, 'properties', 'calendar', 'values', 0, 'value'])) { continue }

            rooms.push({
                title: op.get(body, [i, 'displayname']),
                info: op.get(body, [i, 'displayinfo']),
                ical: op.get(body, [i, 'properties', 'calendar', 'values', 0, 'value']),
            })
        }

        callback(null, rooms)
    })
}

var doHarvest = () => {
    console.log('')

    getNews('http://www.artun.ee/?feed=newsticker', (err, news) => {
        if (err) { console.error(err) }

        sortedNews = _.sortBy(news, ['date'])

        fs.writeFile(path.resolve(__dirname, 'json', 'news.json'), JSON.stringify(sortedNews, null, 3), 'utf8', () => {
            console.log((new Date()).toISOString(), `News: ${sortedNews.length}`);
        })
    })

    getRooms('https://eka.entu.ee/api/get_entity_list?only_public=true&full_info=true&entity_definition_keyname=room', (err, rooms) => {
        if (err) { console.error(err) }

        console.log((new Date()).toISOString(), `Rooms: ${rooms.length}`)

        var events = []
        async.each(rooms, (room, callback) => {
            ical.fromURL(room.ical, {}, function(err, data) {
                if(err) { return callback(err) }

                for (let k in data) {
                    if (!data.hasOwnProperty(k)) { continue }
                    if (op.get(data, [k, 'type']) !== 'VEVENT') { continue }

                    events.push({
                        title: room.title,
                        info: room.info,
                        start: op.get(data, [k, 'start']),
                        end: op.get(data, [k, 'end']),
                        summary: entities.decode(op.get(data, [k, 'summary'])),
                        description: entities.decode(op.get(data, [k, 'description']))
                    })
                }

                callback(null)
            })
        }, err => {
            if (err) { console.error(err) }

            sortedEvents = _.sortBy(events, ['start', 'end', 'title'])

            fs.writeFile(path.resolve(__dirname, 'json', 'events.json'), JSON.stringify(sortedEvents, null, 3), 'utf8', () => {
                console.log((new Date()).toISOString(), `Events: ${sortedEvents.length}`)
            })
        })
    })
}

setInterval(doHarvest, interval)

doHarvest()
<|endoftext|>