<commit_before>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2.view',
  name: 'RichChoiceView',
  extends: 'foam.u2.View',

  documentation: `
    This is similar to foam.u2.view.ChoiceView, but lets you provide views for
    the button content and options instead of strings. This allows you to create
    dropdowns with rich content like images and formatting using CSS.

    Example usage for a Reference property on a model:

      {
        class: 'Reference',
        of: 'foam.nanos.auth.User',
        name: 'exampleProperty',
        view: function(_, X) {
          return {
            class: 'foam.u2.view.RichChoiceView',
            buttonContentView: { class: 'a.b.c.MyCustomButtonView' }, // Optional
            rowView: { class: 'a.b.c.MyCustomCitationView' }, // Optional
            sections: [
              {
                heading: 'Users',
                dao: X.userDAO.orderBy(foam.nanos.auth.User.LEGAL_NAME)
              }
            ]
          };
        }
      }
  `,

  exports: [
    'of'
  ],

  css: `
    ^container {
      background: white;
      border: 1px solid #bdbdbd;
      border-radius: 4px;
      max-width: 488px;
      max-height: 378px;
      overflow-y: scroll;
      box-sizing: border-box;
    }

    ^heading {
      font-weight: bold;
      border-bottom: 1px solid #f4f4f9;
      line-height: 24px;
      font-size: 14px;
      color: #333;
      font-weight: 900;
      padding: 6px 16px;
    }

    ^button {
      height: 36px;
      width: 488px;
      border-radius: 4px;
      border: solid 1px #bdbdbd;
      background-color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 8px;
      font-size: 12px;
      box-sizing: border-box;
      margin-bottom: 4px;
    }

    ^chevron::before {
      content: '▾';
      color: #bdbdbd;
      font-size: 17px;
      padding-left: 8px;
    }

    ^custom-button {
      flex-grow: 1;
    }
  `,

  properties: [
    {
      class: 'foam.u2.ViewSpec',
      name: 'rowView',
      documentation: `
        Set this to override the default view used for each row. It will be
        instantiated with an object from the DAO as the 'data' property.
      `,
      value: { class: 'foam.u2.CitationView' },
    },
    {
      name: 'data',
      documentation: `
        The value that gets chosen. This is set whenever a user makes a choice.
      `
    },
    {
      class: 'Boolean',
      name: 'isOpen_',
      documentation: `
        An internal property used to determine whether the options list is
        visible or not.
      `
    },
    {
      class: 'foam.u2.ViewSpec',
      name: 'buttonContentView',
      documentation: `
        Set this to override the default view used for the button content. It
        will be instantiated with an object from the DAO as the 'fullObject'
        property and that object's id as the 'data' property.
      `,
      factory: function() {
        return this.DefaultButtonContentView;
      }
    },
    {
      class: 'Array',
      name: 'sections',
      documentation: `
        This lets you pass different predicated versions of a dao in different
        sections, which can be used to do things like grouping by some property
        for each section.
        Each object in the array must have a 'label' property of type string
        which will be used for the section heading, and a 'dao' property of type
        DAO that will be used to populate the list in that section.
      `,
    },
    {
      class: 'FObjectProperty',
      name: 'of',
      documentation: 'The model stored in the DAO. Used intenrally.',
      expression: function(sections) {
        return sections[0].dao.of;
      }
    },
    {
      class: 'FObjectProperty',
      name: 'fullObject_',
      documentation: `
        The full object from the DAO. This property is only used internally, you
        do not need to set it as a consumer of this view.
      `
    }
  ],

  methods: [
    function initE() {
      var self = this;

      if ( ! Array.isArray(this.sections) || this.sections.length === 0 ) {
        throw new Error(`You must provide an array of sections. See documentation on the 'sections' property in RichTextView.js.`);
      }

      // If the property that this view is for already has a value when being
      // rendered, the 'data' property on this model will be set to an id for
      // the object being referenced by the Reference property being rendered.
      // Custom views might need the full object to render though, not just the
      // id, so we do a lookup at the beginning of initE for the full object and
      // set it here when found. This then gets passed to the button view to use
      // it if it wants to.
      if ( this.data ) {
        this.sections[0].dao.find(this.data).then((result) => {
          this.fullObject_ = result;
        });
      }

      this
        .addClass(this.myClass())
        .start()
          .addClass(this.myClass('button'))
          .on('click', function() {
            self.isOpen_ = ! self.isOpen_;
          })
          .start()
            .addClass(this.myClass('custom-button'))
            .add(this.slot((data) => {
              return this.E().tag(self.buttonContentView, {
                data: data,
                fullObject$: this.fullObject_$
              });
            }))
          .end()
          .start()
            .addClass(this.myClass('chevron'))
          .end()
        .end()
        .start()
          .addClass(this.myClass('container'))
          .show(self.isOpen_$)
          .forEach(this.sections, function(section) {
            var dao = section.dao;
            this
              .start()
                .addClass(self.myClass('heading'))
                .add(section.heading)
              .end()
              .start()
                .select(dao, function(obj) {
                  return this.E()
                    .start(self.rowView, { data: obj })
                      .on('click', () => {
                        self.fullObject_ = obj;
                        self.data = obj;
                        self.isOpen_ = false;
                      })
                    .end();
                })
              .end();
          })
        .end();
    }
  ],

  classes: [
    {
      name: 'DefaultButtonContentView',
      extends: 'foam.u2.Element',

      documentation: `
        This is the view that gets rendered inside the button. It is put to the
        left of the chevron (the triangle at the far right side of the button).
        This is an Element instead of a simple string, meaning the button can
        contain "rich" content like images and make use of CSS for styling and
        layout.
        As an example of why this is useful, imagine you wanted to show a
        dropdown to select a country. You could choose to display the flag of
        the selected country alongside its name after the user makes a
        selection by creating that custom view and providing it in place of this
        one by setting the buttonContentView property on RichChoiceView.
      `,

      imports: [
        'of'
      ],

      messages: [
        {
          name: 'CHOOSE_FROM',
          message: 'Choose from '
        }
      ],

      properties: [
        {
          name: 'data',
          documentation: 'The id of the selected object.'
        },
        {
          name: 'fullObject',
          documentation: `
            The full object. It's not used here in the default button view, but
            this property is included to let you know that if you create a
            custom button content view, it will be passed the id of the object
            (data) as well as the full object.
          `
        }
      ],

      methods: [
        function initE() {
          var plural = this.of.model_.plural.toLowerCase();
          return this.add(this.data || this.CHOOSE_FROM + plural);
        }
      ]
    }
  ]
});
<commit_msg>Add default row view<commit_after>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2.view',
  name: 'RichChoiceView',
  extends: 'foam.u2.View',

  documentation: `
    This is similar to foam.u2.view.ChoiceView, but lets you provide views for
    the button content and options instead of strings. This allows you to create
    dropdowns with rich content like images and formatting using CSS.

    Example usage for a Reference property on a model:

      {
        class: 'Reference',
        of: 'foam.nanos.auth.User',
        name: 'exampleProperty',
        view: function(_, X) {
          return {
            class: 'foam.u2.view.RichChoiceView',
            buttonContentView: { class: 'a.b.c.MyCustomButtonView' }, // Optional
            rowView: { class: 'a.b.c.MyCustomCitationView' }, // Optional
            sections: [
              {
                heading: 'Users',
                dao: X.userDAO.orderBy(foam.nanos.auth.User.LEGAL_NAME)
              }
            ]
          };
        }
      }
  `,

  exports: [
    'of'
  ],

  css: `
    ^container {
      background: white;
      border: 1px solid #bdbdbd;
      border-radius: 4px;
      max-width: 488px;
      max-height: 378px;
      overflow-y: scroll;
      box-sizing: border-box;
    }

    ^heading {
      font-weight: bold;
      border-bottom: 1px solid #f4f4f9;
      line-height: 24px;
      font-size: 14px;
      color: #333;
      font-weight: 900;
      padding: 6px 16px;
    }

    ^button {
      height: 36px;
      width: 488px;
      border-radius: 4px;
      border: solid 1px #bdbdbd;
      background-color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 8px;
      font-size: 12px;
      box-sizing: border-box;
      margin-bottom: 4px;
    }

    ^chevron::before {
      content: '▾';
      color: #bdbdbd;
      font-size: 17px;
      padding-left: 8px;
    }

    ^custom-button {
      flex-grow: 1;
    }
  `,

  properties: [
    {
      class: 'foam.u2.ViewSpec',
      name: 'rowView',
      documentation: `
        Set this to override the default view used for each row. It will be
        instantiated with an object from the DAO as the 'data' property.
      `,
      factory: function() {
        return this.DefaultRowView;
      }
    },
    {
      name: 'data',
      documentation: `
        The value that gets chosen. This is set whenever a user makes a choice.
      `
    },
    {
      class: 'Boolean',
      name: 'isOpen_',
      documentation: `
        An internal property used to determine whether the options list is
        visible or not.
      `
    },
    {
      class: 'foam.u2.ViewSpec',
      name: 'buttonContentView',
      documentation: `
        Set this to override the default view used for the button content. It
        will be instantiated with an object from the DAO as the 'fullObject'
        property and that object's id as the 'data' property.
      `,
      factory: function() {
        return this.DefaultButtonContentView;
      }
    },
    {
      class: 'Array',
      name: 'sections',
      documentation: `
        This lets you pass different predicated versions of a dao in different
        sections, which can be used to do things like grouping by some property
        for each section.
        Each object in the array must have a 'label' property of type string
        which will be used for the section heading, and a 'dao' property of type
        DAO that will be used to populate the list in that section.
      `,
    },
    {
      class: 'FObjectProperty',
      name: 'of',
      documentation: 'The model stored in the DAO. Used intenrally.',
      expression: function(sections) {
        return sections[0].dao.of;
      }
    },
    {
      class: 'FObjectProperty',
      name: 'fullObject_',
      documentation: `
        The full object from the DAO. This property is only used internally, you
        do not need to set it as a consumer of this view.
      `
    }
  ],

  methods: [
    function initE() {
      var self = this;

      if ( ! Array.isArray(this.sections) || this.sections.length === 0 ) {
        throw new Error(`You must provide an array of sections. See documentation on the 'sections' property in RichTextView.js.`);
      }

      // If the property that this view is for already has a value when being
      // rendered, the 'data' property on this model will be set to an id for
      // the object being referenced by the Reference property being rendered.
      // Custom views might need the full object to render though, not just the
      // id, so we do a lookup at the beginning of initE for the full object and
      // set it here when found. This then gets passed to the button view to use
      // it if it wants to.
      if ( this.data ) {
        this.sections[0].dao.find(this.data).then((result) => {
          this.fullObject_ = result;
        });
      }

      this
        .addClass(this.myClass())
        .start()
          .addClass(this.myClass('button'))
          .on('click', function() {
            self.isOpen_ = ! self.isOpen_;
          })
          .start()
            .addClass(this.myClass('custom-button'))
            .add(this.slot((data) => {
              return this.E().tag(self.buttonContentView, {
                data: data,
                fullObject$: this.fullObject_$
              });
            }))
          .end()
          .start()
            .addClass(this.myClass('chevron'))
          .end()
        .end()
        .start()
          .addClass(this.myClass('container'))
          .show(self.isOpen_$)
          .forEach(this.sections, function(section) {
            var dao = section.dao;
            this
              .start()
                .addClass(self.myClass('heading'))
                .add(section.heading)
              .end()
              .start()
                .select(dao, function(obj) {
                  return this.E()
                    .start(self.rowView, { data: obj })
                      .on('click', () => {
                        self.fullObject_ = obj;
                        self.data = obj;
                        self.isOpen_ = false;
                      })
                    .end();
                })
              .end();
          })
        .end();
    }
  ],

  classes: [
    {
      name: 'DefaultRowView',
      extends: 'foam.u2.View',

      documentation: `
        This is the view that gets rendered for each item in the list.
      `,

      css: `
        ^row {
          background: white;
          padding: 8px 16px;
        }

        ^row:hover {
          background: #f4f4f9;
          cursor: pointer;
        }
      `,

      properties: [
        {
          name: 'data',
          documentation: 'The selected object.'
        }
      ],

      methods: [
        function initE() {
          return this
            .start()
              .addClass(this.myClass('row'))
              .add(this.data.id)
            .end();
        }
      ]
    },
    {
      name: 'DefaultButtonContentView',
      extends: 'foam.u2.Element',

      documentation: `
        This is the view that gets rendered inside the button. It is put to the
        left of the chevron (the triangle at the far right side of the button).
        This is an Element instead of a simple string, meaning the button can
        contain "rich" content like images and make use of CSS for styling and
        layout.
        As an example of why this is useful, imagine you wanted to show a
        dropdown to select a country. You could choose to display the flag of
        the selected country alongside its name after the user makes a
        selection by creating that custom view and providing it in place of this
        one by setting the buttonContentView property on RichChoiceView.
      `,

      imports: [
        'of'
      ],

      messages: [
        {
          name: 'CHOOSE_FROM',
          message: 'Choose from '
        }
      ],

      properties: [
        {
          name: 'data',
          documentation: 'The id of the selected object.'
        },
        {
          name: 'fullObject',
          documentation: `
            The full object. It's not used here in the default button view, but
            this property is included to let you know that if you create a
            custom button content view, it will be passed the id of the object
            (data) as well as the full object.
          `
        }
      ],

      methods: [
        function initE() {
          var plural = this.of.model_.plural.toLowerCase();
          return this.add(this.data || this.CHOOSE_FROM + plural);
        }
      ]
    }
  ]
});
<|endoftext|>


<commit_before>/* global describe, it */
var expect = require('expect.js');

describe('travis.yml', function () {
    var fs = require('fs'),
        yaml = require('js-yaml'),
        travisYAML,
        travisYAMLError;

    try {
        travisYAML = yaml.safeLoad(fs.readFileSync('.travis.yml').toString());
    }
    catch (e) {
        travisYAMLError = e;
    }

    it('should exist', function (done) {
        fs.stat('.travis.yml', done);
    });

    it('should be a valid yml', function () {
        expect(travisYAMLError && travisYAMLError.message || travisYAMLError).to.not.be.ok();
    });

    describe('strucure', function () {
        it('should have the language set to node', function () {
            expect(travisYAML.language).to.be('node_js');
            expect(travisYAML.node_js).to.eql(['6', '5', '4']);
        });

        it('should have a valid Slack notification token', function () {
            expect(travisYAML.notifications.slack.secure).to.be.ok();
        });
    });
});
<commit_msg>Added a system test for the updated Travis CI configuration<commit_after>/* global describe, it */
var expect = require('expect.js');

describe('travis.yml', function () {
    var fs = require('fs'),
        yaml = require('js-yaml'),
        travisYAML,
        travisYAMLError;

    try {
        travisYAML = yaml.safeLoad(fs.readFileSync('.travis.yml').toString());
    }
    catch (e) {
        travisYAMLError = e;
    }

    it('should exist', function (done) {
        fs.stat('.travis.yml', done);
    });

    it('should be a valid yml', function () {
        expect(travisYAMLError && travisYAMLError.message || travisYAMLError).to.not.be.ok();
    });

    describe('strucure', function () {
        it('should use the trusty Ubuntu distribution', function () {
            expect(travisYAML.dist).to.be('trusty');
        });

        it('should have the language set to node', function () {
            expect(travisYAML.language).to.be('node_js');
            expect(travisYAML.node_js).to.eql(['6', '5', '4']);
        });

        it('should use the stable google chrome package', function () {
            expect(travisYAML.addons).to.eql({apt: {packages: ['google-chrome-stable']}});
        });

        it('should have a valid before_install sequence', function () {
            expect(travisYAML.before_install).to.eql([
                'export CHROME_BIN=google-chrome', 'export DISPLAY=:99.0', 'sh -e /etc/init.d/xvfb start', 'sleep 3'
            ]);
        });

        it('should have a valid Slack notification token', function () {
            expect(travisYAML.notifications.slack.secure).to.be.ok();
        });
    });
});
<|endoftext|>


<commit_before>const should = require('should');
const _ = require('lodash');
const jayson = require('./../');
const support = require('./support');
const suites = require('./support/suites');
const net = require('net');
const url = require('url');
const JSONStream = require('JSONStream');

describe('jayson.tcp', function() {

  describe('server', function() {

    let server = null;
    before(function() {
      server = jayson.server(support.server.methods(), support.server.options()).tcp();
    });

    after(function() {
      server.close();
    });

    it('should listen to a local port', function(done) {
      server.listen(3999, 'localhost', function() {
        server.close(done);
      });
    });

    it('should be an instance of net.Server', function() {
      server.should.be.instanceof(net.Server);
    });

    context('connected socket', function() {

      let socket = null;
      let responses = null;

      before(function(done) {
        server.listen(3999, 'localhost', done);
      });

      beforeEach(function(done) {
        socket = net.connect(3999, 'localhost', done);
        responses = JSONStream.parse();
        socket.pipe(responses);
      });

      afterEach(function(done) {
        socket.end();
        done();
      });

      it('should send a parse error for invalid JSON data', function(done) {
        responses.on('data', function(data) {
          data.should.containDeep({
            id: null,
            error: {code: -32700} // Parse Error
          });
          done();
        });

        // obviously invalid
        socket.end('abc');
      });

      it('should send more than one reply on the same socket', function(done) {
        const replies = [];
        responses.on('data', function(data) {
          replies.push(data);
        });

        // write raw requests to the socket
        socket.write(JSON.stringify(jayson.Utils.request('delay', [20])));
        socket.write(JSON.stringify(jayson.Utils.request('delay', [5])));

        setTimeout(function() {
          replies.should.have.lengthOf(2);
          replies[0].should.have.property('result', 5);
          replies[1].should.have.property('result', 20);
          done();
        }, 40);
      });

    });

  });

  describe('client', function() {

    const server = jayson.server(support.server.methods(), support.server.options());
    const server_tcp = server.tcp();
    const client = jayson.client.tcp({
      reviver: support.server.options().reviver,
      replacer: support.server.options().replacer,
      host: 'localhost',
      port: 3999
    });

    before(function(done) {
      server_tcp.listen(3999, 'localhost', done);
    });

    after(function() {
      server_tcp.close();
    });

    describe('common tests', suites.getCommonForClient(client));

  });

});
<commit_msg>Add delimiter option to test client<commit_after>const should = require('should');
const _ = require('lodash');
const jayson = require('./../');
const support = require('./support');
const suites = require('./support/suites');
const net = require('net');
const url = require('url');
const JSONStream = require('JSONStream');

describe('jayson.tcp', function() {

  describe('server', function() {

    let server = null;
    before(function() {
      server = jayson.server(support.server.methods(), support.server.options()).tcp();
    });

    after(function() {
      server.close();
    });

    it('should listen to a local port', function(done) {
      server.listen(3999, 'localhost', function() {
        server.close(done);
      });
    });

    it('should be an instance of net.Server', function() {
      server.should.be.instanceof(net.Server);
    });

    context('connected socket', function() {

      let socket = null;
      let responses = null;

      before(function(done) {
        server.listen(3999, 'localhost', done);
      });

      beforeEach(function(done) {
        socket = net.connect(3999, 'localhost', done);
        responses = JSONStream.parse();
        socket.pipe(responses);
      });

      afterEach(function(done) {
        socket.end();
        done();
      });

      it('should send a parse error for invalid JSON data', function(done) {
        responses.on('data', function(data) {
          data.should.containDeep({
            id: null,
            error: {code: -32700} // Parse Error
          });
          done();
        });

        // obviously invalid
        socket.end('abc');
      });

      it('should send more than one reply on the same socket', function(done) {
        const replies = [];
        responses.on('data', function(data) {
          replies.push(data);
        });

        // write raw requests to the socket
        socket.write(JSON.stringify(jayson.Utils.request('delay', [20])));
        socket.write(JSON.stringify(jayson.Utils.request('delay', [5])));

        setTimeout(function() {
          replies.should.have.lengthOf(2);
          replies[0].should.have.property('result', 5);
          replies[1].should.have.property('result', 20);
          done();
        }, 40);
      });

    });

  });

  describe('client', function() {

    const server = jayson.server(support.server.methods(), support.server.options());
    const server_tcp = server.tcp();
    const client = jayson.client.tcp({
      reviver: support.server.options().reviver,
      replacer: support.server.options().replacer,
      host: 'localhost',
      port: 3999,
      delimiter: '\r\n'
    });

    before(function(done) {
      server_tcp.listen(3999, 'localhost', done);
    });

    after(function() {
      server_tcp.close();
    });

    describe('common tests', suites.getCommonForClient(client));

  });

});
<|endoftext|>


<commit_before>'use strict';

module.exports = function (dbType, context) {

  describe(dbType + ': ltgt', function () {
    it('does gt queries', function () {
      var db = context.db;
      var index = {
        "index": {
          "fields": ["foo"]
        },
        "name": "foo-index",
        "type": "json"
      };

      return db.createIndex(index).then(function () {
        return db.bulkDocs([
          { _id: '1', foo: 'eyo'},
          { _id: '2', foo: 'ebb'},
          { _id: '3', foo: 'eba'},
          { _id: '4', foo: 'abo'}
        ]);
      }).then(function () {
        return db.find({
          selector: {foo: {"$gt": "eb"}},
          fields: ["_id", "foo"],
          sort: [{foo: "asc"}]
        });
      }).then(function (resp) {
        resp.should.deep.equal({
          docs: [
            {_id: '3', foo: 'eba'},
            {_id: '2', foo: 'ebb'},
            {_id: '1', foo: 'eyo'}
          ]
        });
      });
    });

    it('does lt queries', function () {
      var db = context.db;
      var index = {
        "index": {
          "fields": ["foo"]
        },
        "name": "foo-index",
        "type": "json"
      };

      return db.createIndex(index).then(function () {
        return db.bulkDocs([
          { _id: '1', foo: 'eyo'},
          { _id: '2', foo: 'ebb'},
          { _id: '3', foo: 'eba'},
          { _id: '4', foo: 'abo'}
        ]);
      }).then(function () {
        return db.find({
          selector: {foo: {"$lt": "eb"}},
          fields: ["_id", "foo"]
        });
      }).then(function (resp) {
        resp.should.deep.equal({
          docs: [
            {_id: '4', foo: 'abo'}
          ]
        });
      });
    });

    it('does lte queries', function () {
      var db = context.db;
      var index = {
        "index": {
          "fields": ["foo"]
        },
        "name": "foo-index",
        "type": "json"
      };

      return db.createIndex(index).then(function () {
        return db.bulkDocs([
          { _id: '1', foo: 'eyo'},
          { _id: '2', foo: 'ebb'},
          { _id: '3', foo: 'eba'},
          { _id: '4', foo: 'abo'}
        ]);
      }).then(function () {
        return db.find({
          selector: {foo: {"$lte": "eba"}},
          fields: ["_id", "foo"],
          sort: [{foo: "asc"}]
        });
      }).then(function (resp) {
        resp.should.deep.equal({
          docs: [
            {_id: '4', foo: 'abo'},
            {_id: '3', foo: 'eba'},
          ]
        });
      });
    });

    it('does gt queries, desc sort', function () {
      var db = context.db;
      var index = {
        "index": {
          "fields": ["foo"]
        },
        "name": "foo-index",
        "type": "json"
      };

      return db.createIndex(index).then(function () {
        return db.bulkDocs([
          { _id: '1', foo: 'eyo'},
          { _id: '2', foo: 'ebb'},
          { _id: '3', foo: 'eba'},
          { _id: '4', foo: 'abo'}
        ]);
      }).then(function () {
        return db.find({
          selector: {foo: {"$gt": "eb"}},
          fields: ["_id", "foo"],
          sort: [{foo: "desc"}]
        });
      }).then(function (resp) {
        resp.should.deep.equal({
          docs: [
            {_id: '1', foo: 'eyo'},
            {_id: '2', foo: 'ebb'},
            {_id: '3', foo: 'eba'}
          ]
        });
      });
    });

    it('#38 $gt with dates', function () {
      var db = context.db;

      var startDate = "2015-05-25T00:00:00.000Z";
      var endDate = "2015-05-26T00:00:00.000Z";

      return db.createIndex({
        index: {
          fields: ['docType', 'logDate']
        }
      }).then(function () {
        return db.bulkDocs([
          {_id: '1', docType: 'log', logDate: "2015-05-24T00:00:00.000Z"},
          {_id: '2', docType: 'log', logDate: "2015-05-25T00:00:00.000Z"},
          {_id: '3', docType: 'log', logDate: "2015-05-26T00:00:00.000Z"},
          {_id: '4', docType: 'log', logDate: "2015-05-27T00:00:00.000Z"}
        ]);
      }).then(function() {
        return db.find({
          selector: {docType: 'log'}
        }).then(function (result) {
          result.docs.map(function (x) { delete x._rev; return x; }).should.deep.equal([
            {
              "_id": "1",
              "docType": "log",
              "logDate": "2015-05-24T00:00:00.000Z"
            },
            {
              "_id": "2",
              "docType": "log",
              "logDate": "2015-05-25T00:00:00.000Z"
            },
            {
              "_id": "3",
              "docType": "log",
              "logDate": "2015-05-26T00:00:00.000Z"
            },
            {
              "_id": "4",
              "docType": "log",
              "logDate": "2015-05-27T00:00:00.000Z"
            }
          ], 'test 1');
        });
      }).then(function () {
        return db.find({
          selector: {docType: 'log', logDate: {$gt: startDate}}
        }).then(function (result) {
          result.docs.map(function (x) { delete x._rev; return x; }).should.deep.equal([
            {
              "_id": "3",
              "docType": "log",
              "logDate": "2015-05-26T00:00:00.000Z"
            },
            {
              "_id": "4",
              "docType": "log",
              "logDate": "2015-05-27T00:00:00.000Z"
            }
          ], 'test 2');
        });
      }).then(function () {
        return db.find({
          selector: {docType: 'log', logDate: {$gte: startDate}}
        }).then(function (result) {
          result.docs.map(function (x) { delete x._rev; return x; }).should.deep.equal([
            {
              "_id": "2",
              "docType": "log",
              "logDate": "2015-05-25T00:00:00.000Z"
            },
            {
              "_id": "3",
              "docType": "log",
              "logDate": "2015-05-26T00:00:00.000Z"
            },
            {
              "_id": "4",
              "docType": "log",
              "logDate": "2015-05-27T00:00:00.000Z"
            }
          ], 'test 3');
        });
      }).then(function () {
        return db.find({
          selector: {
            docType: 'log',
            logDate: {$gte: startDate, $lte: endDate}
          }
        }).then(function (result) {
          result.docs.map(function (x) { delete x._rev; return x; }).should.deep.equal([
            {
              "_id": "2",
              "docType": "log",
              "logDate": "2015-05-25T00:00:00.000Z"
            },
            {
              "_id": "3",
              "docType": "log",
              "logDate": "2015-05-26T00:00:00.000Z"
            }
          ], 'test 4');
        });
      });
    });

  });
};<commit_msg>(#41) - add test to try to reproduce<commit_after>'use strict';

module.exports = function (dbType, context) {

  describe(dbType + ': ltgt', function () {
    it('does gt queries', function () {
      var db = context.db;
      var index = {
        "index": {
          "fields": ["foo"]
        },
        "name": "foo-index",
        "type": "json"
      };

      return db.createIndex(index).then(function () {
        return db.bulkDocs([
          { _id: '1', foo: 'eyo'},
          { _id: '2', foo: 'ebb'},
          { _id: '3', foo: 'eba'},
          { _id: '4', foo: 'abo'}
        ]);
      }).then(function () {
        return db.find({
          selector: {foo: {"$gt": "eb"}},
          fields: ["_id", "foo"],
          sort: [{foo: "asc"}]
        });
      }).then(function (resp) {
        resp.should.deep.equal({
          docs: [
            {_id: '3', foo: 'eba'},
            {_id: '2', foo: 'ebb'},
            {_id: '1', foo: 'eyo'}
          ]
        });
      });
    });

    it('does lt queries', function () {
      var db = context.db;
      var index = {
        "index": {
          "fields": ["foo"]
        },
        "name": "foo-index",
        "type": "json"
      };

      return db.createIndex(index).then(function () {
        return db.bulkDocs([
          { _id: '1', foo: 'eyo'},
          { _id: '2', foo: 'ebb'},
          { _id: '3', foo: 'eba'},
          { _id: '4', foo: 'abo'}
        ]);
      }).then(function () {
        return db.find({
          selector: {foo: {"$lt": "eb"}},
          fields: ["_id", "foo"]
        });
      }).then(function (resp) {
        resp.should.deep.equal({
          docs: [
            {_id: '4', foo: 'abo'}
          ]
        });
      });
    });

    it('does lte queries', function () {
      var db = context.db;
      var index = {
        "index": {
          "fields": ["foo"]
        },
        "name": "foo-index",
        "type": "json"
      };

      return db.createIndex(index).then(function () {
        return db.bulkDocs([
          { _id: '1', foo: 'eyo'},
          { _id: '2', foo: 'ebb'},
          { _id: '3', foo: 'eba'},
          { _id: '4', foo: 'abo'}
        ]);
      }).then(function () {
        return db.find({
          selector: {foo: {"$lte": "eba"}},
          fields: ["_id", "foo"],
          sort: [{foo: "asc"}]
        });
      }).then(function (resp) {
        resp.should.deep.equal({
          docs: [
            {_id: '4', foo: 'abo'},
            {_id: '3', foo: 'eba'},
          ]
        });
      });
    });

    it('#41 another complex multifield query', function () {
      var db = context.db;
      var index = {
        "index": {
          "fields": ["datetime"]
        }
      };

      return db.createIndex(index).then(function () {
        return db.bulkDocs([
          {_id: '1',
            datetime: 1434054640000,
            glucoseType: 'fasting',
            patientId: 1
          },
          {_id: '2',
            datetime: 1434054650000,
            glucoseType: 'fasting',
            patientId: 1
          },
          {_id: '3',
            datetime: 1434054660000,
            glucoseType: 'fasting',
            patientId: 1
          },
          {_id: '4',
            datetime: 1434054670000,
            glucoseType: 'fasting',
            patientId: 1
          }
        ]);
      }).then(function () {
        return db.find({
          selector: {
            datetime: { "$lt": 1434054660000 },
            glucoseType: { "$eq": 'fasting' },
            patientId: { "$eq": 1 }
          }
        });
      }).then(function (res) {
        var docs = res.docs.map(function (x) { delete x._rev; return x; });
        docs.should.deep.equal([
          {
            "_id": "1",
            "datetime": 1434054640000,
            "glucoseType": "fasting",
            "patientId": 1
          },
          {
            "_id": "2",
            "datetime": 1434054650000,
            "glucoseType": "fasting",
            "patientId": 1
          }
        ]);
      });
    });

    it('does gt queries, desc sort', function () {
      var db = context.db;
      var index = {
        "index": {
          "fields": ["foo"]
        },
        "name": "foo-index",
        "type": "json"
      };

      return db.createIndex(index).then(function () {
        return db.bulkDocs([
          { _id: '1', foo: 'eyo'},
          { _id: '2', foo: 'ebb'},
          { _id: '3', foo: 'eba'},
          { _id: '4', foo: 'abo'}
        ]);
      }).then(function () {
        return db.find({
          selector: {foo: {"$gt": "eb"}},
          fields: ["_id", "foo"],
          sort: [{foo: "desc"}]
        });
      }).then(function (resp) {
        resp.should.deep.equal({
          docs: [
            {_id: '1', foo: 'eyo'},
            {_id: '2', foo: 'ebb'},
            {_id: '3', foo: 'eba'}
          ]
        });
      });
    });

    it('#38 $gt with dates', function () {
      var db = context.db;

      var startDate = "2015-05-25T00:00:00.000Z";
      var endDate = "2015-05-26T00:00:00.000Z";

      return db.createIndex({
        index: {
          fields: ['docType', 'logDate']
        }
      }).then(function () {
        return db.bulkDocs([
          {_id: '1', docType: 'log', logDate: "2015-05-24T00:00:00.000Z"},
          {_id: '2', docType: 'log', logDate: "2015-05-25T00:00:00.000Z"},
          {_id: '3', docType: 'log', logDate: "2015-05-26T00:00:00.000Z"},
          {_id: '4', docType: 'log', logDate: "2015-05-27T00:00:00.000Z"}
        ]);
      }).then(function() {
        return db.find({
          selector: {docType: 'log'}
        }).then(function (result) {
          result.docs.map(function (x) { delete x._rev; return x; }).should.deep.equal([
            {
              "_id": "1",
              "docType": "log",
              "logDate": "2015-05-24T00:00:00.000Z"
            },
            {
              "_id": "2",
              "docType": "log",
              "logDate": "2015-05-25T00:00:00.000Z"
            },
            {
              "_id": "3",
              "docType": "log",
              "logDate": "2015-05-26T00:00:00.000Z"
            },
            {
              "_id": "4",
              "docType": "log",
              "logDate": "2015-05-27T00:00:00.000Z"
            }
          ], 'test 1');
        });
      }).then(function () {
        return db.find({
          selector: {docType: 'log', logDate: {$gt: startDate}}
        }).then(function (result) {
          result.docs.map(function (x) { delete x._rev; return x; }).should.deep.equal([
            {
              "_id": "3",
              "docType": "log",
              "logDate": "2015-05-26T00:00:00.000Z"
            },
            {
              "_id": "4",
              "docType": "log",
              "logDate": "2015-05-27T00:00:00.000Z"
            }
          ], 'test 2');
        });
      }).then(function () {
        return db.find({
          selector: {docType: 'log', logDate: {$gte: startDate}}
        }).then(function (result) {
          result.docs.map(function (x) { delete x._rev; return x; }).should.deep.equal([
            {
              "_id": "2",
              "docType": "log",
              "logDate": "2015-05-25T00:00:00.000Z"
            },
            {
              "_id": "3",
              "docType": "log",
              "logDate": "2015-05-26T00:00:00.000Z"
            },
            {
              "_id": "4",
              "docType": "log",
              "logDate": "2015-05-27T00:00:00.000Z"
            }
          ], 'test 3');
        });
      }).then(function () {
        return db.find({
          selector: {
            docType: 'log',
            logDate: {$gte: startDate, $lte: endDate}
          }
        }).then(function (result) {
          result.docs.map(function (x) { delete x._rev; return x; }).should.deep.equal([
            {
              "_id": "2",
              "docType": "log",
              "logDate": "2015-05-25T00:00:00.000Z"
            },
            {
              "_id": "3",
              "docType": "log",
              "logDate": "2015-05-26T00:00:00.000Z"
            }
          ], 'test 4');
        });
      });
    });

  });
};<|endoftext|>


<commit_before>
// @flow

import { graphql } from "react-apollo";
import gql from "graphql-tag";
import moment from "moment";

const baseData = [
  { month: "January", amount: 0, tick: "J" },
  { month: "February", amount: 0, tick: "F" },
  { month: "March", amount: 0, tick: "M" },
  { month: "April", amount: 0, tick: "A" },
  { month: "May", amount: 0, tick: "M" },
  { month: "June", amount: 0, tick: "J" },
  { month: "July", amount: 0, tick: "J" },
  { month: "August", amount: 0, tick: "A" },
  { month: "September", amount: 0, tick: "S" },
  { month: "October", amount: 0, tick: "O" },
  { month: "November", amount: 0, tick: "N" },
  { month: "December", amount: 0, tick: "D" },
];

export const formatGivingSummaryData = (data: Object): ?Object => {
  if (!data || !data.accounts) return null;
  const accountsData = data.accounts;

  if (!Array.isArray(accountsData)) return null;
  const summaryData = [...baseData];
  let total = 0;
  const accounts = {};

  accountsData.map((account) => {
    accounts[account.name] = account.total;
    // iterate over every transaction, and sum up the months
    account.transactions.map((transaction) => {
      const month = moment(new Date(transaction.date)).format("M");
      if (!transaction.details || !transaction.details.length) return transaction;
      summaryData[Number(month) - 1].amount += transaction.details
        .reduce((prev, { amount }) => prev + amount, 0);
      total += transaction.details.reduce((prev, { amount }) => prev + amount, 0);
      return transaction;
    });
    return null;
  });

  return ({
    ...data,
    total,
    chartData: summaryData,
    accounts,
  });
};

const YTD_QUERY = gql`
  query givingSummary($start: String!, $end: String!) {
    accounts(allFunds: true) {
      total(start: $start, end: $end)
      name
      transactions(limit: 0, start: $start, end: $end) {
        id
        date
        details {
          amount
        }
      }
    }
  }
`;

export default graphql(YTD_QUERY, {
  options: {
    variables: {
      start: moment().startOf("year").format(),
      end: moment().endOf("year").format(),
    },
  },
  props: ({ data }) => ({
    changeYear: (year) => {
      const start = moment(`${year}`, "YYYY").startOf("year").format();
      const end = moment(`${year}`, "YYYY").endOf("year").format();
      return data.refetch({ start, end });
    },
    loading: data.loading,
    data: formatGivingSummaryData(data),
  }),
});

<commit_msg>moved baseData into class (#1598)<commit_after>
// @flow

import { graphql } from "react-apollo";
import gql from "graphql-tag";
import moment from "moment";

export const formatGivingSummaryData = (data: Object): ?Object => {
  const baseData = [
    { month: "January", amount: 0, tick: "J" },
    { month: "February", amount: 0, tick: "F" },
    { month: "March", amount: 0, tick: "M" },
    { month: "April", amount: 0, tick: "A" },
    { month: "May", amount: 0, tick: "M" },
    { month: "June", amount: 0, tick: "J" },
    { month: "July", amount: 0, tick: "J" },
    { month: "August", amount: 0, tick: "A" },
    { month: "September", amount: 0, tick: "S" },
    { month: "October", amount: 0, tick: "O" },
    { month: "November", amount: 0, tick: "N" },
    { month: "December", amount: 0, tick: "D" },
  ];

  if (!data || !data.accounts) return null;
  const accountsData = data.accounts;

  if (!Array.isArray(accountsData)) return null;
  const summaryData = [...baseData];

  let total = 0;
  const accounts = {};

  accountsData.map((account) => {
    accounts[account.name] = account.total;
    // iterate over every transaction, and sum up the months
    account.transactions.map((transaction) => {
      const month = moment(new Date(transaction.date)).format("M");
      if (!transaction.details || !transaction.details.length) return transaction;
      summaryData[Number(month) - 1].amount += transaction.details
        .reduce((prev, { amount }) => prev + amount, 0);
      total += transaction.details.reduce((prev, { amount }) => prev + amount, 0);
      return transaction;
    });
    return null;
  });

  return ({
    ...data,
    total,
    chartData: summaryData,
    accounts,
  });
};

const YTD_QUERY = gql`
  query givingSummary($start: String!, $end: String!) {
    accounts(allFunds: true) {
      total(start: $start, end: $end)
      name
      transactions(limit: 0, start: $start, end: $end) {
        id
        date
        details {
          amount
        }
      }
    }
  }
`;

export default graphql(YTD_QUERY, {
  options: {
    variables: {
      start: moment().startOf("year").format(),
      end: moment().endOf("year").format(),
    },
  },
  props: ({ data }) => ({
    changeYear: (year) => {
      const start = moment(`${year}`, "YYYY").startOf("year").format();
      const end = moment(`${year}`, "YYYY").endOf("year").format();
      return data.refetch({ start, end });
    },
    loading: data.loading,
    data: formatGivingSummaryData(data),
  }),
});

<|endoftext|>


<commit_before>/**
 * Game state to be stored here - lives, weapon state, score, etc.
 * To be passed around as a require() where needed.
 **/

var gameStatus = {};

// Active status of the three color wells.
gameStatus.colorStates = {
    r: false,
    g: false,
    b: false
};

gameStatus.colorMeters = {
    r: 100,
    g: 100,
    b: 100
}

// Current active mixed color
gameStatus.activeColor = '#ffffff';

// Current active hexint color, for sprite.tint
gameStatus.activeTintColor = 0xffffff;

// Function to toggle color status.
gameStatus.toggleColor = function(colorKey) {
    console.log(colorKey);
    this.colorStates[colorKey] = !this.colorStates[colorKey];
    this.updateActiveColor();
}

// Updates the active color to match the toggled flags
gameStatus.updateActiveColor = function() {
    var r = (this.colorStates.r) ? 'FF' : '00',
        g = (this.colorStates.g) ? 'FF' : '00',
        b = (this.colorStates.b) ? 'FF' : '00';
    this.activeColor = '#' + r + g + b;
    this.activeTintColor = parseInt(r + g + b, 16);
}

gameStatus.updateActiveColor();

module.exports = gameStatus;
<commit_msg>Update collision algo<commit_after>var config = require('../config');
/**
 * Game state to be stored here - lives, weapon state, score, etc.
 * To be passed around as a require() where needed.
 **/

var gameStatus = {};

// Active status of the three color wells.
gameStatus.colorStates = {
    r: false,
    g: false,
    b: false
};

gameStatus.colorMeters = {
    r: 100,
    g: 100,
    b: 100
}

// Current active mixed color
gameStatus.activeColor = '#ffffff';

// Current active hexint color, for sprite.tint
gameStatus.activeTintColor = 0xffffff;

// Function to toggle color status.
gameStatus.toggleColor = function(colorKey) {
    this.colorStates[colorKey] = !this.colorStates[colorKey];
    this.updateActiveColor();
}

// Updates the active color to match the toggled flags
gameStatus.updateActiveColor = function() {
    var str = '', self = this;
    config.gameColorKeys.forEach(function(k) {
        if(self.colorStates[k]) str += k;
    });
    var col;
    if (str === 'rgb') {
        col = '#aa77fa';
    } else if (str === '') {
        col = config.inactiveColor;
    } else {
        col = config.gameColors[str];
    }
    this.activeColor = col;
    this.activeTintColor = parseInt(col.substr(1), 16);
}

gameStatus.updateActiveColor();

module.exports = gameStatus;
<|endoftext|>


<commit_before>
const range = require('./range').default

describe('range', () => {

  it('should return an iterable object that is its own iterator', () => {
    expect(range(0, 1)[Symbol.iterator] instanceof Function).toBe(true)
    let testingRange = range(0, 1)
    expect(testingRange[Symbol.iterator]()).toBe(testingRange)
  })

  it('should return an iterator', () => {
    let testingRange = range(0, 1)
    expect(testingRange.next instanceof Function).toBe(true)
    expect(testingRange.next()).toEqual({ done: false, value: 0 })
    expect(testingRange.next()).toEqual({ done: true, value: undefined })
  })

})
<commit_msg>added more tests for numeric sequences<commit_after>
const range = require('./range').default

describe('range', () => {

  it('should return an iterable object that is its own iterator', () => {
    expect(range(0, 1)[Symbol.iterator] instanceof Function).toBe(true)
    let testingRange = range(0, 1)
    expect(testingRange[Symbol.iterator]()).toBe(testingRange)
  })

  it('should return an iterator', () => {
    let testingRange = range(0, 1)
    expect(testingRange.next instanceof Function).toBe(true)
    expect(testingRange.next()).toEqual({ done: false, value: 0 })
    expect(testingRange.next()).toEqual({ done: true, value: undefined })
  })

  it('should allow generating an incrementing numeric sequence', () => {
    expect([...range(0, 10)]).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  })

  it('should allow generating a decrementing numeric sequence', () => {
    expect([...range(10, 0)]).toEqual([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
  })

  it('should allow generating a single-element sequences', () => {
    expect([...range(0, 1)]).toEqual([0])
    expect([...range(7, 8)]).toEqual([7])
  })

  it('should allow generating empty sequences', () => {
    expect([...range(0, 0)]).toEqual([])
    expect([...range(4, 4)]).toEqual([])
  })

  it('should allow specifying the step size of the sequence', () => {
    expect([...range(0, 10, 3)]).toEqual([0, 3, 6, 9])
    expect([...range(0, 9, 3)]).toEqual([0, 3, 6])
    expect([...range(0, 9, -3)]).toEqual([])
    expect([...range(10, 0, -3)]).toEqual([10, 7, 4, 1])
    expect([...range(10, 1, -3)]).toEqual([10, 7, 4])
  })

})
<|endoftext|>


<commit_before>/**
 * Dependencies.
 */

const _ = require('lodash');
const app = require('../index');
const config = require('config');
const expect = require('chai').expect;
const sinon = require('sinon');
const utils = require('../test/utils.js')();
var roles = require('../server/constants/roles');

/**
 * Models
 */

const models = app.get('models');
const Transaction = models.Transaction;

/**
 * Data
 */

var userData = utils.data('user1');
var groupData = utils.data('group1');
var transactionsData = utils.data('transactions1').transactions;

/**
 * Tests.
 */

describe.only('transaction model', () => {

  var user, group;

  beforeEach(() => utils.cleanAllDb());

  beforeEach(() => models.User.create(userData).tap(u => user = u));

  // Create group2.
  beforeEach(() =>
    models.Group.create(groupData)
      .tap(g => group = g)
      .then(() => group.addUserWithRole(user, roles.HOST)));

  it('isExpense is true if the amount is negative', done => {
    Transaction.create({
      amount: -10
    })
    .then(transaction => {
      expect(transaction.info.isExpense).to.be.true;
      expect(transaction.info.isRejected).to.be.false;
      expect(transaction.info.isManual).to.be.false;
      expect(transaction.info.isDonation).to.be.false;
      expect(transaction.info.isReimbursed).to.be.false;
      done();
    })
    .catch(done);
  });

  it('isRejected is true if approvedAt is not null and approved is false', done => {
    Transaction.create({
      approvedAt: new Date(),
      approved: false
    })
    .then(transaction => {
      expect(transaction.info.isRejected).to.be.true;
      expect(transaction.info.isExpense).to.be.false;
      expect(transaction.info.isManual).to.be.false;
      expect(transaction.info.isDonation).to.be.false;
      expect(transaction.info.isReimbursed).to.be.false;
      done();
    })
    .catch(done);
  });

  it('isDonation is true tags contains `Donation`', done => {
    Transaction.create({
      tags: ['Donation']
    })
    .then(transaction => {
      expect(transaction.info.isDonation).to.be.true;
      expect(transaction.info.isRejected).to.be.false;
      expect(transaction.info.isExpense).to.be.false;
      expect(transaction.info.isManual).to.be.false;
      expect(transaction.info.isReimbursed).to.be.false;
      done();
    })
    .catch(done);
  });

  it('isManual if payoutMethod is manual', done => {
    Transaction.create({
      payoutMethod: 'manual'
    })
    .then(transaction => {
      expect(transaction.info.isManual).to.be.true;
      expect(transaction.info.isDonation).to.be.false;
      expect(transaction.info.isRejected).to.be.false;
      expect(transaction.info.isExpense).to.be.false;
      expect(transaction.info.isReimbursed).to.be.false;
      done();
    })
    .catch(done);
  });

  it('isReimbursed if reimbursedAt is set', done => {
    Transaction.create({
      reimbursedAt: new Date()
    })
    .then(transaction => {
      expect(transaction.info.isReimbursed).to.be.true;
      expect(transaction.info.isManual).to.be.false;
      expect(transaction.info.isDonation).to.be.false;
      expect(transaction.info.isRejected).to.be.false;
      expect(transaction.info.isExpense).to.be.false;
      done();
    })
    .catch(done);
  });

  it('createFromPayload() generates a new activity', done => {

    beforeEach(() => sinon.spy(Transaction, 'createActivity'));

    afterEach(() => Transaction.createActivity.restore());

    Transaction.createFromPayload({
      transaction: transactionsData[7],
      user,
      group
    })
    .then(transaction => {
      expect(transaction.GroupId).to.equal(group.id);
      expect(Transaction.createActivity.lastCall.args[0]).to.equal(transaction);
      done();
    })
    .catch(done);
  })
});
<commit_msg>fix unit tests for the sequelize model<commit_after>/**
 * Dependencies.
 */

const _ = require('lodash');
const app = require('../index');
const config = require('config');
const expect = require('chai').expect;
const sinon = require('sinon');
const utils = require('../test/utils.js')();
var roles = require('../server/constants/roles');

/**
 * Models
 */

const models = app.get('models');
const Transaction = models.Transaction;

/**
 * Data
 */

var userData = utils.data('user1');
var groupData = utils.data('group1');
var transactionsData = utils.data('transactions1').transactions;

/**
 * Tests.
 */

describe.only('transaction model', () => {

  var user, group;

  beforeEach(() => utils.cleanAllDb());

  beforeEach(() => models.User.create(userData).tap(u => user = u));

  // Create group2.
  beforeEach(() =>
    models.Group.create(groupData)
      .tap(g => group = g)
      .then(() => group.addUserWithRole(user, roles.HOST)));

  it('isExpense is true if the amount is negative', done => {
    Transaction.create({
      amount: -10
    })
    .then(transaction => {
      expect(transaction.info.isExpense).to.be.true;
      expect(transaction.info.isRejected).to.be.false;
      expect(transaction.info.isManual).to.be.false;
      expect(transaction.info.isDonation).to.be.false;
      expect(transaction.info.isReimbursed).to.be.false;
      done();
    })
    .catch(done);
  });

  it('isRejected is true if approvedAt is not null and approved is false', done => {
    Transaction.create({
      approvedAt: new Date(),
      approved: false
    })
    .then(transaction => {
      expect(transaction.info.isRejected).to.be.true;
      expect(transaction.info.isExpense).to.be.false;
      expect(transaction.info.isManual).to.be.false;
      expect(transaction.info.isDonation).to.be.false;
      expect(transaction.info.isReimbursed).to.be.false;
      done();
    })
    .catch(done);
  });

  it('isDonation is true tags contains `Donation`', done => {
    Transaction.create({
      tags: ['Donation']
    })
    .then(transaction => {
      expect(transaction.info.isDonation).to.be.true;
      expect(transaction.info.isRejected).to.be.false;
      expect(transaction.info.isExpense).to.be.false;
      expect(transaction.info.isManual).to.be.false;
      expect(transaction.info.isReimbursed).to.be.false;
      done();
    })
    .catch(done);
  });

  it('isManual if payoutMethod is manual', done => {
    Transaction.create({
      payoutMethod: 'manual'
    })
    .then(transaction => {
      expect(transaction.info.isManual).to.be.true;
      expect(transaction.info.isDonation).to.be.false;
      expect(transaction.info.isRejected).to.be.false;
      expect(transaction.info.isExpense).to.be.false;
      expect(transaction.info.isReimbursed).to.be.false;
      done();
    })
    .catch(done);
  });

  it('isReimbursed if reimbursedAt is set', done => {
    Transaction.create({
      reimbursedAt: new Date()
    })
    .then(transaction => {
      expect(transaction.info.isReimbursed).to.be.true;
      expect(transaction.info.isManual).to.be.false;
      expect(transaction.info.isDonation).to.be.false;
      expect(transaction.info.isRejected).to.be.false;
      expect(transaction.info.isExpense).to.be.false;
      done();
    })
    .catch(done);
  });

  var createActivitySpy;

  before(() => {
    createActivitySpy = sinon.spy(Transaction, 'createActivity');
  });

  beforeEach(() => createActivitySpy.reset());

  after(() => createActivitySpy.restore());

  it('createFromPayload() generates a new activity', (done) => {

    Transaction.createFromPayload({
      transaction: transactionsData[7],
      user,
      group
    })
    .then(transaction => {
      expect(transaction.GroupId).to.equal(group.id);
      expect(createActivitySpy.lastCall.args[0]).to.equal(transaction);
      done();
    })
    .catch(done);
  });
});
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var Transformer = require('./../../lib/transformer');
var transformer = new Transformer({classes: true});

function test(script) {
  return transformer.run(script);
}

describe('Class transformation', function () {

  it('should not convert functions without prototype assignment to class', function () {
    var script = "function someClass() {\n}";

    expect(test(script)).to.equal(script);
  });

  it('should convert functions with prototype assignment to class', function () {
    expect(test(
      "function someClass() {\n" +
      "}\n" +
      "someClass.prototype.someMethod = function(a, b) {\n" +
      "};"
    )).to.equal(
      "class someClass {\n" +
      "  someMethod(a, b) {\n" +
      "  }\n" +
      "}"
    );
  });

  it('should convert non-empty function to constructor method', function () {
    expect(test(
      "function someClass(a, b) {\n" +
      "  this.params = [a, b];\n" +
      "}\n" +
      "someClass.prototype.someMethod = function(ma, mb) {\n" +
      "};"
    )).to.equal(
      "class someClass {\n" +
      "  constructor(a, b) {\n" +
      "    this.params = [a, b];\n" +
      "  }\n" +
      "\n" +
      "  someMethod(ma, mb) {\n" +
      "  }\n" +
      "}"
    );
  });

  it('should not convert non-anonymous functions to methods', function () {
    expect(test(
      "function someClass() {\n" +
      "}\n" +
      "someClass.prototype.someMethod = someMethod;\n" +
      "function someMethod(a, b) {\n" +
      "}"
    )).to.equal(
      "function someClass() {\n" +
      "}\n" +
      "someClass.prototype.someMethod = someMethod;\n" +
      "function someMethod(a, b) {\n" +
      "}"
    );
  });

  it('should convert Object.defineProperty to setters and getters', function () {
    expect(test(
      "function someClass() {\n" +
      "}\n" +
      "someClass.prototype.someMethod = function(a, b) {\n" +
      "};\n" +
      "Object.defineProperty(someClass.prototype, 'someAccessor', {\n" +
      "  get: function () {\n" +
      "    return this._some;\n" +
      "  },\n" +
      "  set: function (value) {\n" +
      "    this._some = value;\n" +
      "  }\n" +
      "});"
    )).to.equal(
      "class someClass {\n" +
      "  someMethod(a, b) {\n" +
      "  }\n" +
      "\n" +
      "  get someAccessor() {\n" +
      "    return this._some;\n" +
      "  }\n" +
      "\n" +
      "  set someAccessor(value) {\n" +
      "    this._some = value;\n" +
      "  }\n" +
      "}"
    );
  });

});
<commit_msg>Add expectNoChange() helper to classes test<commit_after>var expect = require('chai').expect;
var Transformer = require('./../../lib/transformer');
var transformer = new Transformer({classes: true});

function test(script) {
  return transformer.run(script);
}

function expectNoChange(script) {
  expect(test(script)).to.equal(script);
}

describe('Class transformation', function () {

  it('should not convert functions without prototype assignment to class', function () {
    var script = "function someClass() {\n}";

    expect(test(script)).to.equal(script);
  });

  it('should convert functions with prototype assignment to class', function () {
    expect(test(
      "function someClass() {\n" +
      "}\n" +
      "someClass.prototype.someMethod = function(a, b) {\n" +
      "};"
    )).to.equal(
      "class someClass {\n" +
      "  someMethod(a, b) {\n" +
      "  }\n" +
      "}"
    );
  });

  it('should convert non-empty function to constructor method', function () {
    expect(test(
      "function someClass(a, b) {\n" +
      "  this.params = [a, b];\n" +
      "}\n" +
      "someClass.prototype.someMethod = function(ma, mb) {\n" +
      "};"
    )).to.equal(
      "class someClass {\n" +
      "  constructor(a, b) {\n" +
      "    this.params = [a, b];\n" +
      "  }\n" +
      "\n" +
      "  someMethod(ma, mb) {\n" +
      "  }\n" +
      "}"
    );
  });

  it('should not convert non-anonymous functions to methods', function () {
    expectNoChange(
      "function someClass() {\n" +
      "}\n" +
      "someClass.prototype.someMethod = someMethod;\n" +
      "function someMethod(a, b) {\n" +
      "}"
    );
  });

  it('should convert Object.defineProperty to setters and getters', function () {
    expect(test(
      "function someClass() {\n" +
      "}\n" +
      "someClass.prototype.someMethod = function(a, b) {\n" +
      "};\n" +
      "Object.defineProperty(someClass.prototype, 'someAccessor', {\n" +
      "  get: function () {\n" +
      "    return this._some;\n" +
      "  },\n" +
      "  set: function (value) {\n" +
      "    this._some = value;\n" +
      "  }\n" +
      "});"
    )).to.equal(
      "class someClass {\n" +
      "  someMethod(a, b) {\n" +
      "  }\n" +
      "\n" +
      "  get someAccessor() {\n" +
      "    return this._some;\n" +
      "  }\n" +
      "\n" +
      "  set someAccessor(value) {\n" +
      "    this._some = value;\n" +
      "  }\n" +
      "}"
    );
  });

});
<|endoftext|>


<commit_before>'use strict';

describe('Treasure Tracking', function () {
  var treasure, server, postUrl, respondWith;

  describe('#addEvent', function () {

    describe('validation', function () {

      beforeEach(function () {
        treasure = new Treasure({
          database: treasureHelper.database,
          writeKey: treasureHelper.writeKey,
          host: treasureHelper.host
        });
      });

      describe('event', function () {

        it('should error if event is absent', function () {

          expect(function () {
            treasure.addEvent(treasureHelper.table, undefined);
          }).to.throw(Error);

        });

        it('should error if event is null', function () {

          expect(function () {
            treasure.addEvent(treasureHelper.table, null);
          }).to.throw(Error);

        });

        it('should error if event is of incorrect type', function () {

          // Number
          expect(function () {
            treasure.addEvent(treasureHelper.table, 0);
          }).to.throw(Error);

          // Boolean
          expect(function () {
            treasure.addEvent(treasureHelper.table, false);
          }).to.throw(Error);

          // Array
          expect(function () {
            treasure.addEvent(treasureHelper.table, ['array']);
          }).to.throw(Error);

          // String
          expect(function () {
            treasure.addEvent(treasureHelper.table, 'String');
          }).to.throw(Error);

        });

      });

      describe('table', function() {

        it('should error if table is absent', function () {

          expect(function () {
            treasure.addEvent(undefined);
          }).to.throw(Error);

        });

        it('should error if table is empty', function () {

          expect(function () {
            treasure.addEvent('');
          }).to.throw(Error);

        });

        it('should error if table is of incorrect type', function () {

          // Number
          expect(function () {
            treasure.addEvent(0);
          }).to.throw(Error);

          // Boolean
          expect(function () {
            treasure.addEvent(false);
          }).to.throw(Error);

          // Array
          expect(function () {
            treasure.addEvent(['array']);
          }).to.throw(Error);

          // Object
          expect(function () {
            treasure.addEvent({});
          }).to.throw(Error);

        });

        it('should error if table is invalid', function () {

          // Under 3 characters
          expect(function () {
            treasure.addEvent('12');
          }).to.throw(Error);

          // Over 255 characters
          expect(function () {
            treasure.addEvent('1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111');
          }).to.throw(Error);

          // Uppercase chracters
          expect(function () {
            treasure.addEvent('FOO_BAR');
          }).to.throw(Error);

          // Special characters
          expect(function () {
            treasure.addEvent('!@#$%ˆ&*()-+=');
          }).to.throw(Error);

        });

        it('should accept a valid table', function () {
          expect(function () {
            treasure.addEvent(treasureHelper.table, {});
          }).not.to.throw(Error);
        });
      });

    });

    describe('via XHR/CORS (if supported)', function () {

      beforeEach(function () {
        treasure = new Treasure({
          database: treasureHelper.database,
          writeKey: treasureHelper.writeKey,
          host: treasureHelper.host,
          requestType: 'xhr'
        });
        postUrl = treasure.client.endpoint + '/js/v3/event/' + treasure.client.database + '/' + treasureHelper.table;
        server = sinon.fakeServer.create();
        respondWith = function (code, body) {
          server.respondWith('POST', postUrl, [code, { 'Content-Type': 'application/json'}, body]);
        };
      });

      afterEach(function () {
        server.restore();
      });

      if ('withCredentials' in new XMLHttpRequest()) {

        it('should post to the API using xhr where CORS is supported', function () {

          var successCallback = JSON.parse(treasureHelper.responses.success);

          var callbacks = [sinon.spy(), sinon.spy()];
          respondWith(200, treasureHelper.responses.success);
          treasure.addEvent(treasureHelper.table, treasureHelper.properties, callbacks[0], callbacks[1]);
          server.respond();

          expect(server.requests[0].requestBody)
            .to.equal(JSON.stringify(treasureHelper.properties));
          expect(callbacks[0].calledOnce).to.equal(true);
          expect(callbacks[0].calledWith(successCallback)).to.equal(true);
          expect(callbacks[1].calledOnce).not.to.equal(true);

        });

        it('should call the error callback on error', function () {

          var callbacks = [sinon.spy(), sinon.spy()];
          respondWith(500, treasureHelper.responses.error);
          treasure.addEvent(treasureHelper.table, treasureHelper.properties, callbacks[0], callbacks[1]);
          server.respond();

          expect(server.requests[0].requestBody)
            .to.equal(JSON.stringify(treasureHelper.properties));
          expect(callbacks[0].calledOnce).not.to.equal(true);
          expect(callbacks[1].calledOnce).to.equal(true);

        });

      }

    });

    describe('via JSONP to a fake server', function () {

      beforeEach(function () {
        treasure = new Treasure({
          database: treasureHelper.database,
          writeKey: treasureHelper.writeKey,
          host: treasureHelper.jsonphost,
          requestType: 'jsonp'
        });
      });

      it('should add a script tag with a URL that has data and modified params', function () {

        treasure.addEvent(treasureHelper.table, treasureHelper.properties);
        var tag = document.getElementById('td-js-sdk-jsonp');
        expect(tag).to.exist.and.be.an('object');
        expect(tag.src).to.contain('data=');
        expect(tag.src).to.contain('modified=');

      });

      it('should call success callback if successful', function (done) {
        var successCallback = JSON.parse(treasureHelper.responses.success);

        function spyCallback () {
          if (timeoutId) {
            clearTimeout(timeoutId);
          }
          timeoutCallback();
        }

        function timeoutCallback () {
          expect(callbacks[0].calledOnce).to.equal(true);
          expect(callbacks[1].calledOnce).not.to.equal(true);
          expect(callbacks[0].calledWith(successCallback)).to.equal(true);
          done();
        }

        var timeoutId, callbacks = [sinon.spy(spyCallback), sinon.spy(spyCallback)];

        treasure.addEvent(
          treasureHelper.table,
          treasureHelper.properties,
          callbacks[0],
          callbacks[1]
        );

        timeoutId = setTimeout(timeoutCallback, treasureHelper.TIMEOUT);
      });

      it('should call error callback if unsuccessful', function (done) {

        function spyCallback () {
          if (timeoutId) {
            clearTimeout(timeoutId);
          }
          timeoutCallback();
        }

        function timeoutCallback () {
          expect(callbacks[0].calledOnce).not.to.equal(true);
          expect(callbacks[1].calledOnce).to.equal(true);
          done();
        }

        var timeoutId, callbacks = [sinon.spy(spyCallback), sinon.spy(spyCallback)];

        treasure.addEvent(
          'error',
          treasureHelper.properties,
          callbacks[0],
          callbacks[1]
        );

        timeoutId = setTimeout(timeoutCallback, treasureHelper.TIMEOUT);
      });

    });

  });
});
<commit_msg>style(tests): add space<commit_after>'use strict';

describe('Treasure Tracking', function () {
  var treasure, server, postUrl, respondWith;

  describe('#addEvent', function () {

    describe('validation', function () {

      beforeEach(function () {
        treasure = new Treasure({
          database: treasureHelper.database,
          writeKey: treasureHelper.writeKey,
          host: treasureHelper.host
        });
      });

      describe('event', function () {

        it('should error if event is absent', function () {

          expect(function () {
            treasure.addEvent(treasureHelper.table, undefined);
          }).to.throw(Error);

        });

        it('should error if event is null', function () {

          expect(function () {
            treasure.addEvent(treasureHelper.table, null);
          }).to.throw(Error);

        });

        it('should error if event is of incorrect type', function () {

          // Number
          expect(function () {
            treasure.addEvent(treasureHelper.table, 0);
          }).to.throw(Error);

          // Boolean
          expect(function () {
            treasure.addEvent(treasureHelper.table, false);
          }).to.throw(Error);

          // Array
          expect(function () {
            treasure.addEvent(treasureHelper.table, ['array']);
          }).to.throw(Error);

          // String
          expect(function () {
            treasure.addEvent(treasureHelper.table, 'String');
          }).to.throw(Error);

        });

      });

      describe('table', function () {

        it('should error if table is absent', function () {

          expect(function () {
            treasure.addEvent(undefined);
          }).to.throw(Error);

        });

        it('should error if table is empty', function () {

          expect(function () {
            treasure.addEvent('');
          }).to.throw(Error);

        });

        it('should error if table is of incorrect type', function () {

          // Number
          expect(function () {
            treasure.addEvent(0);
          }).to.throw(Error);

          // Boolean
          expect(function () {
            treasure.addEvent(false);
          }).to.throw(Error);

          // Array
          expect(function () {
            treasure.addEvent(['array']);
          }).to.throw(Error);

          // Object
          expect(function () {
            treasure.addEvent({});
          }).to.throw(Error);

        });

        it('should error if table is invalid', function () {

          // Under 3 characters
          expect(function () {
            treasure.addEvent('12');
          }).to.throw(Error);

          // Over 255 characters
          expect(function () {
            treasure.addEvent('1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111');
          }).to.throw(Error);

          // Uppercase chracters
          expect(function () {
            treasure.addEvent('FOO_BAR');
          }).to.throw(Error);

          // Special characters
          expect(function () {
            treasure.addEvent('!@#$%ˆ&*()-+=');
          }).to.throw(Error);

        });

        it('should accept a valid table', function () {
          expect(function () {
            treasure.addEvent(treasureHelper.table, {});
          }).not.to.throw(Error);
        });
      });

    });

    describe('via XHR/CORS (if supported)', function () {

      beforeEach(function () {
        treasure = new Treasure({
          database: treasureHelper.database,
          writeKey: treasureHelper.writeKey,
          host: treasureHelper.host,
          requestType: 'xhr'
        });
        postUrl = treasure.client.endpoint + '/js/v3/event/' + treasure.client.database + '/' + treasureHelper.table;
        server = sinon.fakeServer.create();
        respondWith = function (code, body) {
          server.respondWith('POST', postUrl, [code, { 'Content-Type': 'application/json'}, body]);
        };
      });

      afterEach(function () {
        server.restore();
      });

      if ('withCredentials' in new XMLHttpRequest()) {

        it('should post to the API using xhr where CORS is supported', function () {

          var successCallback = JSON.parse(treasureHelper.responses.success);

          var callbacks = [sinon.spy(), sinon.spy()];
          respondWith(200, treasureHelper.responses.success);
          treasure.addEvent(treasureHelper.table, treasureHelper.properties, callbacks[0], callbacks[1]);
          server.respond();

          expect(server.requests[0].requestBody)
            .to.equal(JSON.stringify(treasureHelper.properties));
          expect(callbacks[0].calledOnce).to.equal(true);
          expect(callbacks[0].calledWith(successCallback)).to.equal(true);
          expect(callbacks[1].calledOnce).not.to.equal(true);

        });

        it('should call the error callback on error', function () {

          var callbacks = [sinon.spy(), sinon.spy()];
          respondWith(500, treasureHelper.responses.error);
          treasure.addEvent(treasureHelper.table, treasureHelper.properties, callbacks[0], callbacks[1]);
          server.respond();

          expect(server.requests[0].requestBody)
            .to.equal(JSON.stringify(treasureHelper.properties));
          expect(callbacks[0].calledOnce).not.to.equal(true);
          expect(callbacks[1].calledOnce).to.equal(true);

        });

      }

    });

    describe('via JSONP to a fake server', function () {

      beforeEach(function () {
        treasure = new Treasure({
          database: treasureHelper.database,
          writeKey: treasureHelper.writeKey,
          host: treasureHelper.jsonphost,
          requestType: 'jsonp'
        });
      });

      it('should add a script tag with a URL that has data and modified params', function () {

        treasure.addEvent(treasureHelper.table, treasureHelper.properties);
        var tag = document.getElementById('td-js-sdk-jsonp');
        expect(tag).to.exist.and.be.an('object');
        expect(tag.src).to.contain('data=');
        expect(tag.src).to.contain('modified=');

      });

      it('should call success callback if successful', function (done) {
        var successCallback = JSON.parse(treasureHelper.responses.success);

        function spyCallback () {
          if (timeoutId) {
            clearTimeout(timeoutId);
          }
          timeoutCallback();
        }

        function timeoutCallback () {
          expect(callbacks[0].calledOnce).to.equal(true);
          expect(callbacks[1].calledOnce).not.to.equal(true);
          expect(callbacks[0].calledWith(successCallback)).to.equal(true);
          done();
        }

        var timeoutId, callbacks = [sinon.spy(spyCallback), sinon.spy(spyCallback)];

        treasure.addEvent(
          treasureHelper.table,
          treasureHelper.properties,
          callbacks[0],
          callbacks[1]
        );

        timeoutId = setTimeout(timeoutCallback, treasureHelper.TIMEOUT);
      });

      it('should call error callback if unsuccessful', function (done) {

        function spyCallback () {
          if (timeoutId) {
            clearTimeout(timeoutId);
          }
          timeoutCallback();
        }

        function timeoutCallback () {
          expect(callbacks[0].calledOnce).not.to.equal(true);
          expect(callbacks[1].calledOnce).to.equal(true);
          done();
        }

        var timeoutId, callbacks = [sinon.spy(spyCallback), sinon.spy(spyCallback)];

        treasure.addEvent(
          'error',
          treasureHelper.properties,
          callbacks[0],
          callbacks[1]
        );

        timeoutId = setTimeout(timeoutCallback, treasureHelper.TIMEOUT);
      });

    });

  });
});
<|endoftext|>


<commit_before>/* global expect, BigInt */
if (typeof BigInt === 'function') {
  describe('BigInt type', () => {
    it('should consider an instance equal to itself', () => {
      const a = BigInt(1);
      expect(a, 'to equal', a);
    });

    it('should inspect as source code', () => {
      const a = BigInt(123);
      expect(a, 'to inspect as', 'BigInt(123)');
    });
  });
}
<commit_msg>Test that a BigInt does not equal the equivalent number<commit_after>/* global expect, BigInt */
if (typeof BigInt === 'function') {
  describe('BigInt type', () => {
    it('should consider an instance equal to itself', () => {
      const a = BigInt(1);
      expect(a, 'to equal', a);
    });

    it('should not be considered equal to the equivalent number', () => {
      expect(
        () => expect(BigInt(1), 'to equal', 1),
        'to throw',
        'expected BigInt(1) to equal 1'
      );
    });

    it('should inspect as source code', () => {
      const a = BigInt(123);
      expect(a, 'to inspect as', 'BigInt(123)');
    });
  });
}
<|endoftext|>


<commit_before>'use strict';
/*jshint expr: true*/
const path = require('path');
const events = require('events');
const chai = require('chai');
const sinon = require('sinon');
const fs = require('fs-extra');
const expect = require('chai').expect;
const periodic = require('../../../index');
const periodicClass = require('../../../lib/periodicClass');
const express = require('../../../lib/init/express');
const testPathDir = path.resolve(__dirname, '../../mock/spec/periodic');
const initTestExpressPathDir = path.join(testPathDir, 'TestExpress');
const initTestExpressEndPathDir = path.join(testPathDir, 'TestExpressEnd');
chai.use(require('sinon-chai'));
chai.use(require('chai-as-promised'));

describe('Periodic Init Express', function() {
  this.timeout(10000);
  before('initialize Express test periodic dir', (done) => {
    Promise.all([
        fs.ensureDir(initTestExpressPathDir),
        fs.ensureDir(initTestExpressEndPathDir),
      ])
      .then(() => {
        done();
      }).catch(done);
  });
  describe('configureViews', () => {
    it('should handle errors', () => {
      expect(express.configureViews()).to.eventually.be.rejected;
    });
    it('sets express non ejs view with proxy options', (done) => {
      const setSpy = sinon.spy();
      const enableSpy = sinon.spy();
      const engineSpy = sinon.spy();
      const mockThis = {
        config: {
          app_root: initTestExpressPathDir,
        },
        settings: {
          express: {
            config: {
              trust_proxy: true,
            },
            views: {
              engine: 'jsx',
              lru_cache: true,
              lru: 100,
              package: 'ejs',
            }
          }
        },
        app: {
          set: setSpy,
          enable: enableSpy,
          engine: engineSpy,
          // set: setSpy,
        },
      };
      express.configureViews.call(mockThis)
        .then(result => {
          expect(result).to.be.true;
          expect(setSpy.calledTwice).to.be.true;
          expect(enableSpy.calledOnce).to.be.true;
          expect(engineSpy.calledThrice).to.be.true;
          // expect(mockThis.config.time_end).to.be.a('number');
          done();
        })
        .catch(done);
    });
    it('sets express ejs view without proxy options', (done) => {
      const setSpy = sinon.spy();
      const enableSpy = sinon.spy();
      const engineSpy = sinon.spy();
      const mockThis = {
        config: {
          app_root: initTestExpressPathDir,
        },
        settings: {
          express: {
            config: {
              trust_proxy: false,
            },
            views: {
              // engine: 'ejs',
              lru_cache: false,
              lru: 100,
              package: 'ejs',
            }
          }
        },
        app: {
          set: setSpy,
          enable: enableSpy,
          engine: engineSpy,
          // set: setSpy,
        },
      };
      express.configureViews.call(mockThis)
        .then(result => {
          expect(result).to.be.true;
          expect(setSpy.calledTwice).to.be.true;
          expect(enableSpy.called).to.not.be.true;
          expect(engineSpy.calledThrice).to.be.true;
          // expect(mockThis.config.time_end).to.be.a('number');
          done();
        })
        .catch(done);
    });
  });
  describe('configureExpress', () => {
    it('should handle errors', () => {
      expect(express.configureExpress()).to.eventually.be.rejected;
    });
  });
  describe('customizeExpress', () => {
    it('should handle errors', () => {
      expect(express.customizeExpress()).to.eventually.be.rejected;
    });
  });
  describe('staticCacheExpress', () => {
    it('should handle errors', () => {
      expect(express.staticCacheExpress()).to.eventually.be.rejected;
    });
  });
  describe('compressExpress', () => {
    it('should handle errors', () => {
      expect(express.compressExpress()).to.eventually.be.rejected;
    });
  });
  describe('logExpress', () => {
    it('should handle errors', () => {
      expect(express.logExpress()).to.eventually.be.rejected;
    });
  });
  // describe('expressSessions', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressSessions()).to.eventually.be.rejected;
  //   });
  // });
  // describe('expressLocals', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressLocals()).to.eventually.be.rejected;
  //   });
  // });
  // describe('expressRouting', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressRouting()).to.eventually.be.rejected;
  //   });
  // });
  // describe('expressStatus', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressStatus()).to.eventually.be.rejected;
  //   });
  // });
  // describe('expressErrors', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressErrors()).to.eventually.be.rejected;
  //   });
  // });
  describe('Error handling', () => {
    // it('stores intialization start time', (done) => {
    //   const mockThis = {
    //     config: {},
    //   };
    //   express.startTimer.call(mockThis)
    //     .then(result => {
    //       expect(result).to.be.true;
    //       expect(mockThis.config.time_start).to.be.a('number');
    //       done();
    //     })
    //     .catch(done);
    // });

  });
  after('remove Express test periodic dir', (done) => {
    Promise.all([
        fs.remove(initTestExpressPathDir),
        fs.remove(initTestExpressEndPathDir),
      ])
      .then(() => {
        done();
      }).catch(done);
  });
});<commit_msg>adding configured express tests<commit_after>'use strict';
/*jshint expr: true*/
const path = require('path');
const events = require('events');
const chai = require('chai');
const sinon = require('sinon');
const fs = require('fs-extra');
const expect = require('chai').expect;
const periodic = require('../../../index');
const periodicClass = require('../../../lib/periodicClass');
const express = require('../../../lib/init/express');
const testPathDir = path.resolve(__dirname, '../../mock/spec/periodic');
const folderStructure = require('../../../lib/init/folderStructure');
const initTestExpressPathDir = path.join(testPathDir, 'TestExpress');
const initTestExpressEndPathDir = path.join(testPathDir, 'TestExpressEnd');
const __STRUCTURE_DIR = path.resolve(__dirname, '../../../__STRUCTURE');
chai.use(require('sinon-chai'));
chai.use(require('chai-as-promised'));

describe('Periodic Init Express', function() {
  this.timeout(10000);
  before('initialize Express test periodic dir', (done) => {
    Promise.all([
        fs.ensureDir(initTestExpressPathDir),
        fs.ensureDir(initTestExpressEndPathDir),
        fs.copy(__STRUCTURE_DIR, initTestExpressPathDir)
      ])
      .then(() => {
        done();
      }).catch(done);
  });
  describe('configureViews', () => {
    it('should handle errors', () => {
      expect(express.configureViews()).to.eventually.be.rejected;
    });
    it('sets express non ejs view with proxy options', (done) => {
      const setSpy = sinon.spy();
      const enableSpy = sinon.spy();
      const engineSpy = sinon.spy();
      const mockThis = {
        config: {
          app_root: initTestExpressPathDir,
        },
        settings: {
          express: {
            config: {
              trust_proxy: true,
            },
            views: {
              engine: 'jsx',
              lru_cache: true,
              lru: 100,
              package: 'ejs',
            }
          }
        },
        app: {
          set: setSpy,
          enable: enableSpy,
          engine: engineSpy,
          // set: setSpy,
        },
      };
      express.configureViews.call(mockThis)
        .then(result => {
          expect(result).to.be.true;
          expect(setSpy.calledTwice).to.be.true;
          expect(enableSpy.calledOnce).to.be.true;
          expect(engineSpy.calledThrice).to.be.true;
          // expect(mockThis.config.time_end).to.be.a('number');
          done();
        })
        .catch(done);
    });
    it('sets express ejs view without proxy options', (done) => {
      const setSpy = sinon.spy();
      const enableSpy = sinon.spy();
      const engineSpy = sinon.spy();
      const mockThis = {
        config: {
          app_root: initTestExpressPathDir,
        },
        settings: {
          express: {
            config: {
              trust_proxy: false,
            },
            views: {
              // engine: 'ejs',
              lru_cache: false,
              lru: 100,
              package: 'ejs',
            }
          }
        },
        app: {
          set: setSpy,
          enable: enableSpy,
          engine: engineSpy,
          // set: setSpy,
        },
      };
      express.configureViews.call(mockThis)
        .then(result => {
          expect(result).to.be.true;
          expect(setSpy.calledTwice).to.be.true;
          expect(enableSpy.called).to.not.be.true;
          expect(engineSpy.calledThrice).to.be.true;
          // expect(mockThis.config.time_end).to.be.a('number');
          done();
        })
        .catch(done);
    });
  });
  describe('configureExpress', () => {
    it('has configurable flash settings', (done) => {
      const useSpy = sinon.spy();
      const mockThis = {
        config: {
          app_root: initTestExpressPathDir,
        },
        settings: {
          express: {
            use_flash: false,
            config: {
              trust_proxy: false,
            },
            body_parser: {
              urlencoded: {
                limit: '1mb',
                extended: true,
              },
              json: {
                limit: '1mb'
              },
            },
            cookies: {
              cookie_parser: 'defaultcookiejson',
            },
            views: {
              // engine: 'ejs',
              lru_cache: false,
              lru: 100,
              package: 'ejs',
            }
          }
        },
        app: {
          use: useSpy,
        },
      };
      express.configureExpress.call(mockThis)
        .then(result => {
          expect(result).to.be.true;
          expect(useSpy.called).to.be.true;
          // expect(enableSpy.called).to.not.be.true;
          // expect(engineSpy.calledThrice).to.be.true;
          // expect(mockThis.config.time_end).to.be.a('number');
          done();
        })
        .catch(done);
    });
    it('should handle errors', () => {
      expect(express.configureExpress()).to.eventually.be.rejected;
    });
  });
  describe('customizeExpress', () => {
    it('should handle errors', () => {
      expect(express.customizeExpress()).to.eventually.be.rejected;
    });
  });
  describe('staticCacheExpress', () => {
    it('should handle errors', () => {
      expect(express.staticCacheExpress()).to.eventually.be.rejected;
    });
  });
  describe('compressExpress', () => {
    it('should handle errors', () => {
      expect(express.compressExpress()).to.eventually.be.rejected;
    });
  });
  describe('logExpress', () => {
    it('should handle errors', () => {
      expect(express.logExpress()).to.eventually.be.rejected;
    });
  });
  // describe('expressSessions', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressSessions()).to.eventually.be.rejected;
  //   });
  // });
  // describe('expressLocals', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressLocals()).to.eventually.be.rejected;
  //   });
  // });
  // describe('expressRouting', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressRouting()).to.eventually.be.rejected;
  //   });
  // });
  // describe('expressStatus', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressStatus()).to.eventually.be.rejected;
  //   });
  // });
  // describe('expressErrors', () => {
  //   it('should handle errors', () => {
  //     expect(express.expressErrors()).to.eventually.be.rejected;
  //   });
  // });
  describe('Error handling', () => {
    // it('stores intialization start time', (done) => {
    //   const mockThis = {
    //     config: {},
    //   };
    //   express.startTimer.call(mockThis)
    //     .then(result => {
    //       expect(result).to.be.true;
    //       expect(mockThis.config.time_start).to.be.a('number');
    //       done();
    //     })
    //     .catch(done);
    // });

  });
  after('remove Express test periodic dir', (done) => {
    Promise.all([
        fs.remove(initTestExpressPathDir),
        fs.remove(initTestExpressEndPathDir),
      ])
      .then(() => {
        done();
      }).catch(done);
  });
});<|endoftext|>


<commit_before>/* eslint-disable no-unused-expressions */
import { createElement } from 'react';
import ReactTestUtils from 'react-dom/test-utils'; // ES6
import { build, plugins } from 'ladda-cache';
import sinon from 'sinon';

import { withResolve } from '.';

const delay = (t = 1) => new Promise(res => setTimeout(() => res(), t));

const createConfig = () => {
  const peter = { id: 'peter', name: 'peter' };
  const gernot = { id: 'gernot', name: 'gernot' };
  const robin = { id: 'robin', name: 'robin' };

  const users = [peter, gernot, robin].reduce((m, u) => {
    m[u.id] = u;
    return m;
  }, {});

  const getUser = (id) => Promise.resolve(users[id]);
  getUser.operation = 'READ';
  getUser.byId = true;
  const getUsers = () => Promise.resolve(Object.values(users));
  getUsers.operation = 'READ';

  const updateUser = (nextUser) => {
    const { id } = nextUser;
    const user = users[id];
    users[id] = { ...user, ...nextUser };
    return Promise.resolve(users[id]);
  };
  updateUser.operation = 'UPDATE';

  const removeUser = (id) => {
    delete users[id];
    Promise.resolve();
  };
  removeUser.operation = 'DELETE';

  return {
    user: {
      api: { getUser, getUsers, updateUser, removeUser }
    }
  };
};

const createSpyComponent = () => {
  return sinon.stub().returns(null);
};

const render = (component, props) => {
  const el = createElement(component, props);
  return ReactTestUtils.renderIntoDocument(el);
};

describe('withResolve', () => {
  it('passes the original properties down', () => {
    const api = build(createConfig());
    const spy = createSpyComponent();
    const comp = withResolve({
      resolve: {
        users: () => api.user.getUsers(),
        user: ({ userId }) => api.user.getUser(userId)
      }
    })(spy);

    render(comp, { userId: 'peter' });

    return delay().then(() => {
      expect(spy).to.have.been.called;
      const props = spy.args[0][0];
      expect(props.userId).to.equal('peter');
    });
  });
});
<commit_msg>Add spec for subscibing<commit_after>/* eslint-disable no-unused-expressions */
import { createElement } from 'react';
import ReactTestUtils from 'react-dom/test-utils'; // ES6
import { build, plugins } from 'ladda-cache';
import sinon from 'sinon';

import { withResolve } from '.';

const delay = (t = 1) => new Promise(res => setTimeout(() => res(), t));

const createConfig = () => {
  const peter = { id: 'peter', name: 'peter' };
  const gernot = { id: 'gernot', name: 'gernot' };
  const robin = { id: 'robin', name: 'robin' };

  const users = [peter, gernot, robin].reduce((m, u) => {
    m[u.id] = u;
    return m;
  }, {});

  const getUser = (id) => Promise.resolve(users[id]);
  getUser.operation = 'READ';
  getUser.byId = true;
  const getUsers = () => Promise.resolve(Object.values(users));
  getUsers.operation = 'READ';

  const updateUser = (nextUser) => {
    const { id } = nextUser;
    const user = users[id];
    users[id] = { ...user, ...nextUser };
    return Promise.resolve(users[id]);
  };
  updateUser.operation = 'UPDATE';

  const removeUser = (id) => {
    delete users[id];
    Promise.resolve();
  };
  removeUser.operation = 'DELETE';

  return {
    user: {
      api: { getUser, getUsers, updateUser, removeUser }
    }
  };
};

const createSpyComponent = () => {
  return sinon.stub().returns(null);
};

const render = (component, props) => {
  const el = createElement(component, props);
  return ReactTestUtils.renderIntoDocument(el);
};

describe('withResolve', () => {
  it('passes the original properties down', () => {
    const api = build(createConfig());
    const spy = createSpyComponent();
    const comp = withResolve({
      resolve: {
        users: () => api.user.getUsers(),
        user: ({ userId }) => api.user.getUser(userId)
      }
    })(spy);

    render(comp, { userId: 'peter' });

    return delay().then(() => {
      expect(spy).to.have.been.called;
      const props = spy.args[0][0];
      expect(props.userId).to.equal('peter');
    });
  });

  it('allows to subscribe to changes', () => {
    const api = build(createConfig(), [plugins.subscriber()]);
    const spy = createSpyComponent();
    const comp = withResolve({
      subscribe: {
        user: ({ userId }) => api.user.getUser.createSubscriber().withArgs(userId)
      }
    })(spy);

    render(comp, { userId: 'peter' });

    return delay().then(() => {
      expect(spy).to.have.been.calledOnce;
      const firstProps = spy.args[0][0];
      expect(firstProps.user).to.deep.equal({ id: 'peter', name: 'peter' });

      return api.user.updateUser({ id: 'peter', name: 'crona' }).then((nextUser) => {
        expect(spy).to.have.been.calledTwice;
        const secondProps = spy.args[1][0];
        expect(secondProps.user).to.deep.equal(nextUser);
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Created by Administrator on 2015/5/20.
 */
angular.module('RDash')
.factory('Info',['$resource',function($resource){
        return $resource('/api/user/info/:action/:uid',{},{
            'update':{isArray:false,method:'POST'},
            'get':{isArray:false,method:'GET'}
        })
    }])<commit_msg>infofactory的模块名未写对，更改之<commit_after>/**
 * Created by Administrator on 2015/5/20.
 */
angular.module('Home')
.factory('Info',['$resource',function($resource){
        return $resource('/api/user/info/:action/:uid',{},{
            'update':{isArray:false,method:'POST'},
            'get':{isArray:false,method:'GET'}
        })
    }])<|endoftext|>