<commit_before>define(function (require) {

  var React = require('react/addons'),
    Backbone = require('backbone'),
    actions = require('actions'),
    modals = require('modals'),
    MaintenanceMessageBanner = require('./MaintenanceMessageBanner.react'),
    Router = require('react-router'),

  // plugin: required to enable the drop-down, but not used directly
    bootstrap = require('bootstrap');

  var Link = Router.Link;

  var links = [
    {
      name: "Dashboard",
      linksTo: "dashboard",
      href: "/application/dashboard",
      icon: "stats",
      requiresLogin: true
    },
    {
      name: "Projects",
      linksTo: "projects",
      href: "/application/projects",
      icon: "folder-open",
      requiresLogin: true
    },
    {
      name: "Images",
      linksTo: "images",
      href: "/application/images",
      icon: "floppy-disk",
      requiresLogin: false
    },
    {
      name: "Providers",
      linksTo: "providers",
      href: "/application/providers",
      icon: "cloud",
      requiresLogin: true
    },
    {
      name: "Help",
      linksTo: "help",
      href: "/application/help",
      icon: "question-sign",
      requiresLogin: false
    },
    {
      name: "Admin",
      linksTo: "admin",
      icon: "cog",
      requiresLogin: true,
      requiresStaff: true
    },
    {
      name: "Badges",
      linksTo: "my-badges",
      href: "/application/badges",
      icon: "star",
      requiresLogin: true,
      requiresStaff: false
    }
  ];

  var LoginLink = React.createClass({
    render: function () {
      return (

          Login

      );
    }
  });

  var LogoutLink = React.createClass({

    propTypes: {
      username: React.PropTypes.string.isRequired
    },

    onShowVersion: function (e) {
      e.preventDefault();
      modals.VersionModals.showVersion();
    },

    render: function () {
      return (

            {this.props.username}

              <Link to="settings">Settings</Link>

              Version

              Status

              Sign out

      );
    }
  });

  var Header = React.createClass({

    propTypes: {
      profile: React.PropTypes.instanceOf(Backbone.Model),
      currentRoute: React.PropTypes.array.isRequired
    },

    renderBetaToggle: function () {
      if (!window.show_troposphere_only) {
        return (

View Old UI

        )
      }
    },

    render: function () {

      var profile = this.props.profile;
      var loginLogoutDropdown = profile ? <LogoutLink username={profile.get('username')}/> : <LoginLink/>;

      if (!profile) {
        links = links.filter(function (link) {
          return !link.requiresLogin;
        })
      } else {
        links = links.filter(function (link) {
          if (link.requiresStaff) return profile.get('is_staff');
          return true;
        })
      }

      var navLinks = links.map(function (link) {
        var isCurrentRoute = (link.name.toLowerCase() === this.props.currentRoute[0]);
        var className = isCurrentRoute ? "active" : null;
        return (

            <Link to={link.linksTo}>

              {link.name}
            </Link>

        );
      }.bind(this));

      var brandLink;
      if (profile) {
        brandLink = <Link to="dashboard" className="navbar-brand"/>;
      } else {
        brandLink = <Link to="images" className="navbar-brand"/>;
      }

      return (

          <MaintenanceMessageBanner maintenanceMessages={this.props.maintenanceMessages}/>

              <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

              </button>
              {brandLink}

                {navLinks}

                {this.renderBetaToggle()}
                {loginLogoutDropdown}

      );

    }
  });

  return Header;

});
<commit_msg>add "isEnabled" field to header menu items<commit_after>define(function (require) {

  var React = require('react/addons'),
    Backbone = require('backbone'),
    actions = require('actions'),
    modals = require('modals'),
    MaintenanceMessageBanner = require('./MaintenanceMessageBanner.react'),
    Router = require('react-router'),

  // plugin: required to enable the drop-down, but not used directly
    bootstrap = require('bootstrap');

  var Link = Router.Link;

  var all_links = [
    {
      name: "Dashboard",
      linksTo: "dashboard",
      href: "/application/dashboard",
      icon: "stats",
      requiresLogin: true,
      isEnabled: true
    },
    {
      name: "Projects",
      linksTo: "projects",
      href: "/application/projects",
      icon: "folder-open",
      requiresLogin: true,
      isEnabled: true
    },
    {
      name: "Images",
      linksTo: "images",
      href: "/application/images",
      icon: "floppy-disk",
      requiresLogin: false,
      isEnabled: true
    },
    {
      name: "Providers",
      linksTo: "providers",
      href: "/application/providers",
      icon: "cloud",
      requiresLogin: true,
      isEnabled: true
    },
    {
      name: "Help",
      linksTo: "help",
      href: "/application/help",
      icon: "question-sign",
      requiresLogin: false,
      isEnabled: true
    },
    {
      name: "Admin",
      linksTo: "admin",
      icon: "cog",
      requiresLogin: true,
      requiresStaff: true,
      isEnabled: true
    },
    {
      name: "Badges",
      linksTo: "my-badges",
      href: "/application/badges",
      icon: "star",
      requiresLogin: true,
      requiresStaff: false,
      isEnabled: true
    }
  ];

  var LoginLink = React.createClass({
    render: function () {
      return (

          Login

      );
    }
  });

  var LogoutLink = React.createClass({

    propTypes: {
      username: React.PropTypes.string.isRequired
    },

    onShowVersion: function (e) {
      e.preventDefault();
      modals.VersionModals.showVersion();
    },

    render: function () {
      return (

            {this.props.username}

              <Link to="settings">Settings</Link>

              Version

              Status

              Sign out

      );
    }
  });

  var Header = React.createClass({

    propTypes: {
      profile: React.PropTypes.instanceOf(Backbone.Model),
      currentRoute: React.PropTypes.array.isRequired
    },

    renderBetaToggle: function () {
      if (!window.show_troposphere_only) {
        return (

View Old UI

        )
      }
    },

    render: function () {
      var profile = this.props.profile;
      var loginLogoutDropdown = profile ? <LogoutLink username={profile.get('username')}/> : <LoginLink/>;
      var badgesEnabled = profile.get('badges_enabled');

      if (!profile) {
        links = all_links.filter(function (link) {
          return !link.requiresLogin && link.isEnabled;
        })
      } else {
        links = all_links.filter(function (link) {
          if (link.requiresStaff) return profile.get('is_staff');
          return link.isEnabled;
        })
      }
      for (link in all_links){
        if (all_links[link].name == "Badges"){
            all_links[link].isEnabled = badgesEnabled;
        }
      }

      var navLinks = links.map(function (link) {
        var isCurrentRoute = (link.name.toLowerCase() === this.props.currentRoute[0]);
        var className = isCurrentRoute ? "active" : null;
        return (

            <Link to={link.linksTo}>

              {link.name}
            </Link>

        );
      }.bind(this));

      var brandLink;
      if (profile) {
        brandLink = <Link to="dashboard" className="navbar-brand"/>;
      } else {
        brandLink = <Link to="images" className="navbar-brand"/>;
      }

      return (

          <MaintenanceMessageBanner maintenanceMessages={this.props.maintenanceMessages}/>

              <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

              </button>
              {brandLink}

                {navLinks}

                {this.renderBetaToggle()}
                {loginLogoutDropdown}

      );

    }
  });

  return Header;

});
<|endoftext|>


<commit_before>/**
 * @fileOverview Testers common library.
 */

var sinon = require('sinon');

var chai = require('chai');
var sinonChai = require('sinon-chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
chai.use(sinonChai);

var tester = module.exports = {};

/**
 * Returns A stub Entity to perform tests on.
 *
 * @return {Function} A stub Entity Ctor.
 */
tester.entity = function() {
  var item = {a: 1};

  var Entity = function () {
    this.__item = item;
  };

  Entity.prototype.create = sinon.stub().returns(item);
  Entity.prototype.read = sinon.stub().returns([item]);
  Entity.prototype.readLimit = sinon.stub().returns([item]);
  Entity.prototype.readOne = sinon.stub().returns(item);
  Entity.prototype.update = sinon.stub().returns(item);
  Entity.prototype.count = sinon.stub().returns(1);
  Entity.prototype.delete = sinon.stub().returns(item);

  return Entity;
};

/**
 * Return express Request / Response objects.
 *
 * @return {Object} Req Res mocks.
 */
tester.reqres = function() {
  var reqres = {
    req: {
      query: {},
      body: {},
      params: {},
      url: 'http://localhost/',
      app: {
        settings: {
          port: 80,
        },
      },
    },
    res: {
      status: sinon.mock(),
      set: sinon.mock(),
      json: sinon.mock(),
    },
  };

  reqres.res.status.returns(reqres.res);

  return reqres;
};
<commit_msg>switch mocks to stubs in req/res mocks<commit_after>/**
 * @fileOverview Testers common library.
 */

var sinon = require('sinon');

var chai = require('chai');
var sinonChai = require('sinon-chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
chai.use(sinonChai);

var tester = module.exports = {};

/**
 * Returns A stub Entity to perform tests on.
 *
 * @return {Function} A stub Entity Ctor.
 */
tester.entity = function() {
  var item = {a: 1};

  var Entity = function () {
    this.__item = item;
  };

  Entity.prototype.create = sinon.stub().returns(item);
  Entity.prototype.read = sinon.stub().returns([item]);
  Entity.prototype.readLimit = sinon.stub().returns([item]);
  Entity.prototype.readOne = sinon.stub().returns(item);
  Entity.prototype.update = sinon.stub().returns(item);
  Entity.prototype.count = sinon.stub().returns(1);
  Entity.prototype.delete = sinon.stub().returns(item);

  return Entity;
};

/**
 * Return express Request / Response objects.
 *
 * @return {Object} Req Res mocks.
 */
tester.reqres = function() {
  var reqres = {
    req: {
      query: {},
      body: {},
      params: {},
      url: 'http://localhost/',
      app: {
        settings: {
          port: 80,
        },
      },
    },
    res: {
      status: sinon.stub(),
      set: sinon.stub(),
      json: sinon.stub(),
    },
  };

  reqres.res.status.returns(reqres.res);

  return reqres;
};
<|endoftext|>


<commit_before>define(function (require) {

  var Promise = require("cherrytree/vendor/promise");
  var Router = require("cherrytree");
  var Route = require("cherrytree/route");
  var HistoryLocation = require("cherrytree/locations/history");

  var delay = function (time) {
    return new Promise(function (resolve) {
      setTimeout(resolve, time);
    });
  };

  var router, sequence = [];

  var BaseRoute = Route.extend({
    model: function () {
      sequence.push("model " + this.name);
      return delay(30);
    },
    initialize: function () {
      sequence.push("initialize " + this.name);
    },
    activate: function () {
      sequence.push("activate " + this.name);
    },
    deactivate: function () {
      sequence.push("deactivate " + this.name);
    }
  });

  describe("route lifecycle", function () {

    beforeEach(function (done) {
      window.location.hash = "/";
      router = new Router({
        location: new HistoryLocation(),
        BaseRoute: BaseRoute
      });

      // provide the route map
      router.map(function () {
        this.route("about");
        this.resource("posts", function () {
          this.route("popular");
          this.route("latest");
          this.route("best");
          this.route("show", {path: "/:postId"});
          this.resource("postsAdmin", function () {
            this.route("create", {queryParams: ["templateId"]});
          });
        });
        this.resource("account", {path: "/:accountId"}, function () {
          this.resource("settings", function () {
            this.route("password");
            this.route("photo", {queryParams: ["size"]});
            this.route("permissions", {path: "/:setId"});
          });
        });
      });

      router.routes["postsAdmin.create"] = BaseRoute.extend({
        update: function () {
          sequence.push("update " + this.name);
        },
        queryParamsDidChange: function () {
          this.refresh();
        }
      });

      router.routes["settings.photo"] = BaseRoute.extend({
        update: function () {
          sequence.push("update " + this.name);
        },
        queryParamsDidChange: function () {
          this.refresh();
        }
      });

      router.startRouting().then(done, done);
    });

    afterEach(function () {
      router.destroy();
    });

    it("should handle rapid retransitioning", function (done) {
      router.routes["posts.show"] = BaseRoute.extend({
        initialize: function () {
          sequence.push("initialize " + this.name);
        },
        model: function (params) {
          sequence.push("model " + this.name + " " + params.postId);
          this.setContext(params);
          return delay(30);
        },
        activate: function (context) {
          this.postId = context.postId;
          sequence.push("activate " + this.name + " " + context.postId);
        },
        deactivate: function () {
          sequence.push("deactivate " + this.name + " " + this.postId);
        }
      });
      router.transitionTo("about").then(function () {
        sequence = [];
        router.transitionTo("posts.show", 1);
        return delay(60);
      }).then(function () {
        router.transitionTo("posts.show", 2);
        return delay(10);
      }).then(function () {
        return router.transitionTo("posts.show", 3);
      }).then(function () {
        return router.transitionTo("posts.show", 4);
      }).then(function () {
        sequence.should.deep.equal([
          'initialize posts',
          'model posts',
          'initialize posts.show',
          'model posts.show 1',
          'model posts.show 2',
          'model posts.show 3',
          'deactivate about',
          'activate posts',
          'activate posts.show 3',
          'model posts.show 4',
          'deactivate posts.show 3',
          'activate posts.show 4',
        ]);
      }).then(done, done);
    });

    it("should deactivate all abandoned states when changing target route midst transition", function (done) {
      router.transitionTo("about").then(function () {
        sequence = [];
        router.transitionTo("posts.popular");
        return delay(50);
      }).then(function () {
        router.transitionTo("posts.latest");
        return delay(20);
      }).then(function () {
        return router.transitionTo("posts.best");
      }).then(function () {
        sequence.should.deep.equal([
          'initialize posts',
          'model posts',
          'initialize posts.popular',
          'model posts.popular',
          'initialize posts.latest',
          'model posts.latest',
          'initialize posts.best',
          'model posts.best',
          'deactivate about',
          'activate posts',
          'activate posts.best'
        ]);
      }).then(done, done);
    });

    describe("update hook", function () {
      it("should be able to prevent the route from exiting", function (done) {
        router.transitionTo("postsAdmin.create", {queryParams: {templateId: 1}}).then(function () {
          sequence = [];
          return router.transitionTo("postsAdmin.create", {queryParams: {templateId: 2}});
        }).then(function () {
          sequence.should.deep.equal([
            'model postsAdmin.create',
            'update postsAdmin.create'
          ]);
        }).then(done, done);
      });
    });

    describe("optional transitionTo params", function () {
      it("should be possible to list all params", function (done) {
        router.transitionTo("settings.permissions", 1, 2).then(function () {
          sequence = [];
          return router.transitionTo("settings.permissions", 1, 3);
        }).then(function () {
          sequence.should.deep.equal([
            'model settings.permissions',
            'deactivate settings.permissions',
            'activate settings.permissions'
          ]);
        }).then(done, done);
      });
      it("should be possible to skip parent route params", function (done) {
        router.transitionTo("settings.permissions", 1, 2).then(function () {
          sequence = [];
          return router.transitionTo("settings.permissions", 3);
        }).then(function () {
          sequence.should.deep.equal([
            'model settings.permissions',
            'deactivate settings.permissions',
            'activate settings.permissions'
          ]);
        }).then(done, done);
      });
    });

    describe("upstream route changing context", function () {
      it("should reactivate the child routes", function (done) {
        router.transitionTo("settings.password", 1).then(function () {
          sequence = [];
          return router.transitionTo("settings.password", 2);
        }).then(function () {
          sequence.should.deep.equal([
            'model account',
            'model settings',
            'model settings.password',
            'deactivate account',
            'activate account',
            'deactivate settings',
            'activate settings',
            'deactivate settings.password',
            'activate settings.password'
          ]);
        }).then(done, done);
      });

      it("should reactivate the child routes with update function", function (done) {
        router.transitionTo("settings.photo", 1).then(function () {
          sequence = [];
          return router.transitionTo("settings.photo", {queryParams: {size: 24}});
        }).then(function () {
          sequence.should.deep.equal([
            'model settings.photo',
            'update settings.photo'
          ]);
          sequence = [];
          return router.transitionTo("settings.photo", 2);
        }).then(function () {
          sequence.should.deep.equal([
            'model account',
            'model settings',
            'model settings.photo',
            'deactivate account',
            'activate account',
            'deactivate settings',
            'activate settings',
            'deactivate settings.photo',
            'activate settings.photo'
          ]);
        }).then(done, done);
      });
    });

    describe("only changing params", function () {
      it("should still deactivate the previous state with the same name", function (done) {
        router.routes["posts.show"] = BaseRoute.extend({
          initialize: function () {
            sequence.push("initialize " + this.name);
          },
          model: function (params) {
            this.postId = params.postId;
            sequence.push("model " + this.name + " " + this.postId);
            this.setContext(params);
            return delay(30);
          },
          activate: function (context) {
            sequence.push("activate " + this.name + " " + context.postId);
          },
          deactivate: function () {
            sequence.push("deactivate " + this.name);
          }
        });
        router.transitionTo("about").then(function () {
          sequence = [];
          return router.transitionTo("posts.show", 1);
        }).then(function () {
          return router.transitionTo("posts.show", 2);
        }).then(function () {
          sequence.should.deep.equal([
            'initialize posts',
            'model posts',
            'initialize posts.show',
            'model posts.show 1',
            'deactivate about',
            'activate posts',
            'activate posts.show 1',
            'model posts.show 2',
            'deactivate posts.show',
            'activate posts.show 2',
          ]);
        }).then(done, done);
      });
    });

    describe("check for identical transitions", function () {
      it("should fail when params have changed", function (done) {
        var t1, t2;
        router.transitionTo("posts.show", 1).then(function () {
          t1 = router.transitionTo("posts.show", 2);
          return delay(10);
        }).then(function () {
          // we can also transition via URL
          t2 = router.transitionTo("posts.show", 3);
          return t2;
        }).then(function () {
          t1.should.not.equal(t2);
        }).then(done, done);
      });
    });

  });

});<commit_msg>Make tests faster - reduce the number and duration of timeouts<commit_after>define(function (require) {

  var Promise = require("cherrytree/vendor/promise");
  var Router = require("cherrytree");
  var Route = require("cherrytree/route");

  var delay = function (time) {
    return new Promise(function (resolve) {
      setTimeout(resolve, time);
    });
  };

  var router, sequence = [];

  var BaseRoute = Route.extend({
    model: function () {
      sequence.push("model " + this.name);
      return delay(10);
    },
    initialize: function () {
      sequence.push("initialize " + this.name);
    },
    activate: function () {
      sequence.push("activate " + this.name);
    },
    deactivate: function () {
      sequence.push("deactivate " + this.name);
    }
  });

  describe("route lifecycle", function () {

    beforeEach(function (done) {
      router = new Router({
        BaseRoute: BaseRoute
      });

      // provide the route map
      router.map(function () {
        this.route("about");
        this.resource("posts", function () {
          this.route("popular");
          this.route("latest");
          this.route("best");
          this.route("show", {path: "/:postId"});
          this.resource("postsAdmin", function () {
            this.route("create", {queryParams: ["templateId"]});
          });
        });
        this.resource("account", {path: "/:accountId"}, function () {
          this.resource("settings", function () {
            this.route("password");
            this.route("photo", {queryParams: ["size"]});
            this.route("permissions", {path: "/:setId"});
          });
        });
      });

      router.routes["postsAdmin.create"] = BaseRoute.extend({
        update: function () {
          sequence.push("update " + this.name);
        },
        queryParamsDidChange: function () {
          this.refresh();
        }
      });

      router.routes["settings.photo"] = BaseRoute.extend({
        update: function () {
          sequence.push("update " + this.name);
        },
        queryParamsDidChange: function () {
          this.refresh();
        }
      });

      router.startRouting().then(done, done);
    });

    afterEach(function () {
      router.destroy();
    });

    it("should handle rapid retransitioning", function (done) {
      router.routes["posts.show"] = BaseRoute.extend({
        initialize: function () {
          sequence.push("initialize " + this.name);
        },
        model: function (params) {
          sequence.push("model " + this.name + " " + params.postId);
          this.setContext(params);
          return delay(10);
        },
        activate: function (context) {
          this.postId = context.postId;
          sequence.push("activate " + this.name + " " + context.postId);
        },
        deactivate: function () {
          sequence.push("deactivate " + this.name + " " + this.postId);
        }
      });
      router.transitionTo("about").then(function () {
        sequence = [];
        router.transitionTo("posts.show", 1);
        return delay(20);
      }).then(function () {
        router.transitionTo("posts.show", 2);
        return delay(5);
      }).then(function () {
        return router.transitionTo("posts.show", 3);
      }).then(function () {
        return router.transitionTo("posts.show", 4);
      }).then(function () {
        sequence.should.deep.equal([
          'initialize posts',
          'model posts',
          'initialize posts.show',
          'model posts.show 1',
          'model posts.show 2',
          'model posts.show 3',
          'deactivate about',
          'activate posts',
          'activate posts.show 3',
          'model posts.show 4',
          'deactivate posts.show 3',
          'activate posts.show 4',
        ]);
      }).then(done, done);
    });

    it("should deactivate all abandoned states when changing target route midst transition", function (done) {
      router.transitionTo("about").then(function () {
        sequence = [];
        router.transitionTo("posts.popular");
        return delay(20);
      }).then(function () {
        router.transitionTo("posts.latest");
        return delay(2);
      }).then(function () {
        return router.transitionTo("posts.best");
      }).then(function () {
        sequence.should.deep.equal([
          'initialize posts',
          'model posts',
          'initialize posts.popular',
          'model posts.popular',
          'initialize posts.latest',
          'model posts.latest',
          'initialize posts.best',
          'model posts.best',
          'deactivate about',
          'activate posts',
          'activate posts.best'
        ]);
      }).then(done, done);
    });

    describe("update hook", function () {
      it("should be able to prevent the route from exiting", function (done) {
        router.transitionTo("postsAdmin.create", {queryParams: {templateId: 1}}).then(function () {
          sequence = [];
          return router.transitionTo("postsAdmin.create", {queryParams: {templateId: 2}});
        }).then(function () {
          sequence.should.deep.equal([
            'model postsAdmin.create',
            'update postsAdmin.create'
          ]);
        }).then(done, done);
      });
    });

    describe("optional transitionTo params", function () {
      it("should be possible to list all params", function (done) {
        router.transitionTo("settings.permissions", 1, 2).then(function () {
          sequence = [];
          return router.transitionTo("settings.permissions", 1, 3);
        }).then(function () {
          sequence.should.deep.equal([
            'model settings.permissions',
            'deactivate settings.permissions',
            'activate settings.permissions'
          ]);
        }).then(done, done);
      });
      it("should be possible to skip parent route params", function (done) {
        router.transitionTo("settings.permissions", 1, 2).then(function () {
          sequence = [];
          return router.transitionTo("settings.permissions", 3);
        }).then(function () {
          sequence.should.deep.equal([
            'model settings.permissions',
            'deactivate settings.permissions',
            'activate settings.permissions'
          ]);
        }).then(done, done);
      });
    });

    describe("upstream route changing context", function () {
      it("should reactivate the child routes", function (done) {
        router.transitionTo("settings.password", 1).then(function () {
          sequence = [];
          return router.transitionTo("settings.password", 2);
        }).then(function () {
          sequence.should.deep.equal([
            'model account',
            'model settings',
            'model settings.password',
            'deactivate account',
            'activate account',
            'deactivate settings',
            'activate settings',
            'deactivate settings.password',
            'activate settings.password'
          ]);
        }).then(done, done);
      });

      it("should reactivate the child routes with update function", function (done) {
        router.transitionTo("settings.photo", 1).then(function () {
          sequence = [];
          return router.transitionTo("settings.photo", {queryParams: {size: 24}});
        }).then(function () {
          sequence.should.deep.equal([
            'model settings.photo',
            'update settings.photo'
          ]);
          sequence = [];
          return router.transitionTo("settings.photo", 2);
        }).then(function () {
          sequence.should.deep.equal([
            'model account',
            'model settings',
            'model settings.photo',
            'deactivate account',
            'activate account',
            'deactivate settings',
            'activate settings',
            'deactivate settings.photo',
            'activate settings.photo'
          ]);
        }).then(done, done);
      });
    });

    describe("only changing params", function () {
      it("should still deactivate the previous state with the same name", function (done) {
        router.routes["posts.show"] = BaseRoute.extend({
          initialize: function () {
            sequence.push("initialize " + this.name);
          },
          model: function (params) {
            this.postId = params.postId;
            sequence.push("model " + this.name + " " + this.postId);
            this.setContext(params);
          },
          activate: function (context) {
            sequence.push("activate " + this.name + " " + context.postId);
          },
          deactivate: function () {
            sequence.push("deactivate " + this.name);
          }
        });
        router.transitionTo("about").then(function () {
          sequence = [];
          return router.transitionTo("posts.show", 1);
        }).then(function () {
          return router.transitionTo("posts.show", 2);
        }).then(function () {
          sequence.should.deep.equal([
            'initialize posts',
            'model posts',
            'initialize posts.show',
            'model posts.show 1',
            'deactivate about',
            'activate posts',
            'activate posts.show 1',
            'model posts.show 2',
            'deactivate posts.show',
            'activate posts.show 2',
          ]);
        }).then(done, done);
      });
    });

    describe("check for identical transitions", function () {
      it("should fail when params have changed", function (done) {
        var t1, t2;
        router.transitionTo("posts.show", 1).then(function () {
          t1 = router.transitionTo("posts.show", 2);
          return t1;
        }).then(function () {
          t2 = router.transitionTo("posts.show", 3);
          return t2;
        }).then(function () {
          t1.should.not.equal(t2);
        }).then(done, done);
      });
    });

  });

});<|endoftext|>


<commit_before>/**
 * express-restify-mongoose.js
 *
 * Copyright (C) 2013 by Florian Holzapfel
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
**/
var util = require('util');

var restify = function(app, model, options) {
	if(!options) {
		options = { };
	}
	if(!options.prefix) {
		options.prefix = "/api";
	}
  if( ( typeof options.plural === "undefined" ) || ( options.plural === null ) ) {
    options.plural = true
  }
	if(!options.version) {
		options.version = "/v1";
	}
  if(options.middleware) {
		if(!options.middleware instanceof Array) {
			var m = options.middleware;
			options.middleware = [ m ];
		}
	} else {
		options.middleware = [];
	}
    options.middleware.unshift(cleanQuery);

    var queryOptions = {protected: ["skip", "limit", "sort", "populate"], current: {}};

    var apiUri = options.plural === true ? "%s%s/%ss" : "%s%s/%s"

  	var uri_items = util.format(apiUri, options.prefix, options.version, model.modelName);
  	var uri_item = util.format(apiUri + '/:id', options.prefix, options.version, model.modelName);

    function cleanQuery(req, res, next) {
        queryOptions.current = {};
        for(var key in req.query) {
            if(!model.schema.paths.hasOwnProperty(key)) {
                if(queryOptions.protected.indexOf(key) != -1) {
                    queryOptions.current[key] = req.query[key];
                }
                delete req.query[key];
            }
        }
        next();
    }

	function buildQuery(query, options) {
		for(var key in options) {
            query.where(key);

            var value = options[key];
            if('>' == value[0]) {
                if('=' == value[1]) {
                    query.gte(value.substr(2));
                } else {
                    query.gt(value.substr(1));
                }
            }
            else if('<' == value[0]) {
                if('=' == value[1]) {
                    query.lte(value.substr(2));
                } else {
                    query.lt(value.substr(1));
                }
            } else {
                query.equals(value);
            }
		}

		if(queryOptions.current.skip) {
			query.skip(queryOptions.current.skip);
		}
		if(queryOptions.current.limit) {
			query.limit(queryOptions.current.limit);
		}
		if(queryOptions.current.sort) {
			query.sort(queryOptions.current.sort);
		}
		if(queryOptions.current.populate) {
			var arr = queryOptions.current.populate.split(',');
			for(var i = 0; i < arr.length; ++i) {
				query = query.populate(arr[i]);
			}
		}

		return query;
	}

	function ensureContentType(req, res, next) {
		var ct = req.get('Content-Type');
		if(-1 == ct.indexOf('application/json')) {
			res.send(400, 'Bad request');
		} else {
			next();
		}
	}
	function createObject(req, res) {
		model.create(req.body, function(err, item) {
			if(err) {
				res.send(400, 'Bad request');
			} else {
				res.type('json');
				res.send(JSON.stringify(item));
			}
		});
	}
	function modifyObject(req, res) {
		delete req.body._id;
		delete req.body.__v;

		model.findOneAndUpdate({ _id: res.req.param('id') }, req.body, {}, function(err, item) {
			if(err) {
				console.log(err);
				res.send(404, 'Not found');
			} else {
				res.type('json');
				res.send(JSON.stringify(item));
			}
		});
	}

	var write_middleware = options.middleware.slice(0);
	write_middleware.push(ensureContentType);

	app.get(uri_items, options.middleware, function(req, res) {
        buildQuery(model.find(), req.query).exec(function(err, items) {
			if(err) {
				res.send(400, 'Bad request');
			} else {
				res.type('json');
				res.send(JSON.stringify(items));
			}
		});
	});
	app.post(uri_items, write_middleware, createObject);
	app.put(uri_items, write_middleware, createObject);
	app.delete(uri_items, options.middleware, function(req, res) {
		buildQuery(model.find(), req.query).remove(function(err) {
			if(err) {
				res.send(400, 'Bad request');
			} else {
				res.send(200, 'Ok');
			}
		});
	});
	app.get(uri_item, options.middleware, function(req, res) {
		buildQuery(model.findById(res.req.param('id')), req.query).findOne(function(err, item) {
			if(err) {
				res.send(404, 'Not found');
			} else {
				res.type('json');
				res.send(JSON.stringify(item));
			}
		});
	});
	app.post(uri_item, write_middleware, modifyObject);
	app.put(uri_item, write_middleware, modifyObject);
	app.delete(uri_item, options.middleware, function(req, res) {
		model.remove({ _id: res.req.param('id') }, function(err) {
			if(err) {
				res.send(404, 'Not found');
			} else {
				res.send(200, 'Ok');
			}
		});
	});
};

module.exports.serve = restify;
<commit_msg>added support for querying a key's value using regular expressions<commit_after>/**
 * express-restify-mongoose.js
 *
 * Copyright (C) 2013 by Florian Holzapfel
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/
 var util = require('util');

 var restify = function(app, model, options) {
 	if(!options) {
 		options = { };
 	}
 	if(!options.prefix) {
 		options.prefix = "/api";
 	}
 	if( ( typeof options.plural === "undefined" ) || ( options.plural === null ) ) {
 		options.plural = true
 	}
 	if(!options.version) {
 		options.version = "/v1";
 	}
 	if(options.middleware) {
 		if(!options.middleware instanceof Array) {
 			var m = options.middleware;
 			options.middleware = [ m ];
 		}
 	} else {
 		options.middleware = [];
 	}
 	options.middleware.unshift(cleanQuery);

 	var queryOptions = {protected: ["skip", "limit", "sort", "populate"], current: {}};

 	var apiUri = options.plural === true ? "%s%s/%ss" : "%s%s/%s"

 	var uri_items = util.format(apiUri, options.prefix, options.version, model.modelName);
 	var uri_item = util.format(apiUri + '/:id', options.prefix, options.version, model.modelName);

 	function cleanQuery(req, res, next) {
 		queryOptions.current = {};
 		for(var key in req.query) {
 			if(!model.schema.paths.hasOwnProperty(key)) {
 				if(queryOptions.protected.indexOf(key) != -1) {
 					queryOptions.current[key] = req.query[key];
 				}
 				delete req.query[key];
 			}
 		}
 		next();
 	}

 	function buildQuery(query, options) {
 		for(var key in options) {
 			query.where(key);
 			var value = options[key];

 			if('~' == value[0]) {
				re = new RegExp(value.substring(1), 'i');
				query.where(key).regex(re);
 			} else if('>' == value[0]) {
 				if('=' == value[1]) {
 					query.gte(value.substr(2));
 				} else {
 					query.gt(value.substr(1));
 				}
 			} else if('<' == value[0]) {
 				if('=' == value[1]) {
 					query.lte(value.substr(2));
 				} else {
 					query.lt(value.substr(1));
 				}
 			} else {
 				query.equals(value);
 			}
 		}

 		if(queryOptions.current.skip) {
 			query.skip(queryOptions.current.skip);
 		}
 		if(queryOptions.current.limit) {
 			query.limit(queryOptions.current.limit);
 		}
 		if(queryOptions.current.sort) {
 			query.sort(queryOptions.current.sort);
 		}
 		if(queryOptions.current.populate) {
 			var arr = queryOptions.current.populate.split(',');
 			for(var i = 0; i < arr.length; ++i) {
 				query = query.populate(arr[i]);
 			}
 		}

 		return query;
 	}

 	function ensureContentType(req, res, next) {
 		var ct = req.get('Content-Type');
 		if(-1 == ct.indexOf('application/json')) {
 			res.send(400, 'Bad request');
 		} else {
 			next();
 		}
 	}
 	function createObject(req, res) {
 		model.create(req.body, function(err, item) {
 			if(err) {
 				res.send(400, 'Bad request');
 			} else {
 				res.type('json');
 				res.send(JSON.stringify(item));
 			}
 		});
 	}
 	function modifyObject(req, res) {
 		delete req.body._id;
 		delete req.body.__v;

 		model.findOneAndUpdate({ _id: res.req.param('id') }, req.body, {}, function(err, item) {
 			if(err) {
 				console.log(err);
 				res.send(404, 'Not found');
 			} else {
 				res.type('json');
 				res.send(JSON.stringify(item));
 			}
 		});
 	}

 	var write_middleware = options.middleware.slice(0);
 	write_middleware.push(ensureContentType);

 	app.get(uri_items, options.middleware, function(req, res) {
 		buildQuery(model.find(), req.query).exec(function(err, items) {
 			if(err) {
 				res.send(400, 'Bad request');
 			} else {
 				res.type('json');
 				res.send(JSON.stringify(items));
 			}
 		});
 	});
 	app.post(uri_items, write_middleware, createObject);
 	app.put(uri_items, write_middleware, createObject);
 	app.delete(uri_items, options.middleware, function(req, res) {
 		buildQuery(model.find(), req.query).remove(function(err) {
 			if(err) {
 				res.send(400, 'Bad request');
 			} else {
 				res.send(200, 'Ok');
 			}
 		});
 	});
 	app.get(uri_item, options.middleware, function(req, res) {
 		buildQuery(model.findById(res.req.param('id')), req.query).findOne(function(err, item) {
 			if(err) {
 				res.send(404, 'Not found');
 			} else {
 				res.type('json');
 				res.send(JSON.stringify(item));
 			}
 		});
 	});
 	app.post(uri_item, write_middleware, modifyObject);
 	app.put(uri_item, write_middleware, modifyObject);
 	app.delete(uri_item, options.middleware, function(req, res) {
 		model.remove({ _id: res.req.param('id') }, function(err) {
 			if(err) {
 				res.send(404, 'Not found');
 			} else {
 				res.send(200, 'Ok');
 			}
 		});
 	});
 };

 module.exports.serve = restify;
<|endoftext|>


<commit_before>/* global suite, test, setup, teardown */
import { default as chai, assert } from 'chai';
import chaiSpies from 'chai-spies';
import chaiSpiesTdd from 'chai-spies-tdd';

chai.use(chaiSpies);
chai.use(chaiSpiesTdd);

import {
  parse,
  isIgnored,
  __RewireAPI__ as RewireAPI
} from '../src/log-utils';

RewireAPI.__Rewire__('IGNORED_LOGS', [
  'useless message',
  'something really stupid',
  'just ignored log'
]);

suite('API', () => {
  test('named export type', () => {
    assert.isFunction(parse, 'parse is a function');
    assert.isFunction(isIgnored, 'isIgnored is a function');
  });
});

suite('parsing logs', () => {
  test('chrome logs', () => {

  });

  test('firefox logs', () => {

  });

  test('firefox addon logs', () => {

  });

  test('android emulator logs', () => {

  });

  test('custom logs', () => {

  });
});<commit_msg>name test suite better<commit_after>/* global suite, test, setup, teardown */
import { default as chai, assert } from 'chai';
import chaiSpies from 'chai-spies';
import chaiSpiesTdd from 'chai-spies-tdd';

chai.use(chaiSpies);
chai.use(chaiSpiesTdd);

import {
  parse,
  isIgnored,
  __RewireAPI__ as RewireAPI
} from '../src/log-utils';

RewireAPI.__Rewire__('IGNORED_LOGS', [
  'useless message',
  'something really stupid',
  'just ignored log'
]);

suite('log utils - API', () => {
  test('named export type', () => {
    assert.isFunction(parse, 'parse is a function');
    assert.isFunction(isIgnored, 'isIgnored is a function');
  });
});

suite('parsing logs', () => {
  test('chrome logs', () => {

  });

  test('firefox logs', () => {

  });

  test('firefox addon logs', () => {

  });

  test('android emulator logs', () => {

  });

  test('custom logs', () => {

  });
});<|endoftext|>


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

var Bootstrap = require('./support/bootstrap');
var manager   = require('./support/manager');

describe('manager', function() {
  describe('.create', function() {
    beforeEach(function(done) {
      Bootstrap.database().then(function() {
        return Bootstrap.tables();
      }).then(function() {
        done();
      });
    });

    it('should create a new model', function(done) {
      manager.create('car').then(function(car) {
        assert.ok(manager.isModel(car), 'Car should be a Model');
        assert.ok(car.id, 'Car should have ID 1');
        done();
      });
    });

    it('should create a new collection', function(done) {
      manager.create('cars').then(function(cars) {
        assert.ok(manager.isCollection(cars), 'Car should be a Collection');
        done();
      });
    });

    it('should create a new, populated model', function(done) {
      manager.create('car', {
        quantity: 1
      }).then(function(car) {
        assert.equal(1, car.id, 'Car should have ID 1');
        assert.equal(1, car.get('quantity'), 'Car should have quantity of 1');
        done();
      });
    })

    it('should create a new, populated collection', function(done) {
      manager.create('cars', [
        { quantity: 1 },
        { quantity: 2 },
      ]).then(function(cars) {
        cars.sortBy('id');

        assert.equal(2, cars.length, 'Cars collection should have 2 Car models');
        assert.equal(1, cars.at(0).id, 'Car #1 should have ID 1, not ' + cars.at(0).id);
        assert.equal(2, cars.at(1).id, 'Car #2 should have ID 2, not ' + cars.at(1).id);
        done();
      });
    })

    it('should create a model within a new model (belongsTo)', function(done) {
      manager.create('car', {
        color: {
          name: 'White',
          hex_value: '#fff',
        },
        quantity: 1
      }).then(function(car) {
        assert.equal(1, car.id, 'Car should have ID 1, not ' + car.id);
        assert.equal(1, car.get('quantity'), 'Car should have quantity of 1');
        assert.equal(1, car.related('color').id, 'Color should have ID 1, not ' + car.related('color').id);
        assert.equal('White', car.related('color').get('name'), 'Color name should be White');
        assert.equal('#fff', car.related('color').get('hex_value'), 'Color hex_value should be #fff');
        done();
      })
    });

    it('should modify an existing nested model', function(done) {
      manager.create('color', {
        name: 'White',
        hex_value: '#fff',
      }).then(function(color) {
        manager.create('car', {
          color: {
            id: color.id,
            name: 'Grey',
            hex_value: '#666',
          },
          quantity: 2
        }).then(function(car) {
          assert.equal(color.id, car.related('color').id, 'Color ID should stay the same, not ' + car.related('color').id);
          assert.equal('Grey', car.related('color').get('name'), 'Color name should be Grey');
          assert.equal('#666', car.related('color').get('hex_value'), 'Color hex_value should be #666');
          done();
        });
      });
    });

    it('should create models within a nested collection (belongsToMany)', function(done) {
      manager.create('car', {
        features: [
          { name: 'ABS', cost: '1250' },
          { name: 'GPS', cost: '500' },
        ],
        quantity: 1
      }).then(function(car) {
        car.related('features').sortBy('name');

        assert.equal(1, car.id, 'Car should have ID 1');
        assert.equal(2, car.related('features').length, 'There should be 2 features');
        assert.ok(car.related('features').at(0).id, 'Feature #1 should have ID');
        assert.ok(car.related('features').at(1).id, 'Feature #2 should have ID');
        assert.equal('ABS', car.related('features').at(0).get('name'), 'Feature #1 name should be ABS');
        assert.equal('GPS', car.related('features').at(1).get('name'), 'Feature #2 name should be GPS');
        done();
      });
    });

    it('should create models within a nested collection (hasMany)', function(done) {
      manager.create('make', {
        models: [
          { name: 'X3' },
          { name: 'X5' },
        ]
      }).then(function(make) {
        make.related('models').sortBy('name');

        assert.equal(1, make.id, 'Make should have ID 1');
        assert.equal(2, make.related('models').length);
        assert.ok(make.related('models').at(0).id, 'Model #1 should have ID, not ' + make.related('models').at(0).id);
        assert.ok(make.related('models').at(1).id, 'Model #2 should have ID, not ' + make.related('models').at(1).id);
        assert.equal('X3', make.related('models').at(0).get('name'), 'Model #1 name should be X3, not ' + make.related('models').at(0).get('name'));
        assert.equal('X5', make.related('models').at(1).get('name'), 'Model #2 name should be X5, not ' + make.related('models').at(1).get('name'));
        done();
      });
    });

    it('should create a deep object', function(done) {
      manager.create('make', {
        name: 'BMW',
        models: [
          {
            name: 'X5',
            cost: 50000,
            type: {
              name: 'Crossover'
            },
            specs: [
              { name: '4 door' },
              { name: 'v6' },
            ]
          }
        ]
      }).then(function(result) {
        return manager.fetch('make', { name: 'BMW' }, ['models.type', 'models.specs']).then(function(actual) {
          assert.equal(
            actual.related('models').length,
            result.related('models').length
          );

          assert.equal(
            actual.related('models').at(0).related('specs').length,
            result.related('models').at(0).related('specs').length
          );

          assert.equal(
            JSON.stringify(actual.related('models').at(0).related('type').toJSON(), null, 2),
            JSON.stringify(result.related('models').at(0).related('type').toJSON(), null, 2)
          );

          done();
        });
      });
    });
  });
});
<commit_msg>Fix annoying test dependent on ID insertion order<commit_after>var assert    = require('assert');
var Promise   = require('bluebird');

var Bootstrap = require('./support/bootstrap');
var manager   = require('./support/manager');

describe('manager', function() {
  describe('.create', function() {
    beforeEach(function(done) {
      Bootstrap.database().then(function() {
        return Bootstrap.tables();
      }).then(function() {
        done();
      });
    });

    it('should create a new model', function(done) {
      manager.create('car').then(function(car) {
        assert.ok(manager.isModel(car), 'Car should be a Model');
        assert.ok(car.id, 'Car should have ID 1');
        done();
      });
    });

    it('should create a new collection', function(done) {
      manager.create('cars').then(function(cars) {
        assert.ok(manager.isCollection(cars), 'Car should be a Collection');
        done();
      });
    });

    it('should create a new, populated model', function(done) {
      manager.create('car', {
        quantity: 1
      }).then(function(car) {
        assert.equal(1, car.id, 'Car should have ID 1');
        assert.equal(1, car.get('quantity'), 'Car should have quantity of 1');
        done();
      });
    })

    it('should create a new, populated collection', function(done) {
      manager.create('cars', [
        { quantity: 1 },
        { quantity: 2 },
      ]).then(function(cars) {
        cars.sortBy('quantity');

        assert.equal(2, cars.length, 'Cars collection should have 2 Car models');
        assert.equal(2, cars.pluck('quantity').length, 'Quantities should be set');
        done();
      });
    })

    it('should create a model within a new model (belongsTo)', function(done) {
      manager.create('car', {
        color: {
          name: 'White',
          hex_value: '#fff',
        },
        quantity: 1
      }).then(function(car) {
        assert.equal(1, car.id, 'Car should have ID 1, not ' + car.id);
        assert.equal(1, car.get('quantity'), 'Car should have quantity of 1');
        assert.equal(1, car.related('color').id, 'Color should have ID 1, not ' + car.related('color').id);
        assert.equal('White', car.related('color').get('name'), 'Color name should be White');
        assert.equal('#fff', car.related('color').get('hex_value'), 'Color hex_value should be #fff');
        done();
      })
    });

    it('should modify an existing nested model', function(done) {
      manager.create('color', {
        name: 'White',
        hex_value: '#fff',
      }).then(function(color) {
        manager.create('car', {
          color: {
            id: color.id,
            name: 'Grey',
            hex_value: '#666',
          },
          quantity: 2
        }).then(function(car) {
          assert.equal(color.id, car.related('color').id, 'Color ID should stay the same, not ' + car.related('color').id);
          assert.equal('Grey', car.related('color').get('name'), 'Color name should be Grey');
          assert.equal('#666', car.related('color').get('hex_value'), 'Color hex_value should be #666');
          done();
        });
      });
    });

    it('should create models within a nested collection (belongsToMany)', function(done) {
      manager.create('car', {
        features: [
          { name: 'ABS', cost: '1250' },
          { name: 'GPS', cost: '500' },
        ],
        quantity: 1
      }).then(function(car) {
        car.related('features').sortBy('name');

        assert.equal(1, car.id, 'Car should have ID 1');
        assert.equal(2, car.related('features').length, 'There should be 2 features');
        assert.equal(2, car.related('features').pluck('name').length, 'There should be 2 names');
        done();
      });
    });

    it('should create models within a nested collection (hasMany)', function(done) {
      manager.create('make', {
        models: [
          { name: 'X3' },
          { name: 'X5' },
        ]
      }).then(function(make) {
        make.related('models').sortBy('name');

        assert.equal(1, make.id, 'Make should have ID 1');
        assert.equal(2, make.related('models').length);
        assert.ok(make.related('models').at(0).id, 'Model #1 should have ID, not ' + make.related('models').at(0).id);
        assert.ok(make.related('models').at(1).id, 'Model #2 should have ID, not ' + make.related('models').at(1).id);
        assert.equal('X3', make.related('models').at(0).get('name'), 'Model #1 name should be X3, not ' + make.related('models').at(0).get('name'));
        assert.equal('X5', make.related('models').at(1).get('name'), 'Model #2 name should be X5, not ' + make.related('models').at(1).get('name'));
        done();
      });
    });

    it('should create a deep object', function(done) {
      manager.create('make', {
        name: 'BMW',
        models: [
          {
            name: 'X5',
            cost: 50000,
            type: {
              name: 'Crossover'
            },
            specs: [
              { name: '4 door' },
              { name: 'v6' },
            ]
          }
        ]
      }).then(function(result) {
        return manager.fetch('make', { name: 'BMW' }, ['models.type', 'models.specs']).then(function(actual) {
          assert.equal(
            actual.related('models').length,
            result.related('models').length
          );

          assert.equal(
            actual.related('models').at(0).related('specs').length,
            result.related('models').at(0).related('specs').length
          );

          assert.equal(
            JSON.stringify(actual.related('models').at(0).related('type').toJSON(), null, 2),
            JSON.stringify(result.related('models').at(0).related('type').toJSON(), null, 2)
          );

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


<commit_before>
Core.Schemas.TimeWriting = new SimpleSchema({
    _id: {
        type: String,
        optional: true
    },
    employeeId: {
        type: String,
        index: 1,
        autoform: {
            type: "hidden",
            label: false
        },
        autoValue: function() {
            if (this.isInsert) {
                if (this.isSet && Meteor.isServer) {
                    return this.value;
                } else {
                    return this.userId;
                }
            }
        }
    },
    businessId: {
        type: String
    },
    project: {
        type: String,
        optional: true
    },
    activity:{
        type: String,
        optional: true,
        custom: function () {
            let employeeId = this.siblingField("employeeId").value;
            let duration = this.siblingField("duration").value;
            let activity = this.siblingField("activity").value;

            if(activity) {
                let dayAsDate = this.siblingField("day").value;

                var dayStart = moment(dayAsDate).startOf('day').toDate();
                var dayEnd = moment(dayAsDate).endOf('day').toDate();

                return TimeWritings.find({
                    activity: activity,
                    employeeId: employeeId,
                    day: {
                        $gte: dayStart,
                        $lt: dayEnd
                    }
                }).count() > 0 ? "duplicateActivityOnSameDayNotAllowed" : true
            }
        }
    },
    costCenter: {
        type: String,
        optional: true
    },
    locationId: {
        type: String,
        optional: true
    },
    day: {
        type: Date
    },
    duration: {
        type: Number
    },
    note: {
        type: String,
        optional: true
    },
    status: {
        type: String,
        defaultValue: 'Open',
        allowedValues: ['Approved', 'Open', "Rejected"],
        optional: true
    },
    isStatusSeenByCreator: {
        type: Boolean,
        defaultValue: false
    },
    approvedBy: {
        type: String,
        regEx: SimpleSchema.RegEx.Id,
        optional: true
    },
    approvedDate: {
        type: Date,
        optional: true
    },
    isApprovalStatusSeenByCreator: {
        type: Boolean,
        defaultValue: false
    },
    "successFactorsCostCenter": {
        type: String,
        optional: true,
    },
    "successFactorsCustProject": {
        type: String,
        optional: true,
    },
    createdAt: {
        type: Date,
        autoValue: function () {
            if (this.isInsert) {
                return new Date;
            } else if (this.isUpsert) {
                return {
                    $setOnInsert: new Date
                };
            }
        },
        denyUpdate: true
    }

});

SimpleSchema.messages({
    "duplicateActivityOnSameDayNotAllowed": "You cannot record time for same activity twice in one day",
});
<commit_msg>hours in decimal<commit_after>
Core.Schemas.TimeWriting = new SimpleSchema({
    _id: {
        type: String,
        optional: true
    },
    employeeId: {
        type: String,
        index: 1,
        autoform: {
            type: "hidden",
            label: false
        },
        autoValue: function() {
            if (this.isInsert) {
                if (this.isSet && Meteor.isServer) {
                    return this.value;
                } else {
                    return this.userId;
                }
            }
        }
    },
    businessId: {
        type: String
    },
    project: {
        type: String,
        optional: true
    },
    activity:{
        type: String,
        optional: true,
        custom: function () {
            let employeeId = this.siblingField("employeeId").value;
            let duration = this.siblingField("duration").value;
            let activity = this.siblingField("activity").value;

            if(activity) {
                let dayAsDate = this.siblingField("day").value;

                var dayStart = moment(dayAsDate).startOf('day').toDate();
                var dayEnd = moment(dayAsDate).endOf('day').toDate();

                return TimeWritings.find({
                    activity: activity,
                    employeeId: employeeId,
                    day: {
                        $gte: dayStart,
                        $lt: dayEnd
                    }
                }).count() > 0 ? "duplicateActivityOnSameDayNotAllowed" : true
            }
        }
    },
    costCenter: {
        type: String,
        optional: true
    },
    locationId: {
        type: String,
        optional: true
    },
    day: {
        type: Date
    },
    duration: {
        type: Number,
        decimal:true
    },
    note: {
        type: String,
        optional: true
    },
    status: {
        type: String,
        defaultValue: 'Open',
        allowedValues: ['Approved', 'Open', "Rejected"],
        optional: true
    },
    isStatusSeenByCreator: {
        type: Boolean,
        defaultValue: false
    },
    approvedBy: {
        type: String,
        regEx: SimpleSchema.RegEx.Id,
        optional: true
    },
    approvedDate: {
        type: Date,
        optional: true
    },
    isApprovalStatusSeenByCreator: {
        type: Boolean,
        defaultValue: false
    },
    "successFactorsCostCenter": {
        type: String,
        optional: true,
    },
    "successFactorsCustProject": {
        type: String,
        optional: true,
    },
    createdAt: {
        type: Date,
        autoValue: function () {
            if (this.isInsert) {
                return new Date;
            } else if (this.isUpsert) {
                return {
                    $setOnInsert: new Date
                };
            }
        },
        denyUpdate: true
    }

});

SimpleSchema.messages({
    "duplicateActivityOnSameDayNotAllowed": "You cannot record time for same activity twice in one day",
});
<|endoftext|>


<commit_before>var _ = require('underscore')
  , vows = require('vows')
  , assert = require('assert')
  , should = require('should')
  , fmap = require('functools').map

  , common = require('./common.js')
  , Hyde = require('..')(common.conf)
  , Base = Hyde.Base
  , client = Hyde.client

common.prepareTesting(client);

var Models = {
  Volatile: Base.extend({
    table: 'volatile',
    schema: { id: Base.Schema.Id, drop: Base.Schema.Number, rename: Base.Schema.Number }
  }),

  User: Base.extend({
    table: 'user',
    schema: { id: Base.Schema.Id }
  }),

  Stuff: Base.extend({
    table: 'stuff',
    schema: { id: Base.Schema.Id }
  }),
};

function binder(o) { _.bindAll(o); }
_.map(_.values(Models), binder);

vows.describe('testing migrations').addBatch({
  'Test some migrations, yo' : {
    topic: function () {
      var maker = function (M, callback) { M.makeTable(callback) }

      fmap.async(maker, _.values(Models), function (err, res) {
        if (err) throw err;
        this.callback(null, Models);
      }.bind(this));

    },
    // 'getCreateTable': function () {
    //   var t = Base.Migration(User);
    // },
    'getAlterSql': {
      topic: function (M) { return M.User.Migration() },
      'add' : function (t) {
        var sql = t.getAlterSql({ yam: Base.Schema.String() }, 'add');
        sql[0].should.equal('ALTER TABLE `user` ADD `yam` TEXT');
      },
      'change': {
        'takes a spec' :function (t) {
          var sql = t.getAlterSql({ beets: Base.Schema.Number() }, 'change');
          sql[0].should.equal('ALTER TABLE `user` CHANGE `beets` INT');
        },
        'takes a straaaaang': function (t) {
          var sql = t.getAlterSql({ clams: 'TASTY CLAMS' }, 'change');
          sql[0].should.equal('ALTER TABLE `user` CHANGE `clams` TASTY CLAMS');
        },
        'handles unique intelligently': function (t) {
          var sql = t.getAlterSql({ clams: Base.Schema.Text({unique: 128}) }, 'change');
          sql.should.have.lengthOf(2);
          sql[1].should.equal('ALTER TABLE `user` ADD UNIQUE KEY `clams` (`clams` (128))');
        }
      },
      'drop': function (t) {
        var sql = t.getAlterSql('words', 'drop');
        sql[0].should.equal('ALTER TABLE `user` DROP COLUMN `words`');
      },
      'engine': function (t) {
        var sql = t.getAlterSql('MyISAM', 'engine');
        sql[0].should.equal('ALTER TABLE `user` ENGINE = MyISAM');
      },
      'add key': function (t) {
        var sql = t.getAlterSql({yeah: { type: 'unique' }}, 'add key')
        sql[0].should.equal('ALTER TABLE `user` ADD UNIQUE KEY `yeah` (`yeah`)');

        sql = t.getAlterSql({yeah: { type: 'unique', name: 'yo' }}, 'add key')
        sql[0].should.equal('ALTER TABLE `user` ADD UNIQUE KEY `yeah` (`yo`)');

        sql = t.getAlterSql({yeah: { type: 'unique', name: 'yo', length: 128 }}, 'add key')
        sql[0].should.equal('ALTER TABLE `user` ADD UNIQUE KEY `yeah` (`yo` (128))');
      }
    },
    'addColumn' : {
      'simple like' : {
        topic: function (M) {
          var t = M.User.Migration();

          var cb_addCol = function (err, result) {
            if (err) return this.callback(err);
            Base.client.query('show create table user', this.callback)
          }.bind(this);

          var spec = { emperor: Base.Schema.String({
            type: 'varchar',length: 255,unique: 128,default: 'x'
          })}

          try {
            t.addColumn(spec, cb_addCol);
          } catch (err) {
            this.callback(err);
          }
        },
        'does what it says on the tin' : function (err, result) {
          assert.ifError(err);
          var sql = result.pop()['Create Table'];
          sql.should.match(/unique key `emperor` \(`emperor`\(128\)\)/i);
          sql.should.match(/`emperor` varchar\(255\).*default 'x'/i);
        }
      },
      'more complex addColumn' : {
        topic: function (M) {
          var t = Base.Migration(M.User);
          _.bindAll(t);

          var adder = function (spec, callback) {
            t.addColumn(spec, callback);
          }

          var cb_addCol = function (err, result) {
            if (err) return this.callback(err);
            Base.client.query('show create table user', this.callback)
          }.bind(this);

          var specs =[
            { sss: Base.Schema.String({type: 'char', length: 128, unique: true, default: 'y'})},
            { nnn: Base.Schema.Number() },
            { eee: Base.Schema.Enum(['one', 'two']) },
            { stuff_id: Base.Schema.Foreign({model: M.Stuff, field: 'id'})}
          ]
          try {
            fmap.async(adder, specs, cb_addCol);
          } catch (err) {
            this.callback(err);
          }
        },

        'adds all the fields fine' : function (err, result) {
          var sql = result[0]['Create Table'];
          console.dir(sql);
          sql.should.match(/`sss` char\(128\).*default 'y'/i);
          sql.should.match(/`nnn` int\(\d+\).*default null/i);
          sql.should.match(/`eee` enum\('one','two'\).*default null/i);
          sql.should.match(/`stuff_id` (big)?int\(\d+\).*default null/i);
        },

        'adds all the keys fine' : function (err, result) {
          var sql = result[0]['Create Table'];
          sql.should.match(/unique key `sss` \(`sss`\)/i);
          sql.should.match(/key `stuff_fkey` \(`stuff_id`\)/i);
          sql.should.match(/constraint `user_ibfk_1` foreign key \(`stuff_id`\) references `stuff` \(`id`\)/i);
        }
      }
    },
    'dropColumn' : {
      topic: function (M) {
        var t = M.Volatile.Migration();
        var cb = function (err, result) {
          if (err) return this.callback(err);
          Hyde.client.query('show create table volatile', this.callback)
        }.bind(this);

        try {
          t.dropColumn('drop', cb);
        } catch (error) {
          this.callback(error);
        }
      },
      'should drop the damn column': function (err, result) {
        assert.ifError(err);
        result.should.not.match(/drop/);
      }
    },
    'renameColumn' : {
      topic: function (M) {
        var t = M.Volatile.Migration();
        var cb = function (err, result) {
          if (err) return this.callback(err);
          Hyde.client.query('show create table volatile', this.callback)
        }.bind(this);

        try {
          t.renameColumn('rename', 'lol', cb);
        } catch (error) {
          this.callback(error);
        }
      },
      'should rename the column': function (err, result) {
        assert.ifError(err);
        var sql = result[0]['Create Table'];
        sql.should.not.match(/rename/);
      }
    },
    'executeSql' : {
      topic: function (M) {
        var t = M.Volatile.Migration();
        var cb = function (err, result) {
          if (err) return this.callback(err);
          Hyde.client.query('show create table volatile', this.callback)
        }.bind(this);

        try {
          t.executeSql('alter table `volatile` change column `id` `rad` int auto_increment not null', cb);
        } catch (error) {
          this.callback(error);
        }
      },
      'should rename the column': function (err, result) {
        assert.ifError(err);
        var sql = result[0]['Create Table'];
        sql.should.not.match(/`id`/);
      }
    }
  }
}).export(module);

<commit_msg>Remove some debugging.<commit_after>var _ = require('underscore')
  , vows = require('vows')
  , assert = require('assert')
  , should = require('should')
  , fmap = require('functools').map

  , common = require('./common.js')
  , Hyde = require('..')(common.conf)
  , Base = Hyde.Base
  , client = Hyde.client

common.prepareTesting(client);

var Models = {
  Volatile: Base.extend({
    table: 'volatile',
    schema: { id: Base.Schema.Id, drop: Base.Schema.Number, rename: Base.Schema.Number }
  }),

  User: Base.extend({
    table: 'user',
    schema: { id: Base.Schema.Id }
  }),

  Stuff: Base.extend({
    table: 'stuff',
    schema: { id: Base.Schema.Id }
  }),
};

function binder(o) { _.bindAll(o); }
_.map(_.values(Models), binder);

vows.describe('testing migrations').addBatch({
  'Test some migrations, yo' : {
    topic: function () {
      var maker = function (M, callback) { M.makeTable(callback) }

      fmap.async(maker, _.values(Models), function (err, res) {
        if (err) throw err;
        this.callback(null, Models);
      }.bind(this));

    },
    // 'getCreateTable': function () {
    //   var t = Base.Migration(User);
    // },
    'getAlterSql': {
      topic: function (M) { return M.User.Migration() },
      'add' : function (t) {
        var sql = t.getAlterSql({ yam: Base.Schema.String() }, 'add');
        sql[0].should.equal('ALTER TABLE `user` ADD `yam` TEXT');
      },
      'change': {
        'takes a spec' :function (t) {
          var sql = t.getAlterSql({ beets: Base.Schema.Number() }, 'change');
          sql[0].should.equal('ALTER TABLE `user` CHANGE `beets` INT');
        },
        'takes a straaaaang': function (t) {
          var sql = t.getAlterSql({ clams: 'TASTY CLAMS' }, 'change');
          sql[0].should.equal('ALTER TABLE `user` CHANGE `clams` TASTY CLAMS');
        },
        'handles unique intelligently': function (t) {
          var sql = t.getAlterSql({ clams: Base.Schema.Text({unique: 128}) }, 'change');
          sql.should.have.lengthOf(2);
          sql[1].should.equal('ALTER TABLE `user` ADD UNIQUE KEY `clams` (`clams` (128))');
        }
      },
      'drop': function (t) {
        var sql = t.getAlterSql('words', 'drop');
        sql[0].should.equal('ALTER TABLE `user` DROP COLUMN `words`');
      },
      'engine': function (t) {
        var sql = t.getAlterSql('MyISAM', 'engine');
        sql[0].should.equal('ALTER TABLE `user` ENGINE = MyISAM');
      },
      'add key': function (t) {
        var sql = t.getAlterSql({yeah: { type: 'unique' }}, 'add key')
        sql[0].should.equal('ALTER TABLE `user` ADD UNIQUE KEY `yeah` (`yeah`)');

        sql = t.getAlterSql({yeah: { type: 'unique', name: 'yo' }}, 'add key')
        sql[0].should.equal('ALTER TABLE `user` ADD UNIQUE KEY `yeah` (`yo`)');

        sql = t.getAlterSql({yeah: { type: 'unique', name: 'yo', length: 128 }}, 'add key')
        sql[0].should.equal('ALTER TABLE `user` ADD UNIQUE KEY `yeah` (`yo` (128))');
      }
    },
    'addColumn' : {
      'simple like' : {
        topic: function (M) {
          var t = M.User.Migration();

          var cb_addCol = function (err, result) {
            if (err) return this.callback(err);
            Base.client.query('show create table user', this.callback)
          }.bind(this);

          var spec = { emperor: Base.Schema.String({
            type: 'varchar',length: 255,unique: 128,default: 'x'
          })}

          try {
            t.addColumn(spec, cb_addCol);
          } catch (err) {
            this.callback(err);
          }
        },
        'does what it says on the tin' : function (err, result) {
          assert.ifError(err);
          var sql = result.pop()['Create Table'];
          sql.should.match(/unique key `emperor` \(`emperor`\(128\)\)/i);
          sql.should.match(/`emperor` varchar\(255\).*default 'x'/i);
        }
      },
      'more complex addColumn' : {
        topic: function (M) {
          var t = Base.Migration(M.User);
          _.bindAll(t);

          var adder = function (spec, callback) {
            t.addColumn(spec, callback);
          }

          var cb_addCol = function (err, result) {
            if (err) return this.callback(err);
            Base.client.query('show create table user', this.callback)
          }.bind(this);

          var specs =[
            { sss: Base.Schema.String({type: 'char', length: 128, unique: true, default: 'y'})},
            { nnn: Base.Schema.Number() },
            { eee: Base.Schema.Enum(['one', 'two']) },
            { stuff_id: Base.Schema.Foreign({model: M.Stuff, field: 'id'})}
          ]
          try {
            fmap.async(adder, specs, cb_addCol);
          } catch (err) {
            this.callback(err);
          }
        },

        'adds all the fields fine' : function (err, result) {
          var sql = result[0]['Create Table'];
          sql.should.match(/`sss` char\(128\).*default 'y'/i);
          sql.should.match(/`nnn` int\(\d+\).*default null/i);
          sql.should.match(/`eee` enum\('one','two'\).*default null/i);
          sql.should.match(/`stuff_id` (big)?int\(\d+\).*default null/i);
        },

        'adds all the keys fine' : function (err, result) {
          var sql = result[0]['Create Table'];
          sql.should.match(/unique key `sss` \(`sss`\)/i);
          sql.should.match(/key `stuff_fkey` \(`stuff_id`\)/i);
          sql.should.match(/constraint `user_ibfk_1` foreign key \(`stuff_id`\) references `stuff` \(`id`\)/i);
        }
      }
    },
    'dropColumn' : {
      topic: function (M) {
        var t = M.Volatile.Migration();
        var cb = function (err, result) {
          if (err) return this.callback(err);
          Hyde.client.query('show create table volatile', this.callback)
        }.bind(this);

        try {
          t.dropColumn('drop', cb);
        } catch (error) {
          this.callback(error);
        }
      },
      'should drop the damn column': function (err, result) {
        assert.ifError(err);
        result.should.not.match(/drop/);
      }
    },
    'renameColumn' : {
      topic: function (M) {
        var t = M.Volatile.Migration();
        var cb = function (err, result) {
          if (err) return this.callback(err);
          Hyde.client.query('show create table volatile', this.callback)
        }.bind(this);

        try {
          t.renameColumn('rename', 'lol', cb);
        } catch (error) {
          this.callback(error);
        }
      },
      'should rename the column': function (err, result) {
        assert.ifError(err);
        var sql = result[0]['Create Table'];
        sql.should.not.match(/rename/);
      }
    },
    'executeSql' : {
      topic: function (M) {
        var t = M.Volatile.Migration();
        var cb = function (err, result) {
          if (err) return this.callback(err);
          Hyde.client.query('show create table volatile', this.callback)
        }.bind(this);

        try {
          t.executeSql('alter table `volatile` change column `id` `rad` int auto_increment not null', cb);
        } catch (error) {
          this.callback(error);
        }
      },
      'should rename the column': function (err, result) {
        assert.ifError(err);
        var sql = result[0]['Create Table'];
        sql.should.not.match(/`id`/);
      }
    }
  }
}).export(module);

<|endoftext|>


<commit_before>'use strict';

const request = require('request');
const core = require('./../core/core.js');
const db = require('./../aslan-messenger/aslan-db.js');

/*
* Fonction appelé par les routes lors de la reception d'un message
*/
function receivedMessage(message, user) {
    console.log("Aslan received a message");
    var m = {
        channel: "Aslan",
        senderID: user._id,
        timestamp: new Date(),
        text: message.text,
        first_name: user.firstname,
        last_name: user.name
    };
    console.log(JSON.stringify(m));
    core.receivedMessage(m);
}

/*
* Fonction appelé par le core pour envoyer un message sur la channel Aslan Messenger
*/
function sendMessage(message) {
	switch(message.type) {
        case "text":
            sendTextMessage(message);
            break;
        case "quickreply":
            sendQuickReplyMessage(message);
            break;
        case "location":
            sendLocationMessage(message);
            break;
        case "template":
            sendTemplateMessage(message);
        break;
    }
}

/*
* Fonction appelé par le core pour envoyer des messages sur la channel Aslan Messenger
*/
function sendMessages(messages) {
    for(var i=0;i<messages.length;i++) {
        sendMessage(messages[i]);
    }
}

/*
* Fonction qui sauvegarde un message en DB
*/
function save(m) {
    console.log(JSON.stringify(m));
    var user_id = m.senderID.toString();
    var message = m.message;
    if(user_id != undefined && message != undefined) {
        db.createMessage(user_id, message, true, function(data){
            console.log(data)
            if(data.length == 0) {
                console.log("Error create message");
            } else {
                console.log(JSON.stringify(data[0]));
            }
        });
    }
}

/*
* Fonction qui envoie un message de type text
*/
function sendTextMessage(message) {
    if(message.senderID != undefined && message.text != undefined) {
        message.message = {text : message.text, type: "text"};
        save(message);
    }
}

/*
* Fonction qui envoie un message de type quickreply
*/
function sendQuickReplyMessage(message) {
    if(message.senderID != undefined && message.text != undefined) {
        message.message = {text : message.text, type: "quickreplies", quickreplies: message.choices};
        save(message);
    }
}

/*
* Fonction qui envoie un message de type location
*/
function sendLocationMessage(message) {
    if(message.senderID != undefined && message.text != undefined) {
        message.message = {text : message.text, type: "location"};
        save(message);
    }
}

/*
* Fonction qui envoie un message de type template
*/
function sendTemplateMessage(message) {
    if(message.senderID != undefined && message.text != undefined) {
        message.message = {text : message.text, type: "template"};
        save(message);
    }
}

/*
* Fonction qui envoie un message audio/file/image/video
*/
function sendFileMessage(message) {

}

exports.receivedMessage = receivedMessage;
exports.sendMessage = sendMessage;
exports.sendMessages = sendMessages;<commit_msg>Fix bug location Aslan-Messenger<commit_after>'use strict';

const request = require('request');
const core = require('./../core/core.js');
const db = require('./../aslan-messenger/aslan-db.js');

/*
* Fonction appelé par les routes lors de la reception d'un message
*/
function receivedMessage(message, user) {
    console.log("Aslan received a message");
    var m = {
        channel: "Aslan",
        senderID: user._id,
        timestamp: new Date(),
        text: message.text,
        first_name: user.firstname,
        last_name: user.name
    };
    if(message.lat != undefined && message.long != undefined) {
        m["location"] = {lat : message.lat, long: message.long};
    }
    console.log(JSON.stringify(m));
    core.receivedMessage(m);
}

/*
* Fonction appelé par le core pour envoyer un message sur la channel Aslan Messenger
*/
function sendMessage(message) {
	switch(message.type) {
        case "text":
            sendTextMessage(message);
            break;
        case "quickreply":
            sendQuickReplyMessage(message);
            break;
        case "location":
            sendLocationMessage(message);
            break;
        case "template":
            sendTemplateMessage(message);
        break;
    }
}

/*
* Fonction appelé par le core pour envoyer des messages sur la channel Aslan Messenger
*/
function sendMessages(messages) {
    for(var i=0;i<messages.length;i++) {
        sendMessage(messages[i]);
    }
}

/*
* Fonction qui sauvegarde un message en DB
*/
function save(m) {
    console.log(JSON.stringify(m));
    var user_id = m.senderID.toString();
    var message = m.message;
    if(user_id != undefined && message != undefined) {
        db.createMessage(user_id, message, true, function(data){
            console.log(data)
            if(data.length == 0) {
                console.log("Error create message");
            } else {
                console.log(JSON.stringify(data[0]));
            }
        });
    }
}

/*
* Fonction qui envoie un message de type text
*/
function sendTextMessage(message) {
    if(message.senderID != undefined && message.text != undefined) {
        message.message = {text : message.text, type: "text"};
        save(message);
    }
}

/*
* Fonction qui envoie un message de type quickreply
*/
function sendQuickReplyMessage(message) {
    if(message.senderID != undefined && message.text != undefined) {
        message.message = {text : message.text, type: "quickreplies", quickreplies: message.choices};
        save(message);
    }
}

/*
* Fonction qui envoie un message de type location
*/
function sendLocationMessage(message) {
    if(message.senderID != undefined && message.text != undefined) {
        message.message = {text : message.text, type: "location"};
        save(message);
    }
}

/*
* Fonction qui envoie un message de type template
*/
function sendTemplateMessage(message) {
    if(message.senderID != undefined && message.text != undefined) {
        message.message = {text : message.text, type: "template"};
        save(message);
    }
}

/*
* Fonction qui envoie un message audio/file/image/video
*/
function sendFileMessage(message) {

}

exports.receivedMessage = receivedMessage;
exports.sendMessage = sendMessage;
exports.sendMessages = sendMessages;<|endoftext|>


<commit_before>/*
 * mocaccino.js
 *
 * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
 *
 * @license MIT
 */
/*globals describe, it*/
'use strict';

var assert     = require('assert');
var browserify = require('browserify');
var coverify   = require('coverify');
var spawn      = require('child_process').spawn;
var mocaccino  = require('../lib/mocaccino');

function run(proc, b, opts, done) {
  var p = spawn(proc);
  var s = b.bundle(opts);
  s.on('error', function (err) {
    done(err);
  });
  var out = '';
  p.stdout.on('data', function (data) {
    out += data;
  });
  p.stderr.pipe(process.stderr);
  p.on('close', function (code) {
    done(null, code, out);
  });
  s.pipe(p.stdin);
}

var bundleOptionsBare = {
  detectGlobal     : true,
  insertGlobalVars : ['__dirname', '__filename']
};

function passOutputAssert(done) {
  return function (err, code, out) {
    if (err) {
      done(err);
    } else {
      assert.equal(code, 0);
      assert.equal(out, '1..1\n'
        + 'ok 1 fixture passes\n'
        + '# tests 1\n'
        + '# pass 1\n'
        + '# fail 0\n');
      done();
    }
  };
}

function failOutputAssert(done) {
  return function (err, code, out) {
    if (err) {
      done(err);
    } else {
      assert.equal(code, 1);
      assert.equal(out.substring(0, 28), '1..1\nnot ok 1 fixture fails\n');
      assert(out.indexOf('# tests 1\n# pass 0\n# fail 1') > 1);
      done();
    }
  };
}

function coverage(callback) {
  return function (err, code, out) {
    if (err) {
      callback(err);
    } else {
      assert.equal(code, 0);
      var cov = spawn('coverify');
      //cov.stderr.pipe(process.stderr);
      cov.stdin.write(out);
      cov.stdin.end();
      cov.on('exit', callback);
    }
  };
}

describe('plugin', function () {

  describe('phantomjs', function () {
    this.timeout(5000);

    it('passes test', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-pass');
      b.plugin(mocaccino);
      run('phantomic', b, {}, passOutputAssert(done));
    });

    it('fails test', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-fail');
      b.plugin(mocaccino);
      run('phantomic', b, {}, failOutputAssert(done));
    });

    it('passes coverage', function (done) {
      var b = browserify();
      b.add('./test/fixture/cover-pass');
      b.transform(coverify);
      b.plugin(mocaccino);
      run('phantomic', b, {}, coverage(function (code) {
        assert.equal(code, 0);
        done();
      }));
    });

    it('fails coverage', function (done) {
      var b = browserify();
      b.add('./test/fixture/cover-fail');
      b.transform(coverify);
      b.plugin(mocaccino);
      run('phantomic', b, {}, coverage(function (code) {
        assert.notEqual(code, 0);
        done();
      }));
    });

    it('uses reporter', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-pass');
      b.plugin(mocaccino, { reporter : 'list' });
      run('phantomic', b, {}, function (err, code, out) {
        /*jslint regexp: true*/
        if (err) {
          done(err);
        } else {
          assert.equal(code, 0);
          assert(/passes\:.*[0-9]+ms/.test(out), out);
          done();
        }
      });
    });

    it('only', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-only');
      b.plugin(mocaccino);
      run('phantomic', b, {}, function (err, code) {
        assert.equal(code, 0);
        done(err);
      });
    });

  });

  describe('node', function () {

    it('passes test', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-pass');
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, passOutputAssert(done));
    });

    it('fails test', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-fail');
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, failOutputAssert(done));
    });

    it('passes coverage', function (done) {
      var b = browserify();
      b.add('./test/fixture/cover-pass');
      b.transform(coverify);
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, coverage(function (code) {
        assert.equal(code, 0);
        done();
      }));
    });

    it('fails coverage', function (done) {
      var b = browserify();
      b.add('./test/fixture/cover-fail');
      b.transform(coverify);
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, coverage(function (code) {
        assert.notEqual(code, 0);
        done();
      }));
    });

    it('uses reporter', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-pass');
      b.plugin(mocaccino, { node : true, reporter : 'list' });
      run('node', b, bundleOptionsBare, function (err, code, out) {
        /*jslint regexp: true*/
        if (err) {
          done(err);
        } else {
          assert.equal(code, 0);
          assert(/passes\:.*[0-9]+ms/.test(out), out);
          done();
        }
      });
    });

    it('only', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-only');
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, function (err, code) {
        assert.equal(code, 0);
        done(err);
      });
    });

  });

});
<commit_msg>Increase timeout for phantomjs tests to 10 seconds for travis<commit_after>/*
 * mocaccino.js
 *
 * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
 *
 * @license MIT
 */
/*globals describe, it*/
'use strict';

var assert     = require('assert');
var browserify = require('browserify');
var coverify   = require('coverify');
var spawn      = require('child_process').spawn;
var mocaccino  = require('../lib/mocaccino');

function run(proc, b, opts, done) {
  var p = spawn(proc);
  var s = b.bundle(opts);
  s.on('error', function (err) {
    done(err);
  });
  var out = '';
  p.stdout.on('data', function (data) {
    out += data;
  });
  p.stderr.pipe(process.stderr);
  p.on('close', function (code) {
    done(null, code, out);
  });
  s.pipe(p.stdin);
}

var bundleOptionsBare = {
  detectGlobal     : true,
  insertGlobalVars : ['__dirname', '__filename']
};

function passOutputAssert(done) {
  return function (err, code, out) {
    if (err) {
      done(err);
    } else {
      assert.equal(code, 0);
      assert.equal(out, '1..1\n'
        + 'ok 1 fixture passes\n'
        + '# tests 1\n'
        + '# pass 1\n'
        + '# fail 0\n');
      done();
    }
  };
}

function failOutputAssert(done) {
  return function (err, code, out) {
    if (err) {
      done(err);
    } else {
      assert.equal(code, 1);
      assert.equal(out.substring(0, 28), '1..1\nnot ok 1 fixture fails\n');
      assert(out.indexOf('# tests 1\n# pass 0\n# fail 1') > 1);
      done();
    }
  };
}

function coverage(callback) {
  return function (err, code, out) {
    if (err) {
      callback(err);
    } else {
      assert.equal(code, 0);
      var cov = spawn('coverify');
      //cov.stderr.pipe(process.stderr);
      cov.stdin.write(out);
      cov.stdin.end();
      cov.on('exit', callback);
    }
  };
}

describe('plugin', function () {

  describe('phantomjs', function () {
    this.timeout(10000);

    it('passes test', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-pass');
      b.plugin(mocaccino);
      run('phantomic', b, {}, passOutputAssert(done));
    });

    it('fails test', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-fail');
      b.plugin(mocaccino);
      run('phantomic', b, {}, failOutputAssert(done));
    });

    it('passes coverage', function (done) {
      var b = browserify();
      b.add('./test/fixture/cover-pass');
      b.transform(coverify);
      b.plugin(mocaccino);
      run('phantomic', b, {}, coverage(function (code) {
        assert.equal(code, 0);
        done();
      }));
    });

    it('fails coverage', function (done) {
      var b = browserify();
      b.add('./test/fixture/cover-fail');
      b.transform(coverify);
      b.plugin(mocaccino);
      run('phantomic', b, {}, coverage(function (code) {
        assert.notEqual(code, 0);
        done();
      }));
    });

    it('uses reporter', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-pass');
      b.plugin(mocaccino, { reporter : 'list' });
      run('phantomic', b, {}, function (err, code, out) {
        /*jslint regexp: true*/
        if (err) {
          done(err);
        } else {
          assert.equal(code, 0);
          assert(/passes\:.*[0-9]+ms/.test(out), out);
          done();
        }
      });
    });

    it('only', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-only');
      b.plugin(mocaccino);
      run('phantomic', b, {}, function (err, code) {
        assert.equal(code, 0);
        done(err);
      });
    });

  });

  describe('node', function () {

    it('passes test', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-pass');
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, passOutputAssert(done));
    });

    it('fails test', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-fail');
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, failOutputAssert(done));
    });

    it('passes coverage', function (done) {
      var b = browserify();
      b.add('./test/fixture/cover-pass');
      b.transform(coverify);
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, coverage(function (code) {
        assert.equal(code, 0);
        done();
      }));
    });

    it('fails coverage', function (done) {
      var b = browserify();
      b.add('./test/fixture/cover-fail');
      b.transform(coverify);
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, coverage(function (code) {
        assert.notEqual(code, 0);
        done();
      }));
    });

    it('uses reporter', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-pass');
      b.plugin(mocaccino, { node : true, reporter : 'list' });
      run('node', b, bundleOptionsBare, function (err, code, out) {
        /*jslint regexp: true*/
        if (err) {
          done(err);
        } else {
          assert.equal(code, 0);
          assert(/passes\:.*[0-9]+ms/.test(out), out);
          done();
        }
      });
    });

    it('only', function (done) {
      var b = browserify();
      b.add('./test/fixture/test-only');
      b.plugin(mocaccino, { node : true });
      run('node', b, bundleOptionsBare, function (err, code) {
        assert.equal(code, 0);
        done(err);
      });
    });

  });

});
<|endoftext|>


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

var should = require('should');

describe('Parsing a file (net)', function () {
  it('should parse a RSS from an URL', function (done) {
    this.timeout(40000);

    var parser = require('../index');
    //var url = 'http://ghostbar.co/feed.xml';

    parser('http://ghostbar.co/feed.xml', 10, function (err, response) {
      should.not.exist(err);

      should.exist(response);

      should.exist(response.meta);

      done(err);
    });
  });
});
<commit_msg>testing all (fixes #1)<commit_after>/* global describe */
/* global it */
'use strict';

var should = require('should');
var url = 'http://ghostbar.co/feed.xml';

describe('Parsing a file (net)', function () {
  it('should parse a RSS from an URL', function (done) {
    this.timeout(40000);

    var parser = require('../index');

    parser(url, 10, function (err, response) {
      should.not.exist(err);

      should.exist(response);

      should.exist(response.meta);

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

describe('Parsing a file with getUrl (net)', function () {
  it('should parse a RSS from an URL', function (done) {
    var parser = require('../index').getUrl;

    parser(url, 10, function (err, response) {
      should.not.exist(err);
      should.exist(response);
      should.exist(response.meta);

      done();
    });

  });
});
<|endoftext|>