<commit_before>import 'babel-polyfill'
import chai from 'chai';
let babel = require("babel-core");
let babylon = require("babylon");
const assert = chai.assert;
import cq, { NodeTypes } from '../src/index';

function lines(str, startLine, endLine) {
  return str.split('\n').slice(startLine, endLine + 1).join('\n');
}

describe('cq', () => {
  describe('createClass', () => {
    const src = `
import React, { PropTypes } from 'react';

const Switch = React.createClass({
  render() {
    return
Hi
;
  }
});

module.exports = Switch;
    `;

    it('should return a top level identifier', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Switch'
      }];

      let { code } = cq(src, query);
      const wanted = lines(src, 3, 7);
      assert.equal(code, wanted);
    });

    it('should return an inner function', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Switch',
        children: [{
          type: NodeTypes.IDENTIFIER,
          matcher: 'render'
        }]
      }];

      let { code } = cq(src, query);
      const wanted = lines(src, 4, 6);
      assert.equal(code, wanted);
    });

    it('should parse string queries', () => {
      let query = '.Switch .render';
      let { code } = cq(src, query);
      const wanted = lines(src, 4, 6);
      assert.equal(code, wanted);
    });

    it('should parse to the EOF', () => {
      let query = '.Switch-EOF';
      let { code } = cq(src, query);
      const wanted = lines(src, 3, 10);
      assert.equal(code, wanted);
    });
  });

  describe('top level functions', () => {
    const someFunctions = `
function hello() {
  return 'hello';
}

const bye = function() {
  return 'bye';
} // -> 'bye'

let Farm = () => 'cow';
bye(); // -> 'bye'
// never say goodbye
    `;

    it('should return a function definition', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'hello'
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 1, 3);
      assert.equal(code, wanted);
    })

    it('should return an anonymous function assigned to a variable', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'bye'
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 5, 7);
      assert.equal(code, wanted);
    })

    it('should return an arrow function assigned to a variable', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Farm'
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 9, 9);
      assert.equal(code, wanted);
    })

    it('should include extra lines given a modifier', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Farm',
        modifiers: [{
          type: NodeTypes.EXTRA_LINES,
          amount: -2
        }, {
          type: NodeTypes.EXTRA_LINES,
          amount: 2
        }]
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 7, 11);
      assert.equal(code, wanted);
    })

    it('should get a range', () => {
      let query = [{
        type: NodeTypes.RANGE,
        start: {
          type: NodeTypes.IDENTIFIER,
          matcher: 'hello'
        },
        end: {
          type: NodeTypes.IDENTIFIER,
          matcher: 'Farm'
        }
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 1, 9);
      assert.equal(code, wanted);
    })

    it('should get a range with modifiers', () => {
      let query = [{
        type: NodeTypes.RANGE,
        start: {
          type: NodeTypes.IDENTIFIER,
          matcher: 'bye'
        },
        end: {
          type: NodeTypes.IDENTIFIER,
          matcher: 'Farm'
        },
        modifiers: [{
          type: NodeTypes.EXTRA_LINES,
          amount: -2
        }, {
          type: NodeTypes.EXTRA_LINES,
          amount: 2
        }]
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 3, 11);
      assert.equal(code, wanted);
    })

    it('should get a range with line numbers', () => {
      let query = [{
        type: NodeTypes.RANGE,
        start: {
          type: NodeTypes.LINE_NUMBER,
          value: 10
        },
        end: {
          type: NodeTypes.LINE_NUMBER,
          value: 12
        }
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 9, 11);
      assert.equal(code, wanted);
    })
  })

  describe('createClass Plus', () => {
    const reactCreateClass = `
import React, { PropTypes } from 'react';

const Switch = React.createClass({
  cats() {
    return 'cats'
  },

  renderOtherStuff() {
    return
Other Stuff
;
  },

  render() {
    return
{this.renderOtherStuff()}
;
  }
});

module.exports = Switch;
    `;

    it('should return an inner range function', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Switch',
        children: [{
          type: NodeTypes.RANGE,
          start: {
            type: NodeTypes.IDENTIFIER,
            matcher: 'renderOtherStuff'
          },
          end: {
            type: NodeTypes.IDENTIFIER,
            matcher: 'render'
          }
        }]
      }];

      let { code } = cq(reactCreateClass, query);
      const wanted = lines(reactCreateClass, 8, 14);
      // console.log('actual', code, 'wanted', wanted);

      assert.equal(code, wanted);
    });
  });

  describe('ES6 Classes', () => {
    const es6Class = `
class Polygon {
  static distance(a, b) {
      const dx = a.x - b.x;
      const dy = a.y - b.y;
      return Math.sqrt(dx*dx + dy*dy);
  }

  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea();
  }

  calcArea() {
    return this.height * this.width;
  }
}

const square = new Polygon(10, 10);

console.log(square.area);
    `;

    it('return an ES6 class', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Polygon',
       }];

      let { code } = cq(es6Class, query);
      const wanted = lines(es6Class, 1, 20);

      assert.equal(code, wanted);
    });

    it('return functions from within a class', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Polygon',
        children: [{
          type: NodeTypes.RANGE,
          start: {
            type: NodeTypes.IDENTIFIER,
            matcher: 'distance'
          },
          end: {
            type: NodeTypes.IDENTIFIER,
            matcher: 'area'
          }
        }]
       }];

      let { code } = cq(es6Class, query);
      const wanted = lines(es6Class, 2, 15);

      assert.equal(code, wanted);
    });
  });

  describe('more ES6 Classes', () => {
    const src = `
class Square {
  area() {
    return this.height * this.width;
  }
}

class Circle {
  area() {
    return PI * this.radius ** 2;
  }
}
    `;

    it('return disambiguate based on parent', () => {
      let { code } = cq(src, '.Circle .area');
      const wanted = lines(src, 8, 10);
      assert.equal(code, wanted);
    });

  });

  describe('searching for strings', () => {
    const src = `
import foo from 'bar';
// here is a nice test
describe('My Test', () => {
  it('should pass', () => {
    expect(1).toEqual(1);
  })
});

describe('Other Test', () => {
  it('should pass', () => {
    expect(2).toEqual(2);
  })
});
    `;

    it('find a whole test', () => {
      let { code } = cq(src, "'My Test'");
      const wanted = lines(src, 3, 7);
      assert.equal(code, wanted);
    })

    it('find a child should', () => {
      let { code } = cq(src, "'My Test' 'should pass'");
      const wanted = lines(src, 4, 6);
      assert.equal(code, wanted);
    })

    it('find a child should with the same name', () => {
      let { code } = cq(src, "'Other Test' 'should pass'");
      const wanted = lines(src, 10, 12);
      assert.equal(code, wanted);
    })

    it('find strings in a range', () => {
      let { code } = cq(src, "1-'My Test'");
      const wanted = lines(src, 0, 7);
      assert.equal(code, wanted);
    })
  });

});
<commit_msg>convert a couple of modifier queries to short-hand syntax<commit_after>import 'babel-polyfill'
import chai from 'chai';
let babel = require("babel-core");
let babylon = require("babylon");
const assert = chai.assert;
import cq, { NodeTypes } from '../src/index';

function lines(str, startLine, endLine) {
  return str.split('\n').slice(startLine, endLine + 1).join('\n');
}

describe('babylon', () => {
  describe('createClass', () => {
    const src = `
import React, { PropTypes } from 'react';

const Switch = React.createClass({
  render() {
    return
Hi
;
  }
});

module.exports = Switch;
    `;

    it('should return a top level identifier', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Switch'
      }];

      let { code } = cq(src, query);
      const wanted = lines(src, 3, 7);
      assert.equal(code, wanted);
    });

    it('should return an inner function', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Switch',
        children: [{
          type: NodeTypes.IDENTIFIER,
          matcher: 'render'
        }]
      }];

      let { code } = cq(src, query);
      const wanted = lines(src, 4, 6);
      assert.equal(code, wanted);
    });

    it('should parse string queries', () => {
      let query = '.Switch .render';
      let { code } = cq(src, query);
      const wanted = lines(src, 4, 6);
      assert.equal(code, wanted);
    });

    it('should parse to the EOF', () => {
      let query = '.Switch-EOF';
      let { code } = cq(src, query);
      const wanted = lines(src, 3, 10);
      assert.equal(code, wanted);
    });
  });

  describe('top level functions', () => {
    const someFunctions = `
function hello() {
  return 'hello';
}

const bye = function() {
  return 'bye';
} // -> 'bye'

let Farm = () => 'cow';
bye(); // -> 'bye'
// never say goodbye
    `;

    it('should return a function definition', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'hello'
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 1, 3);
      assert.equal(code, wanted);
    })

    it('should return an anonymous function assigned to a variable', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'bye'
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 5, 7);
      assert.equal(code, wanted);
    })

    it('should return an arrow function assigned to a variable', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Farm'
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 9, 9);
      assert.equal(code, wanted);
    })

    it('should include extra lines given a modifier', () => {
      let { code } = cq(someFunctions, '.Farm:-2,+2');
      const wanted = lines(someFunctions, 7, 11);
      assert.equal(code, wanted);
    })

    it('should get a range', () => {
      let query = [{
        type: NodeTypes.RANGE,
        start: {
          type: NodeTypes.IDENTIFIER,
          matcher: 'hello'
        },
        end: {
          type: NodeTypes.IDENTIFIER,
          matcher: 'Farm'
        }
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 1, 9);
      assert.equal(code, wanted);
    })

    it('should get a range with modifiers', () => {
      let { code } = cq(someFunctions, '.bye-.Farm:-2,+2');
      const wanted = lines(someFunctions, 3, 11);
      assert.equal(code, wanted);
    })

    it('should get a range with line numbers', () => {
      let query = [{
        type: NodeTypes.RANGE,
        start: {
          type: NodeTypes.LINE_NUMBER,
          value: 10
        },
        end: {
          type: NodeTypes.LINE_NUMBER,
          value: 12
        }
      }];

      let { code } = cq(someFunctions, query);
      const wanted = lines(someFunctions, 9, 11);
      assert.equal(code, wanted);
    })
  })

  describe('createClass Plus', () => {
    const reactCreateClass = `
import React, { PropTypes } from 'react';

const Switch = React.createClass({
  cats() {
    return 'cats'
  },

  renderOtherStuff() {
    return
Other Stuff
;
  },

  render() {
    return
{this.renderOtherStuff()}
;
  }
});

module.exports = Switch;
    `;

    it('should return an inner range function', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Switch',
        children: [{
          type: NodeTypes.RANGE,
          start: {
            type: NodeTypes.IDENTIFIER,
            matcher: 'renderOtherStuff'
          },
          end: {
            type: NodeTypes.IDENTIFIER,
            matcher: 'render'
          }
        }]
      }];

      let { code } = cq(reactCreateClass, query);
      const wanted = lines(reactCreateClass, 8, 14);
      // console.log('actual', code, 'wanted', wanted);

      assert.equal(code, wanted);
    });
  });

  describe('ES6 Classes', () => {
    const es6Class = `
class Polygon {
  static distance(a, b) {
      const dx = a.x - b.x;
      const dy = a.y - b.y;
      return Math.sqrt(dx*dx + dy*dy);
  }

  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea();
  }

  calcArea() {
    return this.height * this.width;
  }
}

const square = new Polygon(10, 10);

console.log(square.area);
    `;

    it('return an ES6 class', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Polygon',
       }];

      let { code } = cq(es6Class, query);
      const wanted = lines(es6Class, 1, 20);

      assert.equal(code, wanted);
    });

    it('return functions from within a class', () => {
      let query = [{
        type: NodeTypes.IDENTIFIER,
        matcher: 'Polygon',
        children: [{
          type: NodeTypes.RANGE,
          start: {
            type: NodeTypes.IDENTIFIER,
            matcher: 'distance'
          },
          end: {
            type: NodeTypes.IDENTIFIER,
            matcher: 'area'
          }
        }]
       }];

      let { code } = cq(es6Class, query);
      const wanted = lines(es6Class, 2, 15);

      assert.equal(code, wanted);
    });
  });

  describe('more ES6 Classes', () => {
    const src = `
class Square {
  area() {
    return this.height * this.width;
  }
}

class Circle {
  area() {
    return PI * this.radius ** 2;
  }
}
    `;

    it('return disambiguate based on parent', () => {
      let { code } = cq(src, '.Circle .area');
      const wanted = lines(src, 8, 10);
      assert.equal(code, wanted);
    });

  });

  describe('searching for strings', () => {
    const src = `
import foo from 'bar';
// here is a nice test
describe('My Test', () => {
  it('should pass', () => {
    expect(1).toEqual(1);
  })
});

describe('Other Test', () => {
  it('should pass', () => {
    expect(2).toEqual(2);
  })
});
    `;

    it('find a whole test', () => {
      let { code } = cq(src, "'My Test'");
      const wanted = lines(src, 3, 7);
      assert.equal(code, wanted);
    })

    it('find a child should', () => {
      let { code } = cq(src, "'My Test' 'should pass'");
      const wanted = lines(src, 4, 6);
      assert.equal(code, wanted);
    })

    it('find a child should with the same name', () => {
      let { code } = cq(src, "'Other Test' 'should pass'");
      const wanted = lines(src, 10, 12);
      assert.equal(code, wanted);
    })

    it('find strings in a range', () => {
      let { code } = cq(src, "1-'My Test'");
      const wanted = lines(src, 0, 7);
      assert.equal(code, wanted);
    })
  });

});
<|endoftext|>


<commit_before>var _ = require('lodash');
var Router = require('director').Router;

var RoutesAction = require('../actions/routes');
var RoutesStore = require('../stores/routes');

var router;

module.exports = {
  back: function() {
    var stacks = RoutesStore.getStacks();
    if (stacks.length > 1) {
      router.setRoute(stacks[stacks.length - 2]);
    }
  },

  navigateTo: function(path) {
    router.setRoute(path);
  },

  create: function(routes, options) {
    var originalOn = options && options.on;
    var on = [function() {
      RoutesAction.navigateTo(router.getRoute().join('/'));
    }];
    if (_.isFunction(originalOn)) {
      on.push(originalOn);
    } else if (_.isArray(originalOn)) {
      on = on.concat(originalOn);
    }
    router = new Router(routes).configure(_.merge({}, options, {on: on}));
    router.init('/');
    return router;
  }
};
<commit_msg>correct route<commit_after>var _ = require('lodash');
var Router = require('director').Router;

var RoutesAction = require('../actions/routes');
var RoutesStore = require('../stores/routes');

var router;

module.exports = {
  back: function() {
    var stacks = RoutesStore.getStacks();
    if (stacks.length > 1) {
      router.setRoute(stacks[stacks.length - 2]);
    }
  },

  navigateTo: function(path) {
    router.setRoute(path);
  },

  create: function(routes, options) {
    var originalOn = options && options.on;
    var on = [function() {
      RoutesAction.navigateTo('/' + router.getRoute().join('/'));
    }];
    if (_.isFunction(originalOn)) {
      on.push(originalOn);
    } else if (_.isArray(originalOn)) {
      on = on.concat(originalOn);
    }
    router = new Router(routes).configure(_.merge({}, options, {on: on}));
    router.init('/');
    return router;
  }
};
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

describe('OpenlmisTableFiltersController', function() {

    var vm, form, $scope, filterButton;

    beforeEach(function() {
        module('openlmis-table-filter');

        inject(function($injector) {
            $controller = $injector.get('$controller');
            $compile = $injector.get('$compile');
            $rootScope = $injector.get('$rootScope');
        });

        $scope = $rootScope.$new();
        vm = $controller('OpenlmisTableFiltersController', {
            $scope: $scope
        });
    });

    describe('getFormElement', function() {

        it('should return undefined if controller was not initialized', function() {
            expect(vm.getFormElement()).toBeUndefined();
        });

        it('should return form if controller was initialized', function() {
            vm.$onInit();

            form = vm.getFormElement();

            expect(form).not.toBeUndefined();
            expect(form.is('form')).toBe(true);
        });

        it('should return a form with a submit button', function() {
            vm.$onInit();

            form = vm.getFormElement();

            expect(form.find('[type="submit"]').length).toBe(1);
        });

    });

    describe('getFilterButton', function() {

        it('should return undefined if controller was not initialized', function() {
            expect(vm.getFilterButton()).toBeUndefined();
        });

        it('should return form if controller was initialized', function() {
            vm.$onInit();

            filterButton = vm.getFilterButton();

            expect(filterButton).not.toBeUndefined();
            expect(filterButton.is('button')).toBe(true);
        });

    });

    describe('registerElement', function() {

        beforeEach(prepareForm);

        it('should add registered element to the form', function() {
            var element = angular.element('

');

            vm.registerElement(element);

            expect(form.find(element).length).toBe(1);
        });

        it('should override submit if some other submit element was marked as filter', function() {
            var submit = angular.element('<input type="submit"/>');

            expect(form.find('[type="submit"]').is(submit)).toBe(false);

            vm.registerElement(submit);
            $rootScope.$apply();

            expect(form.find('[type="submit"]').length).toBe(1);
            expect(form.find('[type="submit"]').is(submit)).toBe(true);
        });

        it('should override submit if registered element has a submit element descendant', function() {
            var submit = angular.element('<input type="submit"/>'),
                element = angular.element('

');

            element.append(submit);

            expect(form.find('[type="submit"]').is(submit)).toBe(false);

            vm.registerElement(element);
            $rootScope.$apply();

            expect(form.find('[type="submit"]').length).toBe(1);
            expect(form.find('[type="submit"]').is(submit)).toBe(true);
        });

        it('should copy children if registering form', function() {
            var elementOne = angular.element('<input id="elementOne"/>'),
                elementTwo = angular.element('<input id="elementTwo"/>'),
                newForm = angular.element('<form></form>');

            newForm.append(elementOne);
            newForm.append(elementTwo);

            vm.registerElement(newForm);

            expect(form.find(elementOne).length).toBe(1);
            expect(form.find(elementTwo).length).toBe(1);
            expect(form.is(newForm)).toBe(false);
        });

        it('should detach registered form', function() {
            var newForm = angular.element('<form></form>');

            spyOn(newForm, 'detach');

            vm.registerElement(newForm);

            expect(newForm.detach).toHaveBeenCalled();
        });

    });

    describe('$onDestroy', function() {

        beforeEach(prepareFilterButton);

        it('should close modal', function() {
            vm.$onDestroy();

            expect(filterButton.popover).toHaveBeenCalledWith('hide');
        });

    });

    describe('filterButton', function() {

        beforeEach(function() {
            prepareFilterButton();
            spyOn(filterButton, 'show');
        });

        it('should be hidden if no elements were registered', function() {
            expect(filterButton.show).not.toHaveBeenCalled();
        });

        it('should be visible if at least one element was registered', function() {
            vm.registerElement(compileMarkup('

'));

            expect(filterButton.show).toHaveBeenCalled();
        });

    });

    describe('popover', function() {

        beforeEach(prepareFilterButton);

        it('should close on submit click', function() {
            form.find('#close-filters').click();

            expect(filterButton.popover).toHaveBeenCalledWith('hide');
        });

        it('should close on cancel click', function() {
            form.find('[type="submit"]').click();

            expect(filterButton.popover).toHaveBeenCalledWith('hide');
        });

        it('should not open if form is pristine and valid', function() {
            expect(filterButton.popover).not.toHaveBeenCalledWith('show');
        });

        //This handles popover opening when we enter the state and the form is has empty required
        //fields
        it('should open if form is pristine and invalid', function() {
            expect(filterButton.popover).not.toHaveBeenCalledWith('show');

            form.controller('form').$setValidity('isInvalid', false);
            $scope.$apply();

            expect(filterButton.popover).toHaveBeenCalledWith('show');
        });

        it('should not open if form is dirty and invalid', function() {
            form.controller('form').$setDirty();
            $scope.$apply();

            expect(filterButton.popover).not.toHaveBeenCalledWith('show');
        });

    });

    describe('submit event', function() {

        beforeEach(prepareForm);

        it('should contain a map of input names and model values', function() {
            var modelValues,
                modelOne = 'someValue1',
                modelTwo = 1,
                modelThree = {
                    some: "otheValue"
                };

            $scope.modelOne = modelOne;
            $scope.modelTwo = modelTwo;
            $scope.modelThree = modelThree;

            vm.registerElement(compileMarkup('<input name="inputOne" ng-model="modelOne"/>'));
            vm.registerElement(compileMarkup('<input name="inputTwo" ng-model="modelTwo"/>'));
            vm.registerElement(compileMarkup('<input name="inputThree" ng-model="modelThree"/>'));

            $scope.$on('openlmis-table-filter', function(event, args) {
                modelValues = args;
            });

            form.submit();
            $scope.$apply();

            expect(modelValues.inputOne).toEqual(modelOne);
            expect(modelValues.inputTwo).toEqual(modelTwo);
            expect(modelValues.inputThree).toEqual(modelThree);
        });

    });

    it('should submit all registered forms if the main one was submitted', function() {
        window.onbeforeunload = function() {};

        var formOne = compileMarkup('<form></form>'),
            formTwo = compileMarkup('<form></form>');

        var formOneSubmitted;
        formOne.on('submit', function() {
            formOneSubmitted = true;
        });

        var formTwoSubmitted;
        formTwo.on('submit', function() {
            formTwoSubmitted = true;
        });

        vm.$onInit();
        form = vm.getFormElement();

        vm.registerElement(formOne);
        vm.registerElement(formTwo);

        form.submit();

        expect(formOneSubmitted).toBe(true);
        expect(formTwoSubmitted).toBe(true);
    });

    function prepareFilterButton() {
        prepareForm();
        filterButton = vm.getFilterButton();
        spyOn(filterButton, 'popover').andCallThrough();
    }

    function prepareForm() {
        vm.$onInit();
        form = vm.getFormElement();
    }

    //TODO: DRY this a bit, as it is repeated in numerous tests
    function compileMarkup(markup) {
        var element = $compile(markup)($scope);

        angular.element('body').append(element);
        $scope.$apply();

        return element;
    }

});
<commit_msg>OLMIS-2656: Commented out bugged tests<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

describe('OpenlmisTableFiltersController', function() {

    var vm, form, $scope, filterButton;

    beforeEach(function() {
        module('openlmis-table-filter');

        inject(function($injector) {
            $controller = $injector.get('$controller');
            $compile = $injector.get('$compile');
            $rootScope = $injector.get('$rootScope');
        });

        $scope = $rootScope.$new();
        vm = $controller('OpenlmisTableFiltersController', {
            $scope: $scope
        });
    });

    describe('getFormElement', function() {

        it('should return undefined if controller was not initialized', function() {
            expect(vm.getFormElement()).toBeUndefined();
        });

        it('should return form if controller was initialized', function() {
            vm.$onInit();

            form = vm.getFormElement();

            expect(form).not.toBeUndefined();
            expect(form.is('form')).toBe(true);
        });

        it('should return a form with a submit button', function() {
            vm.$onInit();

            form = vm.getFormElement();

            expect(form.find('[type="submit"]').length).toBe(1);
        });

    });

    describe('getFilterButton', function() {

        it('should return undefined if controller was not initialized', function() {
            expect(vm.getFilterButton()).toBeUndefined();
        });

        it('should return form if controller was initialized', function() {
            vm.$onInit();

            filterButton = vm.getFilterButton();

            expect(filterButton).not.toBeUndefined();
            expect(filterButton.is('button')).toBe(true);
        });

    });

    describe('registerElement', function() {

        beforeEach(prepareForm);

        it('should add registered element to the form', function() {
            var element = angular.element('

');

            vm.registerElement(element);

            expect(form.find(element).length).toBe(1);
        });

        it('should override submit if some other submit element was marked as filter', function() {
            var submit = angular.element('<input type="submit"/>');

            expect(form.find('[type="submit"]').is(submit)).toBe(false);

            vm.registerElement(submit);
            $rootScope.$apply();

            expect(form.find('[type="submit"]').length).toBe(1);
            expect(form.find('[type="submit"]').is(submit)).toBe(true);
        });

        it('should override submit if registered element has a submit element descendant', function() {
            var submit = angular.element('<input type="submit"/>'),
                element = angular.element('

');

            element.append(submit);

            expect(form.find('[type="submit"]').is(submit)).toBe(false);

            vm.registerElement(element);
            $rootScope.$apply();

            expect(form.find('[type="submit"]').length).toBe(1);
            expect(form.find('[type="submit"]').is(submit)).toBe(true);
        });

        it('should copy children if registering form', function() {
            var elementOne = angular.element('<input id="elementOne"/>'),
                elementTwo = angular.element('<input id="elementTwo"/>'),
                newForm = angular.element('<form></form>');

            newForm.append(elementOne);
            newForm.append(elementTwo);

            vm.registerElement(newForm);

            expect(form.find(elementOne).length).toBe(1);
            expect(form.find(elementTwo).length).toBe(1);
            expect(form.is(newForm)).toBe(false);
        });

        it('should detach registered form', function() {
            var newForm = angular.element('<form></form>');

            spyOn(newForm, 'detach');

            vm.registerElement(newForm);

            expect(newForm.detach).toHaveBeenCalled();
        });

    });

    describe('$onDestroy', function() {

        beforeEach(prepareFilterButton);

        it('should close modal', function() {
            vm.$onDestroy();

            expect(filterButton.popover).toHaveBeenCalledWith('hide');
        });

    });

    describe('filterButton', function() {

        beforeEach(function() {
            prepareFilterButton();
            spyOn(filterButton, 'show');
        });

        it('should be hidden if no elements were registered', function() {
            expect(filterButton.show).not.toHaveBeenCalled();
        });

        it('should be visible if at least one element was registered', function() {
            vm.registerElement(compileMarkup('

'));

            expect(filterButton.show).toHaveBeenCalled();
        });

    });

    describe('popover', function() {

        beforeEach(prepareFilterButton);

        it('should close on submit click', function() {
            form.find('#close-filters').click();

            expect(filterButton.popover).toHaveBeenCalledWith('hide');
        });

        it('should close on cancel click', function() {
            form.find('[type="submit"]').click();

            expect(filterButton.popover).toHaveBeenCalledWith('hide');
        });

        it('should not open if form is pristine and valid', function() {
            expect(filterButton.popover).not.toHaveBeenCalledWith('show');
        });

        //This handles popover opening when we enter the state and the form is has empty required
        //fields
        it('should open if form is pristine and invalid', function() {
            expect(filterButton.popover).not.toHaveBeenCalledWith('show');

            form.controller('form').$setValidity('isInvalid', false);
            $scope.$apply();

            expect(filterButton.popover).toHaveBeenCalledWith('show');
        });

        it('should not open if form is dirty and invalid', function() {
            form.controller('form').$setDirty();
            $scope.$apply();

            expect(filterButton.popover).not.toHaveBeenCalledWith('show');
        });

    });
/**
    describe('submit event', function() {

        beforeEach(prepareForm);

        it('should contain a map of input names and model values', function() {
            var modelValues,
                modelOne = 'someValue1',
                modelTwo = 1,
                modelThree = {
                    some: "otheValue"
                };

            $scope.modelOne = modelOne;
            $scope.modelTwo = modelTwo;
            $scope.modelThree = modelThree;

            vm.registerElement(compileMarkup('<input name="inputOne" ng-model="modelOne"/>'));
            vm.registerElement(compileMarkup('<input name="inputTwo" ng-model="modelTwo"/>'));
            vm.registerElement(compileMarkup('<input name="inputThree" ng-model="modelThree"/>'));

            $scope.$on('openlmis-table-filter', function(event, args) {
                modelValues = args;
            });

            form.submit();
            $scope.$apply();

            expect(modelValues.inputOne).toEqual(modelOne);
            expect(modelValues.inputTwo).toEqual(modelTwo);
            expect(modelValues.inputThree).toEqual(modelThree);
        });

    });

    it('should submit all registered forms if the main one was submitted', function() {
        window.onbeforeunload = function() {};

        var formOne = compileMarkup('<form></form>'),
            formTwo = compileMarkup('<form></form>');

        var formOneSubmitted;
        formOne.on('submit', function() {
            formOneSubmitted = true;
        });

        var formTwoSubmitted;
        formTwo.on('submit', function() {
            formTwoSubmitted = true;
        });

        vm.$onInit();
        form = vm.getFormElement();

        vm.registerElement(formOne);
        vm.registerElement(formTwo);

        form.submit();

        expect(formOneSubmitted).toBe(true);
        expect(formTwoSubmitted).toBe(true);
    });
**/

    function prepareFilterButton() {
        prepareForm();
        filterButton = vm.getFilterButton();
        spyOn(filterButton, 'popover').andCallThrough();
    }

    function prepareForm() {
        vm.$onInit();
        form = vm.getFormElement();
    }

    //TODO: DRY this a bit, as it is repeated in numerous tests
    function compileMarkup(markup) {
        var element = $compile(markup)($scope);

        angular.element('body').append(element);
        $scope.$apply();

        return element;
    }

});
<|endoftext|>


<commit_before><commit_msg>full stop<commit_after><|endoftext|>


<commit_before>var debug = false;
function log(m) { if (console && console.log && debug) console.log(m); }

var collectionHandle = "";
var resultsTemplate = null;

function queryLinksCollection (queryString) {
    log("Querying: " + $.param({q:queryString||""}));
    $(".dateGroup").remove();
    $("#infoMsg").hide();
    var url = "/Me/" + collectionHandle + "/search?q=" + queryString;
    if (!queryString) url = "/Me/" + collectionHandle + '/getLinksFull?limit=100&fields={"link":1,"title":1,"at":1,"network":1,"from":1,"fromID":1,"via.user.screen_name":1,"favicon":1}';
    $.ajax({
      "url": url,
      type: "GET",
      dataType: "json",
      success: function(data) {
        //called when successful
        if (!data || data.length === 0) {
            $("#infoMsg").attr("class", "info");
            $("#infoMsg").text("No results found");
            $("#infoMsg").show();
            return;
        }
        // First we sort it by the at field then we're going to group it by date
        var dateGroups = []; // Array of objectcs matching {date:..., links:[...]}
        var curDate = null;
        var curLinks;
        for (var i = 0; i < data.length; ++i) {
            // We unset all the non compared fields
            var nextDate = new Date;
            nextDate.setTime(parseInt(data[i].at));
            nextDate.setHours(0);
            nextDate.setMinutes(0);
            nextDate.setSeconds(0);
            nextDate.setMilliseconds(0);

            // If it's a different date let's start a new group of links
            if (!curDate || nextDate.getTime() != curDate.getTime()) {
                var newDateGroup = {date:nextDate.strftime("%A, %B %d, %Y"), links:[]};
                dateGroups.push(newDateGroup);
                curLinks = newDateGroup.links;
                curDate = nextDate;
            }

            curLinks.push(data[i]);
        }
        $("#results").render({groups:dateGroups,groupClass:"dateGroup"}, resultsTemplate);
        $("#results").show();
        $(".viewMore").click(function() {
            if ($(this).text().indexOf("Hide") > 0) {
                $(this).parents(".linkInfo").find(".embedView").hide(250);
                $(this).html("▶ View");
            } else {
                var elem = $(this).parents(".linkInfo").find(".embedView");
                var E = $(this);
                $.ajax({
                  url: "/Me/" + collectionHandle + "/embed?url=" + $(this).parents(".linkInfo").find("a").attr("href"),
                  type: "GET",
                  dataType: "json",
                  success: function(data) {
                      if (data.html) {
                          elem.html(data.html);
                      } else if (data.thumbnail_url) {
                          elem.html("
" + data.description||"" + "
");
                      } else {
                          elem.html("No preview.");
                      }
                      elem.show(250);
                      E.html("▼ Hide");
                  },
                  error: function() {

                  }
                });
                E.html(" Loading...");
                //$(this).html("▶ View");
            }
        });
      },
      error: function() {
        //called when there is an error
      }
    });
}

function findLinksCollection() {
    log("Finding the collection");
    $.ajax({
      url: "/providers?types=link",
      type: "GET",
      dataType: "json",
      success: function(data) {
          for (var i = 0; i < data.length; ++i) {
              if (data[i].provides.indexOf("link") > -1 && data[i].is === "collection") {
                  collectionHandle = data[i].id;
                  $("#loading").hide();
                  $("header").show();
                  break;
              }
          }
          // If we couldn't find a collection bail out
          if (collectionHandle === "") {
              showError("Could not find a valid links Collection to display.  Please contact your system administrator.");
              return;
          }
          queryLinksCollection();
      },
      error: function() {
          showError("Could not find a valid links Collection to display.  Please contact your system administrator.");
      }
    });
}

function showError(errorMessage) {
    $("#infoMsg").text(errorMessage);
    $("#infoMsg").attr("class", "error");
    $("#infoMsg").show();
    $("#results").hide();
    $("#loading").hide();
}

$(function(){
    resultsTemplate = $p("#results").compile({
        "div.templateDateGroup" : {
            // Loop on each date group
            "group<-groups" : {
                "@class":"groupClass",
                "div.dateInfo":"group.date",
                "div.linkInfo" : {
                    // On each date group we loop the links
                    "link<-group.links": {
                        "img.providerIcon@src":function(arg, item) {
                            var images = {
                                "facebook":"img/facebook.png",
                                "twitter":"img/twitter.png"
                            };
                            return (arg.item.encounters.length > 0) ? images[arg.item.encounters[arg.item.encounters.length - 1].network] : "img/1x1-pixel.png";
                        },
                        "div.fullInfo@class+":function(arg) {
                            var theClass = arg.pos % 2 === 0 ? " even" : " odd";
                            if (!arg.item.title && arg.item.link.length < 200) theClass += " shiftDownDesc";
                            return theClass;
                        },
                        "img.favicon@src":"link.favicon",
                        "a.expandedLink":function(arg) {
                            if (arg.item.link.length > 100) {
                                return arg.item.link.substring(0, 100) + "...";
                            } else {
                                return arg.item.link;
                            }
                        },
                        "a@href":"link.link",
                        "span.linkDescription":"link.title",
                        "span.linkFrom":function(arg) {
                            return "From: " + arg.item.encounters.map(function(item) {
                                var base = (item.network == "twitter") ? "http://twitter.com/#" : "http://facebook.com/";
                                var id = (item.network == "twitter") ? item.via.user.screen_name : item.fromID;
                                return ''+item.from+'';
                            }).join(", ") + " - " + getSincePrettified(arg.item.encounters[arg.item.encounters.length - 1].at);
                        },
                        "span.linkFrom@style":function(arg) {
                            return arg.item.encounters[arg.item.encounters.length - 1].from ? "" : "display:none";
                        }
                    }
                }
            }
        }
    });

    $("#searchForm").submit(function() {
        queryLinksCollection($("#linksQuery").val());
        return false;
    });
    findLinksCollection();
    $("#searchLinks").click(function(){
        queryLinksCollection($("#linksQuery").val());
        return false;
    });
});

function hideMe() {
    $(event.srcElement).hide();
}

function getSincePrettified(timestamp) {
    var tip;
    var timeDiff = Date.now() - timestamp;
    if (timeDiff < 60000) {
        tip = 'less than a minute ago';
    } else if (timeDiff < 3600000) {
        var min = Math.floor(timeDiff / 60000);
        tip =  min + ' minute' + (min > 1?'s':'') + ' ago';
    } else if (timeDiff < 43200000) {
        tip = 'over an hour ago';
    } else if (timeDiff < 43800000) {
        var hour = Math.floor(timeDiff / 3600000);
        tip =  hour + ' minute' + (hour > 1?'s':'') + ' ago';
    } else {
        var d = new Date();
        d.setTime(timestamp);
        tip = d.toString();
    }
    return tip;
}
<commit_msg>whole bunch of link fixups and cleanups<commit_after>var debug = false;
function log(m) { if (console && console.log && debug) console.log(m); }

var collectionHandle = "";
var resultsTemplate = null;

function queryLinksCollection (queryString) {
    log("Querying: " + $.param({q:queryString||""}));
    $(".dateGroup").remove();
    $("#infoMsg").hide();
    var url = "/Me/" + collectionHandle + "/search?q=" + queryString;
    if (!queryString) url = "/Me/" + collectionHandle + '/getLinksFull?limit=100&fields={"link":1,"title":1,"at":1,"network":1,"from":1,"fromID":1,"via.user.screen_name":1,"favicon":1}';
    $.ajax({
      "url": url,
      type: "GET",
      dataType: "json",
      success: function(data) {
        //called when successful
        if (!data || data.length === 0) {
            $("#infoMsg").attr("class", "info");
            $("#infoMsg").text("No results found");
            $("#infoMsg").show();
            return;
        }
        // First we sort it by the at field then we're going to group it by date
        var dateGroups = []; // Array of objectcs matching {date:..., links:[...]}
        var curDate = null;
        var curLinks;
        for (var i = 0; i < data.length; ++i) {
            // We unset all the non compared fields
            var nextDate = new Date;
            nextDate.setTime(parseInt(data[i].at));
            nextDate.setHours(0);
            nextDate.setMinutes(0);
            nextDate.setSeconds(0);
            nextDate.setMilliseconds(0);

            // If it's a different date let's start a new group of links
            if (!curDate || nextDate.getTime() != curDate.getTime()) {
                var newDateGroup = {date:nextDate.strftime("%A, %B %d, %Y"), links:[]};
                dateGroups.push(newDateGroup);
                curLinks = newDateGroup.links;
                curDate = nextDate;
            }

            curLinks.push(data[i]);
        }
        $("#results").render({groups:dateGroups,groupClass:"dateGroup"}, resultsTemplate);
        $("#results").show();
        $(".viewMore").click(function() {
            if ($(this).text().indexOf("Hide") > 0) {
                $(this).parents(".linkInfo").find(".embedView").hide(250);
                $(this).html("▶ View");
            } else {
                var elem = $(this).parents(".linkInfo").find(".embedView");
                var E = $(this);
                $.ajax({
                  url: "/Me/" + collectionHandle + "/embed?url=" + $(this).parents(".linkInfo").find("a").attr("href"),
                  type: "GET",
                  dataType: "json",
                  success: function(data) {
                      if (data.html) {
                          elem.html(data.html);
                      } else if (data.thumbnail_url) {
                          elem.html("
" + data.description||"" + "
");
                      } else {
                          elem.html("No preview.");
                      }
                      elem.show(250);
                      E.html("▼ Hide");
                  },
                  error: function() {

                  }
                });
                E.html(" Loading...");
                //$(this).html("▶ View");
            }
        });
      },
      error: function() {
        //called when there is an error
      }
    });
}

function findLinksCollection() {
    log("Finding the collection");
    $.ajax({
      url: "/providers?types=link",
      type: "GET",
      dataType: "json",
      success: function(data) {
          for (var i = 0; i < data.length; ++i) {
              if (data[i].provides.indexOf("link") > -1 && data[i].is === "collection") {
                  collectionHandle = data[i].id;
                  $("#loading").hide();
                  $("header").show();
                  break;
              }
          }
          // If we couldn't find a collection bail out
          if (collectionHandle === "") {
              showError("Could not find a valid links Collection to display.  Please contact your system administrator.");
              return;
          }
          queryLinksCollection();
      },
      error: function() {
          showError("Could not find a valid links Collection to display.  Please contact your system administrator.");
      }
    });
}

function showError(errorMessage) {
    $("#infoMsg").text(errorMessage);
    $("#infoMsg").attr("class", "error");
    $("#infoMsg").show();
    $("#results").hide();
    $("#loading").hide();
}

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

$(function(){
    resultsTemplate = $p("#results").compile({
        "div.templateDateGroup" : {
            // Loop on each date group
            "group<-groups" : {
                "@class":"groupClass",
                "div.dateInfo":"group.date",
                "div.linkInfo" : {
                    // On each date group we loop the links
                    "link<-group.links": {
                        "img.providerIcon@src":function(arg, item) {
                            var images = {
                                "facebook":"img/facebook.png",
                                "twitter":"img/twitter.png"
                            };
                            return (arg.item.encounters.length > 0) ? images[arg.item.encounters[arg.item.encounters.length - 1].network] : "img/1x1-pixel.png";
                        },
                        "div.fullInfo@class+":function(arg) {
                            var theClass = arg.pos % 2 === 0 ? " even" : " odd";
                            if (!arg.item.title && arg.item.link.length < 200) theClass += " shiftDownDesc";
                            return theClass;
                        },
                        "img.favicon@src":"link.favicon",
                        "a.expandedLink":function(arg) {
                            if (arg.item.link.length > 100) {
                                return arg.item.link.substring(0, 100) + "...";
                            } else {
                                return arg.item.link;
                            }
                        },
                        "a@href":"link.link",
                        "span.linkDescription":function(arg) {
                            if (arg.item.title && arg.item.title.length > 150) {
                                return arg.item.title.substring(0, 100) + "...";
                            } else {
                                return arg.item.title;
                            }
                        },
                        "span.linkFrom":function(arg) {
                            var dedup = {};
                            return "From: " + arg.item.encounters.map(function(item) {
                                if(dedup[item.from]) return false;
                                dedup[item.from] = true;
                                var base = (item.network == "twitter") ? "http://twitter.com/#" : "http://facebook.com/";
                                var id = (item.network == "twitter") ? item.via.user.screen_name : item.fromID;
                                return ''+item.from+'';
                            }).clean(false).join(", ") + " - " + getSincePrettified(arg.item.encounters[arg.item.encounters.length - 1].at);
                        },
                        "span.linkFrom@style":function(arg) {
                            return arg.item.encounters[arg.item.encounters.length - 1].from ? "" : "display:none";
                        }
                    }
                }
            }
        }
    });

    $("#searchForm").submit(function() {
        queryLinksCollection($("#linksQuery").val());
        return false;
    });
    findLinksCollection();
    $("#searchLinks").click(function(){
        queryLinksCollection($("#linksQuery").val());
        return false;
    });
});

function hideMe() {
    $(event.srcElement).hide();
}

function getSincePrettified(timestamp) {
    var tip;
    var timeDiff = Date.now() - timestamp;
    if (timeDiff < 60000) {
        tip = 'less than a minute ago';
    } else if (timeDiff < 3600000) {
        var min = Math.floor(timeDiff / 60000);
        tip =  min + ' minute' + (min > 1?'s':'') + ' ago';
    } else if (timeDiff < 43800000) {
        var hour = Math.floor(timeDiff / 3600000);
        tip =  hour + ' hour' + (hour > 1?'s':'') + ' ago';
    } else {
        var d = new Date();
        d.setTime(timestamp);
        tip = d.toString();
    }
    return tip;
}
<|endoftext|>


<commit_before>'use strict'
var test = require('tape')
var fresh = require('fresh-require')
var pino = require('../browser')

levelTest('fatal')
levelTest('error')
levelTest('warn')
levelTest('info')
levelTest('debug')
levelTest('trace')

test('throw if creating child without bindings', function (t) {
  t.plan(1)

  var instance = pino()

  t.throws(function () {
    instance.child()
  })
})

test('stubs write, flush and ee methods on instance', function (t) {
  var instance = pino()

  t.ok(isFunc(instance.setMaxListeners))
  t.ok(isFunc(instance.getMaxListeners))
  t.ok(isFunc(instance.emit))
  t.ok(isFunc(instance.addListener))
  t.ok(isFunc(instance.on))
  t.ok(isFunc(instance.prependListener))
  t.ok(isFunc(instance.once))
  t.ok(isFunc(instance.prependOnceListener))
  t.ok(isFunc(instance.removeListener))
  t.ok(isFunc(instance.removeAllListeners))
  t.ok(isFunc(instance.listeners))
  t.ok(isFunc(instance.listenerCount))
  t.ok(isFunc(instance.eventNames))
  t.ok(isFunc(instance.write))
  t.ok(isFunc(instance.flush))

  t.is(instance.on(), undefined)

  t.end()
})

test('exposes levels object', function (t) {
  t.deepEqual(pino.levels, {
    values: {
      fatal: 60,
      error: 50,
      warn: 40,
      info: 30,
      debug: 20,
      trace: 10
    },
    labels: {
      '10': 'trace',
      '20': 'debug',
      '30': 'info',
      '40': 'warn',
      '50': 'error',
      '60': 'fatal'
    }
  })
  t.end()
})

test('exposes LOG_VERSION', function (t) {
  t.is(pino.LOG_VERSION, 1)
  t.end()
})

test('exposes faux stdSerializers', function (t) {
  t.ok(pino.stdSerializers)
  t.ok(pino.stdSerializers.req)
  t.ok(pino.stdSerializers.res)
  t.ok(pino.stdSerializers.err)
  t.deepEqual(pino.stdSerializers.req(), {})
  t.deepEqual(pino.stdSerializers.res(), {})
  t.deepEqual(pino.stdSerializers.err(), {})
  t.end()
})

consoleMethodTest('error')
consoleMethodTest('fatal', 'error')
consoleMethodTest('warn')
consoleMethodTest('info')
consoleMethodTest('debug')
consoleMethodTest('trace')
absentConsoleMethodTest('error', 'log')
absentConsoleMethodTest('warn', 'error')
absentConsoleMethodTest('info', 'log')
absentConsoleMethodTest('debug', 'log')
absentConsoleMethodTest('trace', 'log')

test('in absence of console, log methods become noops', function (t) {
  var console = global.console
  delete global.console
  var instance = fresh('../browser', require)()
  global.console = console
  t.is(fnName(instance.log), 'noop')
  t.is(fnName(instance.fatal), 'noop')
  t.is(fnName(instance.error), 'noop')
  t.is(fnName(instance.warn), 'noop')
  t.is(fnName(instance.info), 'noop')
  t.is(fnName(instance.debug), 'noop')
  t.is(fnName(instance.trace), 'noop')
  t.end()
})

test('opts.browser.asObject logs pino-like object to console', function (t) {
  t.plan(3)
  var info = console.info
  console.info = function (o) {
    t.is(o.level, 30)
    t.is(o.msg, 'test')
    t.ok(o.time)
    console.info = info
  }
  var instance = require('../browser')({
    browser: {
      asObject: true
    }
  })

  instance.info('test')
})

test('opts.browser.write func log single string', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 'test')
        t.ok(o.time)
      }
    }
  })
  instance.info('test')
  t.end()
})

test('opts.browser.write func string joining', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 'test test2 test3')
        t.ok(o.time)
      }
    }
  })
  instance.info('test', 'test2', 'test3')
  t.end()
})

test('opts.browser.write func string object joining', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 'test {"test":"test2"} {"test":"test3"}')
        t.ok(o.time)
      }
    }
  })
  instance.info('test', {test: 'test2'}, {test: 'test3'})
  t.end()
})

test('opts.browser.write func string interpolation', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 'test2 test ({\\"test\\":\\"test3\\"})')
        t.ok(o.time)
      }
    }
  })
  instance.info('%s test (%j)', 'test2', {test: 'test3'})
  t.end()
})

test('opts.browser.write func number', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 1)
        t.ok(o.time)
      }
    }
  })
  instance.info(1)
  t.end()
})

test('opts.browser.write func log single object', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.test, 'test')
        t.ok(o.time)
      }
    }
  })
  instance.info({test: 'test'})
  t.end()
})

test('opts.browser.write obj writes to methods corresponding to level', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: {
        error: function (o) {
          t.is(o.level, 50)
          t.is(o.test, 'test')
          t.ok(o.time)
        }
      }
    }
  })
  instance.error({test: 'test'})
  t.end()
})

test('opts.browser.asObject/write supports child loggers', function (t) {
  var instance = pino({
    browser: {write: function (o) {
      t.is(o.level, 30)
      t.is(o.test, 'test')
      t.is(o.msg, 'msg-test')
      t.ok(o.time)
    }}
  })
  var child = instance.child({test: 'test'})
  child.info('msg-test')
  t.end()
})

test('opts.browser.asObject/write supports child child loggers', function (t) {
  var instance = pino({
    browser: {write: function (o) {
      t.is(o.level, 30)
      t.is(o.test, 'test')
      t.is(o.foo, 'bar')
      t.is(o.msg, 'msg-test')
      t.ok(o.time)
    }}
  })
  var child = instance.child({test: 'test'}).child({foo: 'bar'})
  child.info('msg-test')
  t.end()
})

test('opts.browser.asObject/write supports child child child loggers', function (t) {
  var instance = pino({
    browser: {write: function (o) {
      t.is(o.level, 30)
      t.is(o.test, 'test')
      t.is(o.foo, 'bar')
      t.is(o.baz, 'bop')
      t.is(o.msg, 'msg-test')
      t.ok(o.time)
    }}
  })
  var child = instance.child({test: 'test'}).child({foo: 'bar'}).child({baz: 'bop'})
  child.info('msg-test')
  t.end()
})

test('opts.browser.asObject defensively mitigates naughty numbers', function (t) {
  var instance = pino({
    browser: {asObject: true}
  })
  var child = instance.child({test: 'test'})
  child._childLevel = -10
  child.info('test')
  t.pass() // if we reached here, there was no infinite loop, so, .. pass.
  t.end()
})

test('opts.browser.write obj falls back to console where a method is not supplied', function (t) {
  t.plan(6)
  var info = console.info
  console.info = function (o) {
    t.is(o.level, 30)
    t.is(o.msg, 'test')
    t.ok(o.time)
    console.info = info
  }
  var instance = require('../browser')({
    browser: {
      write: {
        error: function (o) {
          t.is(o.level, 50)
          t.is(o.test, 'test')
          t.ok(o.time)
        }
      }
    }
  })
  instance.error({test: 'test'})
  instance.info('test')
  t.end()
})

function levelTest (name) {
  test(name + ' logs', function (t) {
    var msg = 'hello world'
    sink(name, function (args) {
      t.is(args[0], msg)
      t.end()
    })
    pino({level: name})[name](msg)
  })

  test('passing objects at level ' + name, function (t) {
    var msg = { hello: 'world' }
    sink(name, function (args) {
      t.is(args[0], msg)
      t.end()
    })
    pino({level: name})[name](msg)
  })

  test('passing an object and a string at level ' + name, function (t) {
    var a = { hello: 'world' }
    var b = 'a string'
    sink(name, function (args) {
      t.is(args[0], a)
      t.is(args[1], b)
      t.end()
    })
    pino({level: name})[name](a, b)
  })

  test('formatting logs as ' + name, function (t) {
    sink(name, function (args) {
      t.is(args[0], 'hello %d')
      t.is(args[1], 42)
      t.end()
    })
    pino({level: name})[name]('hello %d', 42)
  })

  test('passing error at level ' + name, function (t) {
    var err = new Error('myerror')
    sink(name, function (args) {
      t.is(args[0], err)
      t.end()
    })
    pino({level: name})[name](err)
  })

  test('passing error with a serializer at level ' + name, function (t) {
    // in browser - should have no effect (should not crash)
    var err = new Error('myerror')
    sink(name, function (args) {
      t.is(args[0].err, err)
      t.end()
    })
    var instance = pino({
      level: name,
      serializers: {
        err: pino.stdSerializers.err
      }
    })
    instance[name]({err: err})
  })

  test('child logger for level ' + name, function (t) {
    var msg = 'hello world'
    var parent = { hello: 'world' }
    sink(name, function (args) {
      t.is(args[0], parent)
      t.is(args[1], msg)
      t.end()
    })
    var instance = pino({level: name})
    var child = instance.child(parent)
    child[name](msg)
  })

  test('child-child logger for level ' + name, function (t) {
    var msg = 'hello world'
    var grandParent = { hello: 'world' }
    var parent = { hello: 'you' }
    sink(name, function (args) {
      t.is(args[0], grandParent)
      t.is(args[1], parent)
      t.is(args[2], msg)
      t.end()
    })
    var instance = pino({level: name})
    var child = instance.child(grandParent).child(parent)
    child[name](msg)
  })
}

function consoleMethodTest (level, method) {
  if (!method) method = level
  test('pino().' + level + ' uses console.' + method, function (t) {
    sink(method, function (args) {
      t.is(args[0], 'test')
      t.end()
    })
    var instance = require('../browser')({level: level})
    instance[level]('test')
  })
}

function absentConsoleMethodTest (method, fallback) {
  test('in absence of console.' + method + ', console.' + fallback + ' is used', function (t) {
    var fn = console[method]
    console[method] = undefined
    sink(fallback, function (args) {
      t.is(args[0], 'test')
      t.end()
      console[method] = fn
    })
    var instance = require('../browser')({level: method})
    instance[method]('test')
  })
}

function isFunc (fn) { return typeof fn === 'function' }
function fnName (fn) {
  var rx = /^\s*function\s*([^(]*)/i
  var match = rx.exec(fn)
  return match && match[1]
}
function sink (method, fn) {
  if (method === 'fatal') method = 'error'
  var orig = console[method]
  console[method] = function () {
    console[method] = orig
    fn(Array.prototype.slice.call(arguments))
  }
}
<commit_msg>Avoid writing to stdout in browser test<commit_after>'use strict'
var test = require('tape')
var fresh = require('fresh-require')
var pino = require('../browser')

levelTest('fatal')
levelTest('error')
levelTest('warn')
levelTest('info')
levelTest('debug')
levelTest('trace')

test('throw if creating child without bindings', function (t) {
  t.plan(1)

  var instance = pino()

  t.throws(function () {
    instance.child()
  })
})

test('stubs write, flush and ee methods on instance', function (t) {
  var instance = pino()

  t.ok(isFunc(instance.setMaxListeners))
  t.ok(isFunc(instance.getMaxListeners))
  t.ok(isFunc(instance.emit))
  t.ok(isFunc(instance.addListener))
  t.ok(isFunc(instance.on))
  t.ok(isFunc(instance.prependListener))
  t.ok(isFunc(instance.once))
  t.ok(isFunc(instance.prependOnceListener))
  t.ok(isFunc(instance.removeListener))
  t.ok(isFunc(instance.removeAllListeners))
  t.ok(isFunc(instance.listeners))
  t.ok(isFunc(instance.listenerCount))
  t.ok(isFunc(instance.eventNames))
  t.ok(isFunc(instance.write))
  t.ok(isFunc(instance.flush))

  t.is(instance.on(), undefined)

  t.end()
})

test('exposes levels object', function (t) {
  t.deepEqual(pino.levels, {
    values: {
      fatal: 60,
      error: 50,
      warn: 40,
      info: 30,
      debug: 20,
      trace: 10
    },
    labels: {
      '10': 'trace',
      '20': 'debug',
      '30': 'info',
      '40': 'warn',
      '50': 'error',
      '60': 'fatal'
    }
  })
  t.end()
})

test('exposes LOG_VERSION', function (t) {
  t.is(pino.LOG_VERSION, 1)
  t.end()
})

test('exposes faux stdSerializers', function (t) {
  t.ok(pino.stdSerializers)
  t.ok(pino.stdSerializers.req)
  t.ok(pino.stdSerializers.res)
  t.ok(pino.stdSerializers.err)
  t.deepEqual(pino.stdSerializers.req(), {})
  t.deepEqual(pino.stdSerializers.res(), {})
  t.deepEqual(pino.stdSerializers.err(), {})
  t.end()
})

consoleMethodTest('error')
consoleMethodTest('fatal', 'error')
consoleMethodTest('warn')
consoleMethodTest('info')
consoleMethodTest('debug')
consoleMethodTest('trace')
absentConsoleMethodTest('error', 'log')
absentConsoleMethodTest('warn', 'error')
absentConsoleMethodTest('info', 'log')
absentConsoleMethodTest('debug', 'log')
absentConsoleMethodTest('trace', 'log')

test('in absence of console, log methods become noops', function (t) {
  var console = global.console
  delete global.console
  var instance = fresh('../browser', require)()
  global.console = console
  t.is(fnName(instance.log), 'noop')
  t.is(fnName(instance.fatal), 'noop')
  t.is(fnName(instance.error), 'noop')
  t.is(fnName(instance.warn), 'noop')
  t.is(fnName(instance.info), 'noop')
  t.is(fnName(instance.debug), 'noop')
  t.is(fnName(instance.trace), 'noop')
  t.end()
})

test('opts.browser.asObject logs pino-like object to console', function (t) {
  t.plan(3)
  var info = console.info
  console.info = function (o) {
    t.is(o.level, 30)
    t.is(o.msg, 'test')
    t.ok(o.time)
    console.info = info
  }
  var instance = require('../browser')({
    browser: {
      asObject: true
    }
  })

  instance.info('test')
})

test('opts.browser.write func log single string', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 'test')
        t.ok(o.time)
      }
    }
  })
  instance.info('test')
  t.end()
})

test('opts.browser.write func string joining', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 'test test2 test3')
        t.ok(o.time)
      }
    }
  })
  instance.info('test', 'test2', 'test3')
  t.end()
})

test('opts.browser.write func string object joining', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 'test {"test":"test2"} {"test":"test3"}')
        t.ok(o.time)
      }
    }
  })
  instance.info('test', {test: 'test2'}, {test: 'test3'})
  t.end()
})

test('opts.browser.write func string interpolation', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 'test2 test ({\\"test\\":\\"test3\\"})')
        t.ok(o.time)
      }
    }
  })
  instance.info('%s test (%j)', 'test2', {test: 'test3'})
  t.end()
})

test('opts.browser.write func number', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.msg, 1)
        t.ok(o.time)
      }
    }
  })
  instance.info(1)
  t.end()
})

test('opts.browser.write func log single object', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: function (o) {
        t.is(o.level, 30)
        t.is(o.test, 'test')
        t.ok(o.time)
      }
    }
  })
  instance.info({test: 'test'})
  t.end()
})

test('opts.browser.write obj writes to methods corresponding to level', function (t) {
  t.plan(3)
  var instance = pino({
    browser: {
      write: {
        error: function (o) {
          t.is(o.level, 50)
          t.is(o.test, 'test')
          t.ok(o.time)
        }
      }
    }
  })
  instance.error({test: 'test'})
  t.end()
})

test('opts.browser.asObject/write supports child loggers', function (t) {
  var instance = pino({
    browser: {write: function (o) {
      t.is(o.level, 30)
      t.is(o.test, 'test')
      t.is(o.msg, 'msg-test')
      t.ok(o.time)
    }}
  })
  var child = instance.child({test: 'test'})
  child.info('msg-test')
  t.end()
})

test('opts.browser.asObject/write supports child child loggers', function (t) {
  var instance = pino({
    browser: {write: function (o) {
      t.is(o.level, 30)
      t.is(o.test, 'test')
      t.is(o.foo, 'bar')
      t.is(o.msg, 'msg-test')
      t.ok(o.time)
    }}
  })
  var child = instance.child({test: 'test'}).child({foo: 'bar'})
  child.info('msg-test')
  t.end()
})

test('opts.browser.asObject/write supports child child child loggers', function (t) {
  var instance = pino({
    browser: {write: function (o) {
      t.is(o.level, 30)
      t.is(o.test, 'test')
      t.is(o.foo, 'bar')
      t.is(o.baz, 'bop')
      t.is(o.msg, 'msg-test')
      t.ok(o.time)
    }}
  })
  var child = instance.child({test: 'test'}).child({foo: 'bar'}).child({baz: 'bop'})
  child.info('msg-test')
  t.end()
})

test('opts.browser.asObject defensively mitigates naughty numbers', function (t) {
  var instance = pino({
    browser: {asObject: true, write: function () {}}
  })
  var child = instance.child({test: 'test'})
  child._childLevel = -10
  child.info('test')
  t.pass() // if we reached here, there was no infinite loop, so, .. pass.
  t.end()
})

test('opts.browser.write obj falls back to console where a method is not supplied', function (t) {
  t.plan(6)
  var info = console.info
  console.info = function (o) {
    t.is(o.level, 30)
    t.is(o.msg, 'test')
    t.ok(o.time)
    console.info = info
  }
  var instance = require('../browser')({
    browser: {
      write: {
        error: function (o) {
          t.is(o.level, 50)
          t.is(o.test, 'test')
          t.ok(o.time)
        }
      }
    }
  })
  instance.error({test: 'test'})
  instance.info('test')
  t.end()
})

function levelTest (name) {
  test(name + ' logs', function (t) {
    var msg = 'hello world'
    sink(name, function (args) {
      t.is(args[0], msg)
      t.end()
    })
    pino({level: name})[name](msg)
  })

  test('passing objects at level ' + name, function (t) {
    var msg = { hello: 'world' }
    sink(name, function (args) {
      t.is(args[0], msg)
      t.end()
    })
    pino({level: name})[name](msg)
  })

  test('passing an object and a string at level ' + name, function (t) {
    var a = { hello: 'world' }
    var b = 'a string'
    sink(name, function (args) {
      t.is(args[0], a)
      t.is(args[1], b)
      t.end()
    })
    pino({level: name})[name](a, b)
  })

  test('formatting logs as ' + name, function (t) {
    sink(name, function (args) {
      t.is(args[0], 'hello %d')
      t.is(args[1], 42)
      t.end()
    })
    pino({level: name})[name]('hello %d', 42)
  })

  test('passing error at level ' + name, function (t) {
    var err = new Error('myerror')
    sink(name, function (args) {
      t.is(args[0], err)
      t.end()
    })
    pino({level: name})[name](err)
  })

  test('passing error with a serializer at level ' + name, function (t) {
    // in browser - should have no effect (should not crash)
    var err = new Error('myerror')
    sink(name, function (args) {
      t.is(args[0].err, err)
      t.end()
    })
    var instance = pino({
      level: name,
      serializers: {
        err: pino.stdSerializers.err
      }
    })
    instance[name]({err: err})
  })

  test('child logger for level ' + name, function (t) {
    var msg = 'hello world'
    var parent = { hello: 'world' }
    sink(name, function (args) {
      t.is(args[0], parent)
      t.is(args[1], msg)
      t.end()
    })
    var instance = pino({level: name})
    var child = instance.child(parent)
    child[name](msg)
  })

  test('child-child logger for level ' + name, function (t) {
    var msg = 'hello world'
    var grandParent = { hello: 'world' }
    var parent = { hello: 'you' }
    sink(name, function (args) {
      t.is(args[0], grandParent)
      t.is(args[1], parent)
      t.is(args[2], msg)
      t.end()
    })
    var instance = pino({level: name})
    var child = instance.child(grandParent).child(parent)
    child[name](msg)
  })
}

function consoleMethodTest (level, method) {
  if (!method) method = level
  test('pino().' + level + ' uses console.' + method, function (t) {
    sink(method, function (args) {
      t.is(args[0], 'test')
      t.end()
    })
    var instance = require('../browser')({level: level})
    instance[level]('test')
  })
}

function absentConsoleMethodTest (method, fallback) {
  test('in absence of console.' + method + ', console.' + fallback + ' is used', function (t) {
    var fn = console[method]
    console[method] = undefined
    sink(fallback, function (args) {
      t.is(args[0], 'test')
      t.end()
      console[method] = fn
    })
    var instance = require('../browser')({level: method})
    instance[method]('test')
  })
}

function isFunc (fn) { return typeof fn === 'function' }
function fnName (fn) {
  var rx = /^\s*function\s*([^(]*)/i
  var match = rx.exec(fn)
  return match && match[1]
}
function sink (method, fn) {
  if (method === 'fatal') method = 'error'
  var orig = console[method]
  console[method] = function () {
    console[method] = orig
    fn(Array.prototype.slice.call(arguments))
  }
}
<|endoftext|>


<commit_before>'use strict';
const ripple = require('ripple-lib');
const connect = require('connect');
const connectRoute = require('connect-route');
const ip = require('request-ip');
//const accesslog = require('./middleware/accesslog');
const RippleCli = require('./ripple-cli');
const assert = require("assert")

const fs = require('fs');
const initialize = (dirname, ctx) => {

    const wallet = JSON.parse(fs.readFileSync(dirname + '/config/wallet.json', 'utf8'));
    ctx.cli = new RippleCli(wallet.address, wallet.secret)
    ctx.cli.connect().then( () => {
        heartbeat(ctx)
    })
}

const heartbeat = (ctx) => {
    ctx.cli.getServerInfo().then(() => {
        setTimeout(() => {
            heartbeat(ctx)
        }, 1000 * 60)
    })
}

const commonerror = e => {
    const fmt = (r) => ({
        success : 0,
        result : {
            message : r.message
        }
    })
    return JSON.stringify(fmt(e));
}

const moment = require('moment')
const accesslog = (req) => console.log(moment().format('YYYY-MM-DD HH:mm:ss'), req.method, req.originalUrl, req.params, req.rawpost)

const healthcheck = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    res.end("OK");
}).catch(e => res.end(commonerror(e) ))

const getbalance = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    return sv.cli.balance().then(r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                balance : r,
            }
        })
        res.end(JSON.stringify(fmt(r.reduce((r,v)=>{
            if(v.currency === "XRP"){
                r[v.currency] = v.value
            }else{
                r[v.currency + ":" + v.counterparty] = v.value
            }
            return r
        }, {XRP:0}))));
    })
}).catch(e => res.end(commonerror(e) ))

const getaddress = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    return sv.cli.address().then(r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                address : r,
            }
        })
        res.end(JSON.stringify(fmt(r)));
    })
}).catch(e => res.end(commonerror(e) ))

const getinfo = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    return sv.cli.getServerInfo().then( r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                validatedLedger: r.validatedLedger,
            }
        })
        res.end(JSON.stringify(fmt(r)));
    })
}).catch(e => res.end(commonerror(e) ))

const gettransaction = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    const params = JSON.parse(req.rawpost)
    assert(params instanceof Object, "params : must be object")

    return sv.cli.transaction(params.txid).then(r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                txid : r.id,
                time : new Date(r.outcome.timestamp) / 1000 | 0,
                ledger : r.outcome.ledgerVersion,
            }
        })
        res.end(JSON.stringify(fmt(r)));
    })
}).catch(e => res.end(commonerror(e) ))

const send = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    const params = JSON.parse(req.rawpost)
    assert(params instanceof Object, "params : must be object")

    return sv.cli.payment(params.address, params.amount, params).then(r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                txid : r.txid,
                fee: (r.Fee * 1e-6).toFixed(6),
                feeDrops: r.Fee,
                amount : (r.Amount * 1e-6).toFixed(6),
                amountDrops : r.Amount,
                raw: r.hex,
            }
        })
        res.end(JSON.stringify(fmt(r)));
    })
}).catch(e => res.end(commonerror(e) ))

const start = exports.start = dirname => {
    const sv = {
        cli : void 0
    };
    initialize(dirname, sv)

    const app = connect();

    app.use((req, res, next) => {
        req.ipaddr = ip.getClientIp(req);
        if(req.method === 'POST'){
            let body = '';
            req.on('data', (data) => {
                body += data;
            });
            req.on('end', () => {
                req.rawpost = body;
                next();
            });
        }else{
            next();
        }
    })

    app.use(connectRoute((router) => {
        router.get('/healthcheck', (req, res, next) => healthcheck(sv, req, res) )
        router.get('/api/getbalance', (req, res, next) => getbalance(sv, req, res) )
        router.post('/api/getbalance', (req, res, next) => getbalance(sv, req, res) )
        router.get('/api/getaddress', (req, res, next) => getaddress(sv, req, res) )
        router.post('/api/getaddress', (req, res, next) => getaddress(sv, req, res) )
        router.get('/api/getinfo', (req, res, next) => getinfo(sv, req, res) )
        router.post('/api/getinfo', (req, res, next) => getinfo(sv, req, res) )

        router.post('/api/gettx', (req, res, next) => gettransaction(sv, req, res) )

        router.post('/api/send', (req, res, next) => send(sv, req, res) )
    }))

    return app;
}

<commit_msg>Update webapp.js<commit_after>'use strict';
const ripple = require('ripple-lib');
const connect = require('connect');
const connectRoute = require('connect-route');
const ip = require('request-ip');
//const accesslog = require('./middleware/accesslog');
const RippleCli = require('./ripple-cli');
const assert = require("assert")

const fs = require('fs');
const initialize = (dirname, ctx) => {

    const wallet = JSON.parse(fs.readFileSync(dirname + '/config/wallet.json', 'utf8'));
    ctx.cli = new RippleCli(wallet.address, wallet.secret)
    ctx.cli.connect().then( () => {
        heartbeat(ctx)
    })
}

const heartbeat = (ctx) => {
    ctx.cli.getServerInfo().then(() => {
        setTimeout(() => {
            heartbeat(ctx)
        }, 1000 * 60)
    }).catch(e => {
        setTimeout(() => {
            heartbeat(ctx)
        }, 1000 * 60)
    })
}

const commonerror = e => {
    const fmt = (r) => ({
        success : 0,
        result : {
            message : r.message
        }
    })
    return JSON.stringify(fmt(e));
}

const moment = require('moment')
const accesslog = (req) => console.log(moment().format('YYYY-MM-DD HH:mm:ss'), req.method, req.originalUrl, req.params, req.rawpost)

const healthcheck = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    res.end("OK");
}).catch(e => res.end(commonerror(e) ))

const getbalance = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    return sv.cli.balance().then(r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                balance : r,
            }
        })
        res.end(JSON.stringify(fmt(r.reduce((r,v)=>{
            if(v.currency === "XRP"){
                r[v.currency] = v.value
            }else{
                r[v.currency + ":" + v.counterparty] = v.value
            }
            return r
        }, {XRP:0}))));
    })
}).catch(e => res.end(commonerror(e) ))

const getfee = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    return sv.cli.getFee().then(r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                fee : r,
            }
        })
        res.end(JSON.stringify(fmt(r)));
    })
}).catch(e => res.end(commonerror(e) ))

const getaddress = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    return sv.cli.address().then(r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                address : r,
            }
        })
        res.end(JSON.stringify(fmt(r)));
    })
}).catch(e => res.end(commonerror(e) ))

const getinfo = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    return sv.cli.getServerInfo().then( r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                validatedLedger: r.validatedLedger,
            }
        })
        res.end(JSON.stringify(fmt(r)));
    })
}).catch(e => res.end(commonerror(e) ))

const gettransaction = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    const params = JSON.parse(req.rawpost)
    assert(params instanceof Object, "params : must be object")

    return sv.cli.transaction(params.txid).then(r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                txid : r.id,
                time : new Date(r.outcome.timestamp) / 1000 | 0,
                ledger : r.outcome.ledgerVersion,
            }
        })
        res.end(JSON.stringify(fmt(r)));
    })
}).catch(e => res.end(commonerror(e) ))

const send = (sv, req, res) => Promise.resolve().then( () => {
    accesslog(req)
    const params = JSON.parse(req.rawpost)
    assert(params instanceof Object, "params : must be object")

    return sv.cli.payment(params.address, params.amount, params).then(r => {
        const fmt = (r) => ({
            success : 1,
            result : {
                txid : r.txid,
                fee: (r.Fee * 1e-6).toFixed(6),
                feeDrops: r.Fee,
                amount : (r.Amount * 1e-6).toFixed(6),
                amountDrops : r.Amount,
                raw: r.hex,
            }
        })
        res.end(JSON.stringify(fmt(r)));
    })
}).catch(e => res.end(commonerror(e) ))

const start = exports.start = dirname => {
    const sv = {
        cli : void 0
    };
    initialize(dirname, sv)

    const app = connect();

    app.use((req, res, next) => {
        req.ipaddr = ip.getClientIp(req);
        if(req.method === 'POST'){
            let body = '';
            req.on('data', (data) => {
                body += data;
            });
            req.on('end', () => {
                req.rawpost = body;
                next();
            });
        }else{
            next();
        }
    })

    app.use(connectRoute((router) => {
        router.get('/healthcheck', (req, res, next) => healthcheck(sv, req, res) )
        router.get('/api/getfee', (req, res, next) => getfee(sv, req, res) )
        router.get('/api/getbalance', (req, res, next) => getbalance(sv, req, res) )
        router.post('/api/getbalance', (req, res, next) => getbalance(sv, req, res) )
        router.get('/api/getaddress', (req, res, next) => getaddress(sv, req, res) )
        router.post('/api/getaddress', (req, res, next) => getaddress(sv, req, res) )
        router.get('/api/getinfo', (req, res, next) => getinfo(sv, req, res) )
        router.post('/api/getinfo', (req, res, next) => getinfo(sv, req, res) )

        router.post('/api/gettx', (req, res, next) => gettransaction(sv, req, res) )

        router.post('/api/send', (req, res, next) => send(sv, req, res) )
    }))

    return app;
}

<|endoftext|>


<commit_before>import { h, render } from '../../src/preact';
/** @jsx h */

describe('keys', () => {
	let scratch;

	before( () => {
		scratch = document.createElement('div');
		(document.body || document.documentElement).appendChild(scratch);
	});

	beforeEach( () => {
		scratch.innerHTML = '';
	});

	after( () => {
		scratch.parentNode.removeChild(scratch);
		scratch = null;
	});

	// See developit/preact-compat#21
	it('should remove orphaned keyed nodes', () => {
		let root = render((

1

a

		), scratch);

		root = render((

2

b

		), scratch, root);

		expect(scratch.innerHTML).to.equal('

2

b

');
	});

	it('should set VNode#key property', () => {
		expect(
).to.have.property('key').that.is.empty;
		expect(
).to.have.property('key').that.is.empty;
		expect(
).to.have.property('key', '1');
	});
});
<commit_msg>Add test for #232<commit_after>import { h, Component, render } from '../../src/preact';
/** @jsx h */

describe('keys', () => {
	let scratch;

	before( () => {
		scratch = document.createElement('div');
		(document.body || document.documentElement).appendChild(scratch);
	});

	beforeEach( () => {
		scratch.innerHTML = '';
	});

	after( () => {
		scratch.parentNode.removeChild(scratch);
		scratch = null;
	});

	// See developit/preact-compat#21
	it('should remove orphaned keyed nodes', () => {
		let root = render((

1

a

		), scratch);

		root = render((

2

b

		), scratch, root);

		expect(scratch.innerHTML).to.equal('

2

b

');
	});

	it('should set VNode#key property', () => {
		expect(
).to.have.property('key').that.is.empty;
		expect(
).to.have.property('key').that.is.empty;
		expect(
).to.have.property('key', '1');
	});

	it('should remove keyed nodes (#232)', () => {
		class App extends Component {
			componentDidMount() {
				setTimeout(() => this.setState({opened: true,loading: true}), 10);
				setTimeout(() => this.setState({opened: true,loading: false}), 20);
			}

			render({ opened, loading }) {
				return (
					<BusyIndicator id="app" busy={loading}>

This div needs to be here for this to break

						{ opened && !loading &&
{[]}
 }
					</BusyIndicator>
				);
			}
		}

		class BusyIndicator extends Component {
			render({ children, busy }) {
				return

					{ children && children.length ? children :

 }

indicator

indicator

indicator

;
			}
		}

		let root;

		root = render(<App />, scratch, root);
		root = render(<App opened loading />, scratch, root);
		root = render(<App opened />, scratch, root);

		expect(root).to.have.property('innerHTML', '
This div needs to be here for this to break

indicator

indicator

indicator

');
	});
});
<|endoftext|>


<commit_before>'use strict';

var grunt = require('grunt');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

function assertFileEquality(test, pathToActual, pathToExpected, message) {
  var actual = grunt.file.read(pathToActual);
  var expected = grunt.file.read(pathToExpected);
  test.equal(expected, actual, message);
}

exports.builder = {
  default_build: {
    patch: function(test) {
      test.expect(4);

      assertFileEquality(test, 'tmp/patch/VERSION', 'test/expected/patch/VERSION', 'patch update to the VERSION FILE');
      assertFileEquality(test, 'tmp/patch/package.json', 'test/expected/patch/package.json', 'patch update to the package.json FILE');
      assertFileEquality(test, 'tmp/patch/bower.json', 'test/expected/patch/bower.json', 'patch update to the bower.json FILE');
      assertFileEquality(test, 'tmp/patch/README.md', 'test/expected/patch/README.md', 'patch update to the README.md FILE');

      test.done();
    },
    minor: function(test) {
      test.expect(4);

      assertFileEquality(test, 'tmp/minor/VERSION', 'test/expected/minor/VERSION', 'minor update to the VERSION FILE');
      assertFileEquality(test, 'tmp/minor/package.json', 'test/expected/minor/package.json', 'minor update to the package.json FILE');
      assertFileEquality(test, 'tmp/minor/bower.json', 'test/expected/minor/bower.json', 'minor update to the bower.json FILE');
      assertFileEquality(test, 'tmp/minor/README.md', 'test/expected/minor/README.md', 'minor update to the README.md FILE');

      test.done();
    },
    major: function(test) {
      test.expect(4);

      assertFileEquality(test, 'tmp/major/VERSION', 'test/expected/major/VERSION', 'major update to the VERSION FILE');
      assertFileEquality(test, 'tmp/major/package.json', 'test/expected/major/package.json', 'major update to the package.json FILE');
      assertFileEquality(test, 'tmp/major/bower.json', 'test/expected/major/bower.json', 'major update to the bower.json FILE');
      assertFileEquality(test, 'tmp/major/README.md', 'test/expected/major/README.md', 'major update to the README.md FILE');

      test.done();
    }
  }
};
<commit_msg>reformatted test error message<commit_after>'use strict';

var grunt = require('grunt');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

function assertFileEquality(test, pathToActual, pathToExpected, message) {
  var actual = grunt.file.read(pathToActual);
  var expected = grunt.file.read(pathToExpected);
  test.equal(expected, actual, message);
}

exports.builder = {
  default_build: {
    patch: function(test) {
      test.expect(4);

      assertFileEquality(test, 'tmp/patch/VERSION', 'test/expected/patch/VERSION', 'patch update to the VERSION file');
      assertFileEquality(test, 'tmp/patch/package.json', 'test/expected/patch/package.json', 'patch update to the package.json file');
      assertFileEquality(test, 'tmp/patch/bower.json', 'test/expected/patch/bower.json', 'patch update to the bower.json file');
      assertFileEquality(test, 'tmp/patch/README.md', 'test/expected/patch/README.md', 'patch update to the README.md file');

      test.done();
    },
    minor: function(test) {
      test.expect(4);

      assertFileEquality(test, 'tmp/minor/VERSION', 'test/expected/minor/VERSION', 'minor update to the VERSION file');
      assertFileEquality(test, 'tmp/minor/package.json', 'test/expected/minor/package.json', 'minor update to the package.json file');
      assertFileEquality(test, 'tmp/minor/bower.json', 'test/expected/minor/bower.json', 'minor update to the bower.json file');
      assertFileEquality(test, 'tmp/minor/README.md', 'test/expected/minor/README.md', 'minor update to the README.md file');

      test.done();
    },
    major: function(test) {
      test.expect(4);

      assertFileEquality(test, 'tmp/major/VERSION', 'test/expected/major/VERSION', 'major update to the VERSION file');
      assertFileEquality(test, 'tmp/major/package.json', 'test/expected/major/package.json', 'major update to the package.json file');
      assertFileEquality(test, 'tmp/major/bower.json', 'test/expected/major/bower.json', 'major update to the bower.json file');
      assertFileEquality(test, 'tmp/major/README.md', 'test/expected/major/README.md', 'major update to the README.md file');

      test.done();
    }
  }
};
<|endoftext|>


<commit_before>const appendEnvIfNotProduction = (name) => {
  let suffix = "-development"

  if(typeof process.env === "object") {
    if(typeof process.env.NODE_ENV === "string") {
      if(process.env.NODE_ENV.trim() !== "") {
        suffix = ("-"+process.env.NODE_ENV.trim().toLowerCase()).replace("-production", "")
      }
    }
  }

  return name+suffix;
}

module.exports = {
    "apps": [
        {
            "name": appendEnvIfNotProduction("feeds"),
            "script": "server.js",
            "instances": 3,
            "env_preprod": {
                "NODE_ENV": "preprod"
            },
            "env_production": {
                "NODE_ENV": "production"
            }
        }
    ],
    "deploy": {
        "production" : {
          "user": "podcloud",
          "host": "eve.podradio.fr",
          "ref": "origin/master",
          "repo": "git@github.com:PodShows/podcloud-feeds.git",
          "path": "/home/podcloud/production/feeds",
          "pre-deploy-local": "ssh-keyscan eve.podradio.fr >> ~/.ssh/known_hosts",
          "post-deploy": "npm install && pm2 startOrReload ecosystem.config.js --env production",
          "env": {
            "NODE_ENV": "production"
          }
        },
        "preprod" : {
          "user": "podcloud",
          "host": "eve.podradio.fr",
          "ref": "origin/develop",
          "repo": "git@github.com:PodShows/podcloud-feeds.git",
          "path": "/home/podcloud/preprod/feeds",
          "pre-deploy-local": "ssh-keyscan eve.podradio.fr >> ~/.ssh/known_hosts",
          "post-deploy": "npm install && pm2 startOrReload ecosystem.config.js --env preprod",
          "env": {
            "NODE_ENV": "preprod"
          }
        }
    }
};
<commit_msg>deployment fix<commit_after>const appendEnvIfNotProduction = (name) => {
  let suffix = "-development"

  if(typeof process.env === "object") {
    if(typeof process.env.NODE_ENV === "string") {
      if(process.env.NODE_ENV.trim() !== "") {
        suffix = ("-"+process.env.NODE_ENV.trim().toLowerCase()).replace("-production", "")
      }
    }
  }

  return name+suffix;
}

module.exports = {
    "apps": [
        {
            "name": appendEnvIfNotProduction("feeds"),
            "script": "server.js",
            "instances": 3,
            "env_preprod": {
                "NODE_ENV": "preprod"
            },
            "env_production": {
                "NODE_ENV": "production"
            }
        }
    ],
    "deploy": {
        "production" : {
          "user": "podcloud",
          "host": "eve.podradio.fr",
          "ref": "origin/master",
          "repo": "git@github.com:PodShows/podcloud-feeds.git",
          "path": "/home/podcloud/production/feeds",
          "pre-deploy-local": "ssh-keyscan eve.podradio.fr >> ~/.ssh/known_hosts",
          "post-deploy": "npm install && NODE_ENV=production pm2 startOrReload ecosystem.config.js --env production",
          "env": {
            "NODE_ENV": "production"
          }
        },
        "preprod" : {
          "user": "podcloud",
          "host": "eve.podradio.fr",
          "ref": "origin/develop",
          "repo": "git@github.com:PodShows/podcloud-feeds.git",
          "path": "/home/podcloud/preprod/feeds",
          "pre-deploy-local": "ssh-keyscan eve.podradio.fr >> ~/.ssh/known_hosts",
          "post-deploy": "npm install && NODE_ENV=preprod pm2 startOrReload ecosystem.config.js --env preprod",
          "env": {
            "NODE_ENV": "preprod"
          }
        }
    }
};
<|endoftext|>