<commit_before>'use strict';

module.exports = function(sequelize, DataTypes) {
  var models = {
    entry: sequelize.define('entry', {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        validate: {
          isUUID: 4
        },
        primaryKey: true
      },
      date: {
        type: DataTypes.DATE,
        allowNull: false,
        validate: {
          isDate: true,
          notNull: true
        }
      },
      body: {
        type: DataTypes.TEXT,
        allowNull: false,
        validate: {
          notEmpty: true,
          notNull: true
        }
      }
    }, {
    }),

    tag: sequelize.define('tag', {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        allowNull: false,
        validate: {
          isUUID: 4
        },
        primaryKey: true
      },
      value: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
        validate: {
          notNull: true
        }
      }
    }, {
    })
  };

  models.tag.belongsToMany(models.entry, { through: 'entry_tag' });
  models.entry.belongsToMany(models.tag, { through: 'entry_tag' });

  return models;
};
<commit_msg>server/app/util/pr/entry.hs - notNull removed from validate (allowNull in property definition preferred)<commit_after>'use strict';

module.exports = function(sequelize, DataTypes) {
  var models = {
    entry: sequelize.define('entry', {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        validate: {
          isUUID: 4
        },
        primaryKey: true
      },
      date: {
        type: DataTypes.DATE,
        allowNull: false,
        validate: {
          isDate: true,
        }
      },
      body: {
        type: DataTypes.TEXT,
        allowNull: false,
        validate: {
          notEmpty: true,
        }
      }
    }, {
    }),

    tag: sequelize.define('tag', {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        allowNull: false,
        validate: {
          isUUID: 4
        },
        primaryKey: true
      },
      value: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
        validate: {
        }
      }
    }, {
    })
  };

  models.tag.belongsToMany(models.entry, { through: 'entry_tag' });
  models.entry.belongsToMany(models.tag, { through: 'entry_tag' });

  return models;
};
<|endoftext|>


<commit_before>var sinon = require('sinon');
var chai = require('chai');

var should = chai.should();
chai.Assertion.includeStack = true;
chai.use(require('sinon-chai'));

var conjure = require('../../dist/conjure');
var Conjure = conjure.Conjure;
var requireComponent = conjure.require;

requireComponent('sinon-doublist')(sinon, 'mocha');

describe('helpers', function() {
  'use strict';

  /**
   * Pack any remotely reusable boilerplate here to keep the actual tests
   * as small/clear as possible.
   */
  beforeEach(function() {
    var self = this;

    // Stub targets
    this.testApi = {}; // CasperJS's this.test API
    this.extendResult = {iAmA: 'extend() component'};
    this.createdContext = {iAmA: 'createdContext() return value'};
    this.requiredComponent = {iAmA: 'component-land require() return value'};
    this.evaluateResult = {iAmA: 'casper.evaluate() return value'};

    this.stubs = {}; // Reusable stub collection

    // Stubbing CasperJS-land require(), ex. for colorizer module
    this.stubs.requiredComponentCreate = this.stubMany(
      this.requiredComponent, 'create'
    ).create;
    this.stubs.casperRequire = this.stub();
    this.stubs.casperRequire.returns(this.requiredComponent);

    this.conjure = conjure.create(this.stubs.casperRequire);
    this.conjure.casper = {}; // Stub target for CasperJS's this.casper API
    this.stubs.conjure = this.stub(this.conjure.conjure);

    // Use for stubs like: $(sel).<some method>().
    this.stubs.$result = {};

    // Use this.$stub to know what selector $ received.
    GLOBAL.$ = function() {};
    this.stubs.$global = this.stub(GLOBAL, '$').returns(this.stubs.$result);

    // More fixtures and prepared stubs
    this.sel = '.klass';
    this.textNeedle = 'foo';
    this.reNeedle = /foo/;
    this.stubs.cb = this.stub();
    this.stubs.$ = this.stubMany(
      this.stubs.$result,
      [
        'click', 'text'
      ]
    );
    this.stubs.casper = this.stubMany(
      this.conjure.casper,
      [
        'evaluate', 'then', 'thenEvaluate'
      ]
    );
    this.stubs.casper.evaluate.returns(this.evaluateResult);
    this.stubs.casper.then.yieldsOn({
      test: this.testApi,
      evaluate: this.stubs.casper.evaluate
    });
    this.stubs.createContext = this.stub(Conjure, 'createContext');
    this.stubs.createContext.returns(this.createdContext);
    this.stubs.extend = this.stub();
    this.stubs.extend.returns(this.extendResult);
    this.stubs.require = this.stub(conjure, 'require');
    this.stubs.require.withArgs('extend').returns(this.stubs.extend);
    conjure.setRequire(this.stubs.require);
    this.stubs.test = this.stubMany(
      this.testApi,
      [
        'assertEquals', 'assertMatch'
      ]
    );
    this.restoreComponentRequire = function() {
      conjure.setRequire(requireComponent);
    };
  });

  describe('click', function() {
    beforeEach(function() {
      this.stubs.casper.thenEvaluate.yields(this.sel);
      this.stubs.conjure.click.restore();
      this.conjure.click(this.sel);
    });
    it('should wait for selector match' , function() {
      this.stubs.conjure.selectorExists.calledWithExactly(this.sel);
    });
    it('should use jQuery to click' , function() {
      this.stubs.casper.thenEvaluate.should.be.called;
      this.stubs.$global.should.have.been.calledWithExactly(this.sel);
      this.stubs.$.click.should.have.been.called;
    });
  });

  describe('then', function() {
    beforeEach(function() {
      this.stubs.conjure.then.restore();
      this.conjure.then(this.stubs.cb);
    });
    it('should inject context' , function() {
      this.stubs.extend.should.have.been.calledWith(
        this.createdContext,
        {casper: this.conjure.casper, test: this.testApi}
      );
      this.stubs.cb.should.have.been.calledOn(this.extendResult);
    });
  });

  describe('assertSelText', function() {
    beforeEach(function() {
      this.stubs.conjure.assertSelText.restore();
      this.restoreComponentRequire();
    });
    it('should use jQuery text()' , function() {
      this.conjure.assertSelText(this.sel, this.textNeedle);
      this.stubs.test.assertEquals.should.have.been.calledWithExactly(
        this.evaluateResult,
        this.textNeedle
      );
    });
    it('should support regex' , function() {
      this.conjure.assertSelText(this.sel, this.reNeedle);
      this.stubs.test.assertMatch.should.have.been.calledWithExactly(
        this.evaluateResult,
        this.reNeedle
      );
    });
  });
});
<commit_msg>test(mixins): Cover assertType()<commit_after>var sinon = require('sinon');
var chai = require('chai');

var should = chai.should();
chai.Assertion.includeStack = true;
chai.use(require('sinon-chai'));

var conjure = require('../../dist/conjure');
var Conjure = conjure.Conjure;
var requireComponent = conjure.require;

requireComponent('sinon-doublist')(sinon, 'mocha');

describe('helpers', function() {
  'use strict';

  /**
   * Pack any remotely reusable boilerplate here to keep the actual tests
   * as small/clear as possible.
   */
  beforeEach(function() {
    var self = this;

    // Stub targets
    this.testApi = {}; // CasperJS's this.test API
    this.utilsApi = {}; // CasperJS's this.utils API
    this.extendResult = {iAmA: 'extend() component'};
    this.createdContext = {iAmA: 'createdContext() return value'};
    this.requiredComponent = {iAmA: 'component-land require() return value'};
    this.evaluateResult = {iAmA: 'casper.evaluate() return value'};
    this.betterTypeOf = {iAmA: 'utils.betterTypeOf() return value'};
    this.format = {iAmA: 'utils.format() return value'};

    this.stubs = {}; // Reusable stub collection

    // Stubbing CasperJS-land require(), ex. for colorizer module
    this.stubs.requiredComponentCreate = this.stubMany(
      this.requiredComponent, 'create'
    ).create;
    this.stubs.casperRequire = this.stub();
    this.stubs.casperRequire.returns(this.requiredComponent);

    this.conjure = conjure.create(this.stubs.casperRequire);
    this.conjure.casper = {}; // Stub target for CasperJS's this.casper API
    this.stubs.conjure = this.stub(this.conjure.conjure);

    // Use for stubs like: $(sel).<some method>().
    this.stubs.$result = {};

    // Use this.$stub to know what selector $ received.
    GLOBAL.$ = function() {};
    this.stubs.$global = this.stub(GLOBAL, '$').returns(this.stubs.$result);

    // More fixtures and prepared stubs
    this.sel = '.klass';
    this.textNeedle = 'foo';
    this.reNeedle = /foo/;
    this.stubs.cb = this.stub();
    this.stubs.$ = this.stubMany(
      this.stubs.$result,
      [
        'click', 'text'
      ]
    );
    this.stubs.utils = this.stubMany(
      this.utilsApi,
      [
        'betterTypeOf', 'format'
      ]
    );
    this.stubs.utils.betterTypeOf.returns(this.betterTypeOf);
    this.stubs.utils.format.returns(this.format);
    this.stubs.test = this.stubMany(
      this.testApi,
      [
        'assertEquals', 'assertMatch'
      ]
    );
    this.stubs.casper = this.stubMany(
      this.conjure.casper,
      [
        'evaluate', 'then', 'thenEvaluate'
      ]
    );
    this.stubs.casper.evaluate.returns(this.evaluateResult);
    var thenContext = {
      test: this.stubs.test,
      evaluate: this.stubs.casper.evaluate,
      utils: this.stubs.utils
    };
    this.stubs.casper.then.yieldsOn(thenContext);
    this.stubs.conjure.then.yieldsOn(thenContext);
    this.stubs.createContext = this.stub(Conjure, 'createContext');
    this.stubs.createContext.returns(this.createdContext);
    this.stubs.extend = this.stub();
    this.stubs.extend.returns(this.extendResult);
    this.stubs.require = this.stub(conjure, 'require');
    this.stubs.require.withArgs('extend').returns(this.stubs.extend);
    conjure.setRequire(this.stubs.require);
    this.restoreComponentRequire = function() {
      conjure.setRequire(requireComponent);
    };
  });

  describe('click', function() {
    beforeEach(function() {
      this.stubs.casper.thenEvaluate.yields(this.sel);
      this.stubs.conjure.click.restore();
      this.conjure.click(this.sel);
    });
    it('should wait for selector match' , function() {
      this.stubs.conjure.selectorExists.calledWithExactly(this.sel);
    });
    it('should use jQuery to click' , function() {
      this.stubs.casper.thenEvaluate.should.be.called;
      this.stubs.$global.should.have.been.calledWithExactly(this.sel);
      this.stubs.$.click.should.have.been.called;
    });
  });

  describe('then', function() {
    beforeEach(function() {
      this.stubs.conjure.then.restore();
      this.conjure.then(this.stubs.cb);
    });
    it('should inject context' , function() {
      this.stubs.extend.should.have.been.calledWith(
        this.createdContext,
        {casper: this.conjure.casper, test: this.testApi}
      );
      this.stubs.cb.should.have.been.calledOn(this.extendResult);
    });
  });

  describe('assertSelText', function() {
    beforeEach(function() {
      this.stubs.conjure.assertSelText.restore();
      this.restoreComponentRequire();
    });
    it('should use jQuery text()' , function() {
      this.conjure.assertSelText(this.sel, this.textNeedle);
      this.stubs.test.assertEquals.should.have.been.calledWithExactly(
        this.evaluateResult,
        this.textNeedle
      );
    });
    it('should support regex' , function() {
      this.conjure.assertSelText(this.sel, this.reNeedle);
      this.stubs.test.assertMatch.should.have.been.calledWithExactly(
        this.evaluateResult,
        this.reNeedle
      );
    });
  });

  describe('assertType', function() {
    beforeEach(function() {
      this.stubs.conjure.assertType.restore();
    });
    it('should use assertEquals()' , function() {
      this.conjure.assertType(this.sel, 'string');
      this.stubs.utils.betterTypeOf.should.have.been.calledWithExactly(this.sel);
      this.stubs.utils.format.should.have.been.calledWithExactly(
        '%s should be a %s', 'subject', 'string'
      );
      this.stubs.test.assertEquals.should.have.been.calledWithExactly(
        this.betterTypeOf,
        'string',
        this.format
      );
    });
    it('should apply custom subject label' , function() {
      var subject = 'testString';
      this.conjure.assertType(this.sel, 'string', subject);
      this.stubs.utils.format.should.have.been.calledWithExactly(
        '%s should be a %s', subject, 'string'
      );
    });
  });
});
<|endoftext|>


<commit_before>(function ($) {
	var _searchDialog = null;

	function getSearchDialog(cm) {
		if (!_searchDialog) {
			_searchDialog = $('

');
			var searchInput = $('<input type="text" class="CodeMirror-Search-Box main">').on("focus", function () {
					_searchDialog.removeClass("searching");
				}).on("blur", function () {
					_searchDialog.addClass("searching");
				}),
			replaceInput = $('<input type="text" class="CodeMirror-Search-Box">').on("focus", function () {
					_searchDialog.removeClass("searching");
				}).on("blur", function () {
					_searchDialog.addClass("searching");
				}),
			backwardInput = $('<input type="checkbox" class="CodeMirror-Check-Box">'),
			regexInput = $('<input type="checkbox" class="CodeMirror-Check-Box">'),
			close = function () {
				_searchDialog.hide();
				cm.focus();
			},
			doSearch = function () {
				var query = parseQuery(searchInput.val(), regexInput[0].checked);
				var state = getSearchState(cm);
				if (!query) {
					clearSearch(cm);
				} else {
					if (isQueryChanged(state.query, query)) {
						cm.operation(function () {
							if (!query)
								return;
							state.query = parseQuery(query, regexInput[0].checked);
							cm.removeOverlay(state.overlay);
							state.overlay = searchOverlay(state.query);
							cm.addOverlay(state.overlay);
							state.posFrom = state.posTo = cm.getCursor();
							findNext(cm, backwardInput[0].checked);
						});
					} else {
						findNext(cm, backwardInput[0].checked);
					}
				}
				cm.focus();
			},
			replace = function (text, all, next) {
				var query = searchInput.val();
				var state = getSearchState(cm);
				if (isQueryChanged(state.query, query)) {
					return false;
				}
				if (all) {
					cm.operation(function () {
						for (var cursor = getSearchCursor(cm, query); cursor.findNext(); ) {
							if (typeof query != "string") {
								var match = cm.getRange(cursor.from(), cursor.to()).match(query);
								cursor.replace(text.replace(/\$(\d)/, function (_, i) {
										return match[i];
									}));
							} else
								cursor.replace(text);
						}
					});
				} else {
					if (state.posTo.ch == state.posFrom.ch && state.posTo.line == state.posFrom.line) {
						return;
					}
					var cursor = getSearchCursor(cm, query, backwardInput[0].checked ? state.posTo : state.posFrom);
					var start = cursor.from(),
					match;
					if (!(match = backwardInput[0].checked ? cursor.findPrevious() : cursor.findNext())) {
						cursor = getSearchCursor(cm, query);
						if (!(match = backwardInput[0].checked ? cursor.findPrevious() : cursor.findNext())
							 || (start && cursor.from().line == start.line && cursor.from().ch == start.ch))
							return;
					}
					cm.setSelection(cursor.from(), cursor.to());
					cm.scrollIntoView({
						from : cursor.from(),
						to : cursor.to()
					});
					cursor.replace(typeof query == "string" ? text : text.replace(/\$(\d)/, function (_, i) {
							return match[i];
						}));
					if (backwardInput[0].checked) {
						state.posTo = state.posFrom = cursor.from();
					} else {
						state.posTo = state.posFrom = cursor.to();
					}
					if (next) {
						findNext(cm, backwardInput[0].checked);
					}
				}
				cm.focus();
			},
			closeIcon = $('<button type="button" class="btn btn-default btn-xs closeIcon">X</button>').on("click", close),
			sButton = $('<button type="button" class="btn btn-default btn-xs">Find</button>').on('click', doSearch),
			rButton = $('<button type="button" class="btn btn-default btn-xs">Replace</button>').on('click', function () {
					replace(replaceInput.val());
				}),
			rfButton = $('<button type="button" class="btn btn-default btn-xs">Replace/Find</button>').on("click", function () {
					replace(replaceInput.val(), false, true);
				}),
			raButton = $('<button type="button" class="btn btn-default btn-xs">Replace All</button>').on("click", function () {
					replace(replaceInput.val(), true);
				});
			_searchDialog.on("keydown", function (e) {
				if (e.keyCode == 27) {
					close();
					if (e.preventDefault) {
						e.preventDefault();
					} else {
						return false;
					}
				}
			});
			$(cm.getWrapperElement()).append(
				_searchDialog.html(closeIcon).append($("
").append("Search: ").append(searchInput),
					[$("
").append("Back: ").append(backwardInput), $("
").append("Replace: ").append(replaceInput), $("
").append("Regex: ").append(regexInput), $("
").append(sButton, [rButton, rfButton, raButton])]));
		}
		setTimeout(function () {
			_searchDialog.find(".CodeMirror-Search-Box.main").focus();
		}, 200);
		return _searchDialog;
	}
	function isQueryChanged(a, b) {
		if (a === b) {
			return false;
		} else if (a && a.source && b && b.source) {
			return a.source !== b.source;
		} else {
			return true;
		}
	}
	function openDialog(cm) {
		clearSearch(cm);
		closeNotification(cm, null);
		getSearchDialog(cm).show();
	}
	function closeNotification(cm, newVal) {
		if (cm.state.currentNotificationClose)
			cm.state.currentNotificationClose();
		cm.state.currentNotificationClose = newVal;
	}
	function searchOverlay(query) {
		if (typeof query == "string")
			return {
				token : function (stream) {
					if (stream.match(query))
						return "searching";
					stream.next();
					stream.skipTo(query.charAt(0)) || stream.skipToEnd();
				}
			};
		return {
			token : function (stream) {
				if (stream.match(query))
					return "searching";
				while (!stream.eol()) {
					stream.next();
					if (stream.match(query, false))
						break;
				}
			}
		};
	}
	function findNext(cm, rev) {
		cm.operation(function () {
			var state = getSearchState(cm);
			var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
			if (!cursor.find(rev)) {
				cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm
							.firstLine(), 0));
				if (!cursor.find(rev))
					return;
			}
			cm.setSelection(cursor.from(), cursor.to());
			cm.scrollIntoView({
				from : cursor.from(),
				to : cursor.to()
			});
			state.posFrom = cursor.from();
			state.posTo = cursor.to();
		});
	}
	function parseQuery(query, isRE) {
		return isRE ? new RegExp(query) : query;
	}
	function SearchState() {
		this.posFrom = this.posTo = this.query = null;
		this.overlay = null;
	}
	function getSearchState(cm) {
		return cm.state.search || (cm.state.search = new SearchState());
	}
	function getSearchCursor(cm, query, pos) {
		// Heuristic: if the query string is all lowercase, do a case
		// insensitive search.
		return cm.getSearchCursor(query, pos, typeof query == "string" && query == query.toLowerCase());
	}
	function clearSearch(cm) {
		cm.operation(function () {
			var state = getSearchState(cm);
			if (!state.query)
				return;
			state.query = null;
			cm.removeOverlay(state.overlay);
		});
	}

	CodeMirror.commands.find = openDialog;
	CodeMirror.commands.findPrev = openDialog;
	CodeMirror.commands.clearSearch = clearSearch;
	CodeMirror.commands.replace = openDialog;
	CodeMirror.commands.replaceAll = openDialog;
})(jQuery);
<commit_msg>regex replace<commit_after>(function ($) {
	var _searchDialog = null;

	function getSearchDialog(cm) {
		if (!_searchDialog) {
			_searchDialog = $('

');
			var searchInput = $('<input type="text" class="CodeMirror-Search-Box main">').on("focus", function () {
					_searchDialog.removeClass("searching");
				}).on("blur", function () {
					_searchDialog.addClass("searching");
				}),
			replaceInput = $('<input type="text" class="CodeMirror-Search-Box">').on("focus", function () {
					_searchDialog.removeClass("searching");
				}).on("blur", function () {
					_searchDialog.addClass("searching");
				}),
			backwardInput = $('<input type="checkbox" class="CodeMirror-Check-Box">'),
			regexInput = $('<input type="checkbox" class="CodeMirror-Check-Box">'),
			close = function () {
				_searchDialog.hide();
				cm.focus();
			},
			doSearch = function () {
				var query = parseQuery(searchInput.val(), regexInput[0].checked);
				var state = getSearchState(cm);
				if (!query) {
					clearSearch(cm);
				} else {
					if (isQueryChanged(state.query, query)) {
						cm.operation(function () {
							if (!query)
								return;
							state.query = parseQuery(query, regexInput[0].checked);
							cm.removeOverlay(state.overlay);
							state.overlay = searchOverlay(state.query);
							cm.addOverlay(state.overlay);
							state.posFrom = state.posTo = cm.getCursor();
							findNext(cm, backwardInput[0].checked);
						});
					} else {
						findNext(cm, backwardInput[0].checked);
					}
				}
				cm.focus();
			},
			replace = function (text, all, next) {
				var query = parseQuery(searchInput.val(), regexInput[0].checked);
				var state = getSearchState(cm);
				if (isQueryChanged(state.query, query)) {
					return false;
				}
				if (all) {
					cm.operation(function () {
						for (var cursor = getSearchCursor(cm, query); cursor.findNext(); ) {
							if (typeof query != "string") {
								var match = cm.getRange(cursor.from(), cursor.to()).match(query);
								cursor.replace(text.replace(/\$(\d)/, function (_, i) {
										return match[i];
									}));
							} else
								cursor.replace(text);
						}
					});
				} else {
					if (state.posTo.ch == state.posFrom.ch && state.posTo.line == state.posFrom.line) {
						return;
					}
					var cursor = getSearchCursor(cm, query, backwardInput[0].checked ? state.posTo : state.posFrom);
					var start = cursor.from(),
					match;
					if (!(match = backwardInput[0].checked ? cursor.findPrevious() : cursor.findNext())) {
						cursor = getSearchCursor(cm, query);
						if (!(match = backwardInput[0].checked ? cursor.findPrevious() : cursor.findNext())
							 || (start && cursor.from().line == start.line && cursor.from().ch == start.ch))
							return;
					}
					cm.setSelection(cursor.from(), cursor.to());
					cm.scrollIntoView({
						from : cursor.from(),
						to : cursor.to()
					});
					cursor.replace(typeof query == "string" ? text : text.replace(/\$(\d)/, function (_, i) {
							return match[i];
						}));
					if (backwardInput[0].checked) {
						state.posTo = state.posFrom = cursor.from();
					} else {
						state.posTo = state.posFrom = cursor.to();
					}
					if (next) {
						findNext(cm, backwardInput[0].checked);
					}
				}
				cm.focus();
			},
			closeIcon = $('<button type="button" class="btn btn-default btn-xs closeIcon">X</button>').on("click", close),
			sButton = $('<button type="button" class="btn btn-default btn-xs">Find</button>').on('click', doSearch),
			rButton = $('<button type="button" class="btn btn-default btn-xs">Replace</button>').on('click', function () {
					replace(replaceInput.val());
				}),
			rfButton = $('<button type="button" class="btn btn-default btn-xs">Replace/Find</button>').on("click", function () {
					replace(replaceInput.val(), false, true);
				}),
			raButton = $('<button type="button" class="btn btn-default btn-xs">Replace All</button>').on("click", function () {
					replace(replaceInput.val(), true);
				});
			_searchDialog.on("keydown", function (e) {
				if (e.keyCode == 27) {
					close();
					if (e.preventDefault) {
						e.preventDefault();
					} else {
						return false;
					}
				}
			});
			$(cm.getWrapperElement()).append(
				_searchDialog.html(closeIcon).append($("
").append("Search: ").append(searchInput),
					[$("
").append("Back: ").append(backwardInput), $("
").append("Replace: ").append(replaceInput), $("
").append("Regex: ").append(regexInput), $("
").append(sButton, [rButton, rfButton, raButton])]));
		}
		setTimeout(function () {
			_searchDialog.find(".CodeMirror-Search-Box.main").focus();
		}, 200);
		return _searchDialog;
	}
	function isQueryChanged(a, b) {
		if (a === b) {
			return false;
		} else if (a && a.source && b && b.source) {
			return a.source !== b.source;
		} else {
			return true;
		}
	}
	function openDialog(cm) {
		clearSearch(cm);
		closeNotification(cm, null);
		getSearchDialog(cm).show();
	}
	function closeNotification(cm, newVal) {
		if (cm.state.currentNotificationClose)
			cm.state.currentNotificationClose();
		cm.state.currentNotificationClose = newVal;
	}
	function searchOverlay(query) {
		if (typeof query == "string")
			return {
				token : function (stream) {
					if (stream.match(query))
						return "searching";
					stream.next();
					stream.skipTo(query.charAt(0)) || stream.skipToEnd();
				}
			};
		return {
			token : function (stream) {
				if (stream.match(query))
					return "searching";
				while (!stream.eol()) {
					stream.next();
					if (stream.match(query, false))
						break;
				}
			}
		};
	}
	function findNext(cm, rev) {
		cm.operation(function () {
			var state = getSearchState(cm);
			var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
			if (!cursor.find(rev)) {
				cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm
							.firstLine(), 0));
				if (!cursor.find(rev))
					return;
			}
			cm.setSelection(cursor.from(), cursor.to());
			cm.scrollIntoView({
				from : cursor.from(),
				to : cursor.to()
			});
			state.posFrom = cursor.from();
			state.posTo = cursor.to();
		});
	}
	function parseQuery(query, isRE) {
		return isRE ? new RegExp(query) : query;
	}
	function SearchState() {
		this.posFrom = this.posTo = this.query = null;
		this.overlay = null;
	}
	function getSearchState(cm) {
		return cm.state.search || (cm.state.search = new SearchState());
	}
	function getSearchCursor(cm, query, pos) {
		// Heuristic: if the query string is all lowercase, do a case
		// insensitive search.
		return cm.getSearchCursor(query, pos, typeof query == "string" && query == query.toLowerCase());
	}
	function clearSearch(cm) {
		cm.operation(function () {
			var state = getSearchState(cm);
			if (!state.query)
				return;
			state.query = null;
			cm.removeOverlay(state.overlay);
		});
	}

	CodeMirror.commands.find = openDialog;
	CodeMirror.commands.findPrev = openDialog;
	CodeMirror.commands.clearSearch = clearSearch;
	CodeMirror.commands.replace = openDialog;
	CodeMirror.commands.replaceAll = openDialog;
})(jQuery);
<|endoftext|>


<commit_before>define([
    'underscore',
    'backbone',
    'models/core/BaseModel',
], function(_, Backbone, BaseModel) {

    var ProjectModel = BaseModel.extend({

        urlRoot: 'api/projects',

        defaults: {
            id: null,
            project_statuses_id: 1,
            name: 'No project name set',
            description: 'No description set',
            url: '#/404'
        },

        initialize: function(options) {
            _.bindAll(this, 'url', 'parse');
        },

        url: function() {
            return '/api/projects/' + this.id;
        },

        parse: function(obj) {
            if (typeof(obj.project) != 'undefined')
                return obj.project;
            return obj;
        }

    });

    return ProjectModel;

});<commit_msg>Fix saving projects (null project id in model)<commit_after>define([
    'underscore',
    'backbone',
    'models/core/BaseModel',
], function(_, Backbone, BaseModel) {

    var ProjectModel = BaseModel.extend({

        urlRoot: 'api/projects',

        defaults: {
            id: null,
            project_statuses_id: 1,
            name: 'No project name set',
            description: 'No description set',
            url: '#/404'
        },

        initialize: function(options) {
            _.bindAll(this, 'url', 'parse');
        },

        url: function() {
            if (this.id != null)
                return '/api/projects/' + this.id;
            return '/api/projects/';
        },

        parse: function(obj) {
            if (typeof(obj.project) != 'undefined')
                return obj.project;
            return obj;
        }

    });

    return ProjectModel;

});<|endoftext|>


<commit_before>// API for activity spam checker
//
// Copyright 2011, 2012 StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Training and measuring values

var Tokenizer = require('../lib/tokenizer').Tokenizer,
    SpamFilter = require('../lib/spamfilter').SpamFilter;

exports.thisIsSpam = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {

        var app;

        if (error) {
            res.json({error: error.message}, 500);
            return;
        }

        if (!authenticated) {
            return;
        }

        app = req.getAuthDetails().user;

        SpamFilter.train('spam', req.body, app, function(err, trainrec) {
            if (err) {
                res.json({error: err.message}, 500);
            } else {
                res.json(trainrec);
            }
        });
    });
};

exports.thisIsHam = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {

        var app;

        if (error) {
            res.json({error: error.message}, 500);
            return;
        }

        if (!authenticated) {
            return;
        }

        app = req.getAuthDetails().user;

        SpamFilter.train('ham', req.body, app, function(err, trainrec) {
            if (err) {
                res.json({error: err.message}, 500);
            } else {
                res.json(trainrec);
            }
        });
    });
};

var uniq = function(arr) {
    var newArr = [], i;

    for (i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
            newArr.push(arr[i]);
        }
    }

    return newArr;
};

exports.isThisSpam = function(req, res, next) {

    req.authenticate(['oauth'], function(error, authenticated) {

        var app;

        if (error) {
            res.json({error: error.message}, 500);
            return;
        }

        if (!authenticated) {
            return;
        }

        app = req.getAuthDetails().user;

        var tokens = uniq(Tokenizer.tokenize(req.body));

        SpamFilter.test(tokens, function(err, decision) {
            if (err) {
                res.json({error: err.message}, 500);
            } else {
                res.json(decision);
            }
        });
    });
};

exports.testTokenize = function(req, res, next) {

    req.authenticate(['oauth'], function(error, authenticated) {

        var app;

        if (error) {
            res.json({error: error.message}, 500);
            return;
        }

        if (!authenticated) {
            return;
        }

        app = req.getAuthDetails().user;

        var tokens = Tokenizer.tokenize(req.body);
        res.json(tokens);
    });
};
<commit_msg>don't share app ID for trainrecs<commit_after>// API for activity spam checker
//
// Copyright 2011, 2012 StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Training and measuring values

var Tokenizer = require('../lib/tokenizer').Tokenizer,
    SpamFilter = require('../lib/spamfilter').SpamFilter;

exports.thisIsSpam = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {

        var app;

        if (error) {
            res.json({error: error.message}, 500);
            return;
        }

        if (!authenticated) {
            return;
        }

        app = req.getAuthDetails().user;

        SpamFilter.train('spam', req.body, app, function(err, trainrec) {
            if (err) {
                res.json({error: err.message}, 500);
            } else {
                delete trainrec.app;
                res.json(trainrec);
            }
        });
    });
};

exports.thisIsHam = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {

        var app;

        if (error) {
            res.json({error: error.message}, 500);
            return;
        }

        if (!authenticated) {
            return;
        }

        app = req.getAuthDetails().user;

        SpamFilter.train('ham', req.body, app, function(err, trainrec) {
            if (err) {
                res.json({error: err.message}, 500);
            } else {
                delete trainrec.app;
                res.json(trainrec);
            }
        });
    });
};

var uniq = function(arr) {
    var newArr = [], i;

    for (i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
            newArr.push(arr[i]);
        }
    }

    return newArr;
};

exports.isThisSpam = function(req, res, next) {

    req.authenticate(['oauth'], function(error, authenticated) {

        var app;

        if (error) {
            res.json({error: error.message}, 500);
            return;
        }

        if (!authenticated) {
            return;
        }

        app = req.getAuthDetails().user;

        var tokens = uniq(Tokenizer.tokenize(req.body));

        SpamFilter.test(tokens, function(err, decision) {
            if (err) {
                res.json({error: err.message}, 500);
            } else {
                res.json(decision);
            }
        });
    });
};

exports.testTokenize = function(req, res, next) {

    req.authenticate(['oauth'], function(error, authenticated) {

        var app;

        if (error) {
            res.json({error: error.message}, 500);
            return;
        }

        if (!authenticated) {
            return;
        }

        app = req.getAuthDetails().user;

        var tokens = Tokenizer.tokenize(req.body);
        res.json(tokens);
    });
};
<|endoftext|>


<commit_before>var opbeat = require('../')
  , fs = require('fs')
  , nock = require('nock')
  , common = require('common')
  , mockudp = require('mock-udp');

var options = {
    organization_id: 'some-org-id',
    app_id: 'some-app-id',
    secret_token: 'secret',
    handleExceptions: false
};

var disableUncaughtExceptionHandler = {
    handleExceptions: false
};

var _oldConsoleWarn = console.warn;
var mockConsoleWarn = function () {
    console.warn = function () {
        console.warn._called = true;
    };
    console.warn._called = false;
}
var restoreConsoleWarn = function () {
    console.warn = _oldConsoleWarn;
}

describe('opbeat.version', function () {
    it('should be valid', function () {
        opbeat.version.should.match(/^\d+\.\d+\.\d+(-\w+)?$/);
    });

    it('should match package.json', function () {
        var version = require('../package.json').version;
        opbeat.version.should.equal(version);
    });
});

describe('opbeat.createClient', function () {
    var client;
    var skipBody = function (path) { return '*'; };
    beforeEach(function () {
        mockConsoleWarn();
        process.env.NODE_ENV='production';
    });
    afterEach(function () {
        restoreConsoleWarn();
    });

    it('should initialize the client property', function () {
        opbeat.should.not.have.ownProperty('client');
        var client = opbeat.createClient(options);
        opbeat.should.have.ownProperty('client');
        opbeat.client.should.have.ownProperty('dsn');
    });

    it('should parse the DSN with options', function () {
        var expected = {
            protocol: 'https',
            host: 'opbeat.com',
            path: '/api/v1/organizations/some-org-id/apps/some-app-id/errors/'
        };
        client = opbeat.createClient(common.join(options, { hostname: 'my-hostname' }));
        client.dsn.should.eql(expected);
        client.hostname.should.equal('my-hostname');
    });

    it('should pull OPBEAT_ORGANIZATION_ID from environment', function () {
        process.env.OPBEAT_ORGANIZATION_ID='another-org-id';
        client = opbeat.createClient(disableUncaughtExceptionHandler);
        client.organization_id.should.eql('another-org-id');
        delete process.env.OPBEAT_ORGANIZATION_ID; // gotta clean up so it doesn't leak into other tests
    });

    it('should pull OPBEAT_ORGANIZATION_ID from environment when passing options', function () {
        var expected = {
            protocol: 'https',
            host: 'opbeat.com',
            path: '/api/v1/organizations/another-org-id/apps/some-app-id/errors/'
        };
        process.env.OPBEAT_ORGANIZATION_ID='another-org-id';
        client = opbeat.createClient({
            app_id: 'some-app-id',
            secret_token: 'secret',
            handleExceptions: false
        });
        client.dsn.should.eql(expected);
        client.organization_id.should.equal('another-org-id');
        client.app_id.should.equal('some-app-id');
        client.secret_token.should.equal('secret');
        delete process.env.OPBEAT_ORGANIZATION_ID; // gotta clean up so it doesn't leak into other tests
    });

    it('should be disabled when no options have been specified', function () {
        client = opbeat.createClient(disableUncaughtExceptionHandler);
        client._enabled.should.eql(false);
        console.warn._called.should.eql(true);
    });

    it('should pull OPBEAT_APP_ID from environment', function () {
        process.env.OPBEAT_APP_ID='another-app-id';
        client = opbeat.createClient(disableUncaughtExceptionHandler);
        client.app_id.should.eql('another-app-id');
        delete process.env.OPBEAT_APP_ID;
    });

    it('should pull OPBEAT_SECRET_TOKEN from environment', function () {
        process.env.OPBEAT_SECRET_TOKEN='pazz';
        client = opbeat.createClient(disableUncaughtExceptionHandler);
        client.secret_token.should.eql('pazz');
        delete process.env.OPBEAT_SECRET_TOKEN;
    });

    it('should be disabled and warn when NODE_ENV=test', function () {
        process.env.NODE_ENV = 'test';
        client = opbeat.createClient(options);
        client._enabled.should.eql(false);
        console.warn._called.should.eql(true);
    });

    describe('#captureMessage()', function () {
        beforeEach(function () {
            mockConsoleWarn();
            client = opbeat.createClient(options);
        });
        afterEach(function () {
            restoreConsoleWarn();
        });

        it('should send a plain text message to Opbeat server', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .defaultReplyHeaders({'Location': 'foo'})
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(200);

            client.on('logged', function (result) {
                result.should.eql('foo');
                scope.done();
                done();
            });
            client.captureMessage('Hey!');
        });

        it('should emit error when request returns non 200', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(500, { error_message: 'Oops!' });

            client.on('error', function () {
                scope.done();
                done();
            });
            client.captureMessage('Hey!');
        });

        it('shouldn\'t shit it\'s pants when error is emitted without a listener', function () {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(500, { error_message: 'Oops!' });

            client.captureMessage('Hey!');
        });

        it('should attach an Error object when emitting error', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(500, { error_message: 'Oops!' });

            client.on('error', function (err) {
                err.message.should.eql('Opbeat error (500): Oops!');
                scope.done();
                done();
            });

            client.captureMessage('Hey!');
        });

        it('should use `param_message` instead of `message` if given an object as 1st argument', function (done) {
            var oldProcess = client.process;
            client.process = function (kwargs, cb) {
                kwargs.should.not.have.ownProperty('message');
                kwargs.should.have.ownProperty('param_message');
                kwargs.param_message.message.should.eql('Hello %s');
                kwargs.param_message.params.should.be.instanceOf(Array);
                kwargs.param_message.params[0].should.eql('World');
                done();
            };
            client.captureMessage({ message: 'Hello %s', params: ['World'] });
            client.process = oldProcess;
        });
    });

    describe('#captureError()', function () {
        beforeEach(function () {
            mockConsoleWarn();
            client = opbeat.createClient(options);
        });
        afterEach(function () {
            restoreConsoleWarn();
        });

        it('should send an Error to Opbeat server', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .defaultReplyHeaders({'Location': 'foo'})
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(200);

            client.on('logged', function (result) {
                result.should.eql('foo');
                scope.done();
                done();
            });
            client.captureError(new Error('wtf?'));
        });

        it('should send a plain text "error" as a Message instead', function (done) {
            // See: https://github.com/mattrobenolt/raven-node/issues/18
            var old = client.captureMessage;
            client.captureMessage = function (message) {
                // I'm also appending "Error: " to the beginning to help hint
                message.should.equal('Error: wtf?');
                done();
                client.captureMessage = old;
            };
            client.captureError('wtf?');
        });
    });

    describe('#handleUncaughtExceptions()', function () {
        beforeEach(function () {
            mockConsoleWarn();
            client = opbeat.createClient(options);
        });
        afterEach(function () {
            restoreConsoleWarn();
        });

        it('should add itself to the uncaughtException event list', function () {
            var before = process._events.uncaughtException.length;
            client.handleUncaughtExceptions();
            process._events.uncaughtException.length.should.equal(before+1);
            process._events.uncaughtException.pop(); // patch it back to what it was
        });

        it('should send an uncaughtException to Opbeat server', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(200);

            // remove existing uncaughtException handlers
            var before = process._events.uncaughtException;
            process.removeAllListeners('uncaughtException');

            client.handleUncaughtExceptions(function (err) {
                // restore things to how they were
                process._events.uncaughtException = before;
                scope.done();
                done();
            });

            process.emit('uncaughtException', new Error('derp'));
        });
    });
});
<commit_msg>Opbeat responds with 'error'<commit_after>var opbeat = require('../')
  , fs = require('fs')
  , nock = require('nock')
  , common = require('common')
  , mockudp = require('mock-udp');

var options = {
    organization_id: 'some-org-id',
    app_id: 'some-app-id',
    secret_token: 'secret',
    handleExceptions: false
};

var disableUncaughtExceptionHandler = {
    handleExceptions: false
};

var _oldConsoleWarn = console.warn;
var mockConsoleWarn = function () {
    console.warn = function () {
        console.warn._called = true;
    };
    console.warn._called = false;
}
var restoreConsoleWarn = function () {
    console.warn = _oldConsoleWarn;
}

describe('opbeat.version', function () {
    it('should be valid', function () {
        opbeat.version.should.match(/^\d+\.\d+\.\d+(-\w+)?$/);
    });

    it('should match package.json', function () {
        var version = require('../package.json').version;
        opbeat.version.should.equal(version);
    });
});

describe('opbeat.createClient', function () {
    var client;
    var skipBody = function (path) { return '*'; };
    beforeEach(function () {
        mockConsoleWarn();
        process.env.NODE_ENV='production';
    });
    afterEach(function () {
        restoreConsoleWarn();
    });

    it('should initialize the client property', function () {
        opbeat.should.not.have.ownProperty('client');
        var client = opbeat.createClient(options);
        opbeat.should.have.ownProperty('client');
        opbeat.client.should.have.ownProperty('dsn');
    });

    it('should parse the DSN with options', function () {
        var expected = {
            protocol: 'https',
            host: 'opbeat.com',
            path: '/api/v1/organizations/some-org-id/apps/some-app-id/errors/'
        };
        client = opbeat.createClient(common.join(options, { hostname: 'my-hostname' }));
        client.dsn.should.eql(expected);
        client.hostname.should.equal('my-hostname');
    });

    it('should pull OPBEAT_ORGANIZATION_ID from environment', function () {
        process.env.OPBEAT_ORGANIZATION_ID='another-org-id';
        client = opbeat.createClient(disableUncaughtExceptionHandler);
        client.organization_id.should.eql('another-org-id');
        delete process.env.OPBEAT_ORGANIZATION_ID; // gotta clean up so it doesn't leak into other tests
    });

    it('should pull OPBEAT_ORGANIZATION_ID from environment when passing options', function () {
        var expected = {
            protocol: 'https',
            host: 'opbeat.com',
            path: '/api/v1/organizations/another-org-id/apps/some-app-id/errors/'
        };
        process.env.OPBEAT_ORGANIZATION_ID='another-org-id';
        client = opbeat.createClient({
            app_id: 'some-app-id',
            secret_token: 'secret',
            handleExceptions: false
        });
        client.dsn.should.eql(expected);
        client.organization_id.should.equal('another-org-id');
        client.app_id.should.equal('some-app-id');
        client.secret_token.should.equal('secret');
        delete process.env.OPBEAT_ORGANIZATION_ID; // gotta clean up so it doesn't leak into other tests
    });

    it('should be disabled when no options have been specified', function () {
        client = opbeat.createClient(disableUncaughtExceptionHandler);
        client._enabled.should.eql(false);
        console.warn._called.should.eql(true);
    });

    it('should pull OPBEAT_APP_ID from environment', function () {
        process.env.OPBEAT_APP_ID='another-app-id';
        client = opbeat.createClient(disableUncaughtExceptionHandler);
        client.app_id.should.eql('another-app-id');
        delete process.env.OPBEAT_APP_ID;
    });

    it('should pull OPBEAT_SECRET_TOKEN from environment', function () {
        process.env.OPBEAT_SECRET_TOKEN='pazz';
        client = opbeat.createClient(disableUncaughtExceptionHandler);
        client.secret_token.should.eql('pazz');
        delete process.env.OPBEAT_SECRET_TOKEN;
    });

    it('should be disabled and warn when NODE_ENV=test', function () {
        process.env.NODE_ENV = 'test';
        client = opbeat.createClient(options);
        client._enabled.should.eql(false);
        console.warn._called.should.eql(true);
    });

    describe('#captureMessage()', function () {
        beforeEach(function () {
            mockConsoleWarn();
            client = opbeat.createClient(options);
        });
        afterEach(function () {
            restoreConsoleWarn();
        });

        it('should send a plain text message to Opbeat server', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .defaultReplyHeaders({'Location': 'foo'})
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(200);

            client.on('logged', function (result) {
                result.should.eql('foo');
                scope.done();
                done();
            });
            client.captureMessage('Hey!');
        });

        it('should emit error when request returns non 200', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(500, { error: 'Oops!' });

            client.on('error', function () {
                scope.done();
                done();
            });
            client.captureMessage('Hey!');
        });

        it('shouldn\'t shit it\'s pants when error is emitted without a listener', function () {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(500, { error: 'Oops!' });

            client.captureMessage('Hey!');
        });

        it('should attach an Error object when emitting error', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(500, { error: 'Oops!' });

            client.on('error', function (err) {
                err.message.should.eql('Opbeat error (500): Oops!');
                scope.done();
                done();
            });

            client.captureMessage('Hey!');
        });

        it('should use `param_message` instead of `message` if given an object as 1st argument', function (done) {
            var oldProcess = client.process;
            client.process = function (kwargs, cb) {
                kwargs.should.not.have.ownProperty('message');
                kwargs.should.have.ownProperty('param_message');
                kwargs.param_message.message.should.eql('Hello %s');
                kwargs.param_message.params.should.be.instanceOf(Array);
                kwargs.param_message.params[0].should.eql('World');
                done();
            };
            client.captureMessage({ message: 'Hello %s', params: ['World'] });
            client.process = oldProcess;
        });
    });

    describe('#captureError()', function () {
        beforeEach(function () {
            mockConsoleWarn();
            client = opbeat.createClient(options);
        });
        afterEach(function () {
            restoreConsoleWarn();
        });

        it('should send an Error to Opbeat server', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .defaultReplyHeaders({'Location': 'foo'})
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(200);

            client.on('logged', function (result) {
                result.should.eql('foo');
                scope.done();
                done();
            });
            client.captureError(new Error('wtf?'));
        });

        it('should send a plain text "error" as a Message instead', function (done) {
            // See: https://github.com/mattrobenolt/raven-node/issues/18
            var old = client.captureMessage;
            client.captureMessage = function (message) {
                // I'm also appending "Error: " to the beginning to help hint
                message.should.equal('Error: wtf?');
                done();
                client.captureMessage = old;
            };
            client.captureError('wtf?');
        });
    });

    describe('#handleUncaughtExceptions()', function () {
        beforeEach(function () {
            mockConsoleWarn();
            client = opbeat.createClient(options);
        });
        afterEach(function () {
            restoreConsoleWarn();
        });

        it('should add itself to the uncaughtException event list', function () {
            var before = process._events.uncaughtException.length;
            client.handleUncaughtExceptions();
            process._events.uncaughtException.length.should.equal(before+1);
            process._events.uncaughtException.pop(); // patch it back to what it was
        });

        it('should send an uncaughtException to Opbeat server', function (done) {
            var scope = nock('https://opbeat.com')
                .filteringRequestBody(skipBody)
                .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
                .reply(200);

            // remove existing uncaughtException handlers
            var before = process._events.uncaughtException;
            process.removeAllListeners('uncaughtException');

            client.handleUncaughtExceptions(function (err) {
                // restore things to how they were
                process._events.uncaughtException = before;
                scope.done();
                done();
            });

            process.emit('uncaughtException', new Error('derp'));
        });
    });
});
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/greetings', function(req, res, next) {
  res.json({hello: 'world'});
});

module.exports = router;
<commit_msg>Fix #10<commit_after>var express = require('express');
var router = express.Router();

router.get('/greetings', function(req, res, next) {
  res.json({
    hello:   'world'
  });
});

/**
 * GET /question/:id   /ask/:id
 * Route to get question
 */
router.get(/\/(question|ask)\/:id/, function(req, res, next) {
  res.json(dbAnswers[req.params.id]['question'] || {
    error: 'bad id'
  });
});

router.get('/ans(wers?)?/:id/:answer', function(req, res, next) {
  if (dbAnswers[req.params.id])
    res.json({
      goodAnswerIndex: dbAnswers[req.params.id]['goodAnswer'],
      isGoodAnswer: dbAnswers[req.params.id]['goodAnswer'] == req.params.answer
    });
  else
    res.json({
      error: 'bad id'
    });
});

// TODO: do not send goodAnswer
dbAnswers = [{
  id: 0,
  question: {
    question: "Comment vérifiez l'intégrité d'un script inséré à l'aide de la valise <script src=\"..\"> ?",
    answers: [
      "En utilisant l’attribut \"integrity\"",
      "On lit le code et on regarde si il est joli",
      "Je demande l’appel à un ami",
    ]
  },
  goodAnswer: 0
}, {
  id: 1,
  question: {
    question: "Est-il possible d'utiliser des variables globales en CSS3 ?",
    answers: [
      "Oui",
      "Peut-être",
      "Non",
      "Tabarnak, le web c'est pas fait pour moi !",
    ]
  },
  goodAnswer: 0
}];

module.exports = router;
<|endoftext|>


<commit_before>/**
* Current list of errors:
*
* UCDSVM/SVM.PREREQ/classes -> No Boxes
* CSUSB/LBST BA GT/classes -> Courses missing
*
*/

var express = require('express');
var fs      = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var url     = require('url');
var app     = express.Router();

var conjunctions =
{
  andEither : ' AND EITHER ',
  or        : ' OR ',
  and       : ' AND ',
  amp       : ' & '
};

// Displays the schools available to transfer to from De Anza College.
function getSchools(req, res)
{
  var url = 'http://www.assist.org/web-assist/DAC.html';

  request(url, function(error, response, html)
  {
    if(!error)
    {
      var $ = cheerio.load(html);
      var schools = [];

      $('option').each(function(i, elem)
      {
        if($(this).parent().attr('id') == 'oia' && i != 188)
        {
          var school = $(this).text();
          school = school.replace('To:', '').trim();
          var value = $(this).attr('value');
          var url = require("url");
          value = url.parse(value, true).query.oia;
          schools.push( { school: school, value: value} );
        }
      });

      res.send(JSON.stringify(schools));
    }
    else
    {
      res.send(JSON.stringify(
      {
        error: "Error with parsing"
      }));
    }
  });
}

// Displays the majors available at the transfer school.
function getMajors(req, res)
{
  var school = req.params.school;
  var url = 'http://www.assist.org/web-assist/articulationAgreement.do?inst1=none&inst2=none&ia=DAC&ay=15-16&oia='+school+'&dir=1';

  request(url, function(error, response, html)
  {
    if(!error)
    {
      var $ = cheerio.load(html);
      var majors = [];

      $('#title').each(function(i, elem)
      {
        if($(this).text().indexOf("By Major") > -1 &&
          $(this).text().indexOf("Not Available") > -1)
        {
          res.send(JSON.stringify(
          {
            error: "Major not available for this school"
          }));
        }
      });

      $('option').each(function(i , elem)
      {
        if($(this).parent().parent().attr('name') == 'major' &&
          $(this).parent().attr('name') == 'dora' &&
          $(this).attr('value').length > 0 &&
          $(this).attr('value') != '-1')
        {
          var dora = $(this).text();
          var value = $(this).attr('value');
          majors.push( { major: dora, value: value });
        }
      });

      for(var z = 0; z < majors.length; z++)
      {
        majors[z].value = majors[z].value.replace('/','*');
      }

      if(majors.length > 0)
      {
        res.send(JSON.stringify(majors));
      }
      else
      {
        res.send(JSON.stringify(
        {
          error: "Error with school name"
        }));
      }
    }
    else
    {
      res.send(JSON.stringify(
      {
        error: "Error with school name"
      }));
    }
  });
}

// Displays the courses at De Anza College and its articulated course at transfer school.
function getClasses(req, res)
{
  var school = req.params.school;
  var dora = req.params.dora;
  dora = dora.replace('*','%2F');

  // Get the aay value.
  var url = 'http://www.assist.org/web-assist/articulationAgreement.do?inst1=none&inst2=none&ia=DAC&ay=15-16&oia='+school+'&dir=1';
  request(url, function(error, response, html)
  {
    if(!error)
    {
      var aay = getAay(html);

      // Get the iframe.
      var url2 = 'http://www.assist.org/web-assist/report.do?agreement=aa&reportPath=REPORT_2&reportScript=Rep2.pl&event=19&dir=1&sia=DAC&ria='+school+'&ia=DAC&oia='+school+'&aay='+aay+'&ay=15-16&dora='+dora;
      request(url2, function(error, response, html)
      {
        if(!error)
        {
          var url3 = getIframe(html);

          // The iframe data.
          request(url3, function(error, response, html)
          {
            if(!error){
              var $ = cheerio.load(html);
              var text = $('body').text();
              res.send(
              {
                "data": getCourses(text)
              });
            }
            else
            {
              res.send(JSON.stringify(
              {
                error: "Error with major name"
              }));
            }
          });
        }
        else
        {
          res.send(JSON.stringify(
          {
            error: "Error with school name"
          }));
        }
      });
    }
  });
}

function getAay(html)
{
  var aay = '15-16';
  var $ = cheerio.load(html);

  $('input').each(function(i, elem)
  {
    if($(this).parent().attr('name') == 'major' &&
      $(this).attr('name') == 'aay')
    {
      aay = $(this).attr('value');
    }
  });

  return aay;
}

function getIframe(html)
{
  var url;
  var $ = cheerio.load(html);

  $('iframe').each(function(i, elem)
  {
    url = $(this).attr('src');
  });

  return url;
}

function getCourses(text)
{
  text = text.replace(/  +/g, ' ');
  var result = [];
  var from = false;
  var fromCourse = '';
  var toCourse = '';
  var courses = [];

  // Splits the text into course boxes.
  courses = text.match(/---[^-]+\|[^-]+---/g);

  // Split each box into from and to.
  courses.forEach(function(course)
  {
    // Remove dashes and extra notes.
    course = course.replace(/---[^-]*?\n(.*\|[^-]+)---/g, '$1').trim();

    for (var i = 0; i < course.length; ++i)
    {
      if (course[i] == '|' || course[i] == '\n')
      {
        toCourse += '\n';
        fromCourse += '\n';
        from = !from;
      }
      else if (!from)
      {
        toCourse += course[i];
      }
      else if (from)
      {
        fromCourse += course[i];
      }
    }

    if (/\(\d+\.?\d*\)/.test(toCourse) || /\(\d+\.?\d*\)/.test(fromCourse) || !isArticulated(toCourse) || !isArticulated(fromCourse))
    {
      result.push({ toCourse: parseCourse(toCourse), fromCourse: parseCourse(fromCourse) });
    }
    toCourse = '';
    fromCourse = '';
    from = !from;
  });
  return result;
}

function parseCourse(text)
{
  // Splits each course using the units as a marker for the starting line.
  // Conjunction is for course after current.
  var courses = text.replace(/(^.*\(\d+\.?\d*\).|\n*)(^.*\(\d+\.?\d*\))/mg, '$1|$2')
    .replace(/\s\s+/g, ' ')
    .trim()
    .split('|')
    .filter(function(course)
    {
      return course !== '' && course !== '\n';
    });

  courses.forEach(function(elem, i, arr)
  {
    // Move & to end of line.
    var re = new RegExp('(.*)' + conjunctions.amp + '(.*?\\\(\\\d+\.?\\\d*\\\).*)');
    arr[i] = elem.replace(re, '$1 $2' + conjunctions.amp);
  });

  return conjunctionSplit(courses);
}

function conjunctionSplit(array)
{
  var result = [];
  var line = array.join(' ');

  if (line.indexOf(conjunctions.andEither) > -1)
  {
    // More complicated...
  }
  else if (line.indexOf(conjunctions.and) > -1)
  {
    result.push({ and: getAndSplitted(line) });
  }
  else if (line.indexOf(conjunctions.or) > -1)
  {
    result.push({ or: getOrSplitted(line) });
  }
  else if (line.indexOf(conjunctions.amp) > -1)
  {
    result.push({ amp: getAmpSplitted(line) });
  }
  else
  {
    result.push(parseCourseData(line));
  }
  return result;
}

function getAndSplitted(line)
{
  var result = [];
  var andSplitted = line.split(conjunctions.and);

  andSplitted.forEach(function(elem)
  {
    if (elem.indexOf(conjunctions.or) > -1)
    {
      result.push({ or: getOrSplitted(elem) });
    }
    else if (elem.indexOf(conjunctions.amp) > -1)
    {
      result.push({ amp: getAmpSplitted(elem) });
    }
    else
    {
        result.push(parseCourseData(elem));
    }
  });
  return result;
}

function getOrSplitted(line)
{
  var result = [];
  var orSplitted = line.split(conjunctions.or);

  orSplitted.forEach(function(elem)
  {
    if (elem.indexOf(conjunctions.amp) > -1)
    {
      result.push({ amp: getAmpSplitted(elem) });
    }
    else
    {
      result.push(parseCourseData(elem));
    }
  });
  return result;
}

function getAmpSplitted(line)
{
  var result = [];
  var ampSplitted = line.split(conjunctions.amp);
  var course;
  ampSplitted.forEach(function(elem)
  {
    result.push(parseCourseData(elem));
  });
  return result;
}

function parseCourseData(line)
{
  // If course not articulated, result is empty.
  if (!isArticulated(line))
  {
    return;
  }

  var unit = line.match(/\(\d+\.?\d*\)/);
  var code = line.replace(/(^.+?[0-9]+.*?)\s.+/, '$1');
  var title;
  if (unit)
  {
    unit = unit[0];

    title = line.replace(unit, '')
      .replace(code, '')
      .replace(/\s\s+/g, ' ')
      .trim();
    unit = unit.slice(1, -1).trim();
    code = code.replace(/\s\s+/g, ' ').trim();

    return { code: code, title: title, unit: unit };
  }
  return;
}

function isArticulated(line)
{
  var notArticulated  =
  [
    'no course articulated',
    'no articulation',
    'not articulated',
    'no comparable lab',
    'no comparable courses',
    'this course is never articulated'
  ];

  for (var i = 0; i < notArticulated.length; ++i)
  {
    if (line.toLowerCase().indexOf(notArticulated[i]) > -1)
    {
      return false;
    }
  }
  return true;
}
app.get('/schools', getSchools);
app.get('/:school/majors', getMajors);
app.get('/:school/:dora/classes', getClasses);

module.exports = app;<commit_msg>Modified to allow selections from both to and from institutions.<commit_after>/**
* Current list of errors:
*
* UCDSVM/SVM.PREREQ/classes -> No Boxes
* CSUSB/LBST BA GT/classes -> Courses missing
*
*/

var express = require('express');
var fs      = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var url     = require('url');
var app     = express.Router();

// Conjunctions that are found within a course box.
var conjunctions =
{
  andEither : ' AND EITHER ',
  or        : ' OR ',
  and       : ' AND ',
  amp       : ' & '
};

/**~*~*
  Gets the list of available institutions.
*~**/
function get_ias(req, res)
{
  var url = 'http://www.assist.org/web-assist/welcome.html';

  request(url, function(error, response, html)
  {
    if (!error)
    {
      var $ = cheerio.load(html);
      var ias = [];

      $('option').each(function(i)
      {

        // Index i === 0 is default value.
        if($(this).parent().attr('name') == 'ia' && i !== 0)
        {
          var ia = $(this).text();

          // Get rid of .html extension.
          var value = $(this).attr('value')
            .slice(0, -5);
          ias.push( { name: ia, value: value });
        }
      });
      res.send(JSON.stringify(ias));
    }
    else
    {
      res.send(JSON.stringify(
      {
        error: "Error with parsing."
      }));
    }
  });
}

/**~*~*
  Gets the list of transferable institutions from the selected institution.
*~**/
function get_oias(req, res)
{
  var ia = req.params.ia;
  var url = 'http://www.assist.org/web-assist/'+ia+'.html';

  request(url, function(error, response, html)
  {
    if (!error)
    {
      var $ = cheerio.load(html);
      var oias = [];

      $('option').each(function(i)
      {
        if($(this).parent().attr('id') == 'oia' && i != 188)
        {
          var oia = $(this).text();
          if (oia.indexOf('To:') > -1)
          {
            // Some oias have a 'From' field which modifies the ia property of the URL.
            oia = oia.replace('To:', '').trim();

            // Grab only the oia property of the URL in value.
            var value = $(this).attr('value');
            var url = require("url");
            value = url.parse(value, true).query.oia;
            oias.push( { name: oia, value: value} );
          }
        }
      });
      res.send(JSON.stringify(oias));
    }
    else
    {
      res.send(JSON.stringify(
      {
        error: "Error with parsing."
      }));
    }
  });
}

/**~*~*
  Gets the majors available at oia.
*~**/
function get_doras(req, res)
{
  var ia = req.params.ia;
  var oia = req.params.oia;
  var url = 'http://www.assist.org/web-assist/articulationAgreement.do?inst1=none&inst2=none&ia='+ia+'&ay=15-16&oia='+oia+'&dir=1';

  request(url, function(error, response, html)
  {
    if (!error)
    {
      var $ = cheerio.load(html);
      var majors = [];

      $('#title').each(function()
      {
        if($(this).text().indexOf("By Major") > -1 &&
          $(this).text().indexOf("Not Available") > -1)
        {
          res.send(JSON.stringify(
          {
            error: "Major not available for this school"
          }));
        }
      });

      $('option').each(function()
      {
        if($(this).parent().parent().attr('name') == 'major' &&
          $(this).parent().attr('name') == 'dora' &&
          $(this).attr('value').length > 0 &&
          $(this).attr('value') != '-1')
        {
          var dora = $(this).text();
          var value = $(this).attr('value');
          majors.push( { major: dora, value: value });
        }
      });

      for(var z = 0; z < majors.length; z++)
      {
        majors[z].value = majors[z].value.replace('/','*');
      }

      if(majors.length > 0)
      {
        res.send(JSON.stringify(majors));
      }
      else
      {
        res.send(JSON.stringify(
        {
          error: "Error with school name"
        }));
      }
    }
    else
    {
      res.send(JSON.stringify(
      {
        error: "Error with school name"
      }));
    }
  });
}

/**~*~*
  Gets the courses articulated between ia and oia.
*~**/
function getCourses(req, res)
{
  var ia = req.params.ia;
  var oia = req.params.oia;
  var dora = req.params.dora;
  dora = dora.replace('*','%2F');

  // Get the aay value.
  var url = 'http://www.assist.org/web-assist/articulationAgreement.do?inst1=none&inst2=none&ia='+ia+'&ay=15-16&oia='+oia+'&dir=1';
  request(url, function(error, response, html)
  {
    if(!error)
    {
      var aay = getAay(html);

      // Get the iframe.
      var url2 = 'http://www.assist.org/web-assist/report.do?agreement=aa&reportPath=REPORT_2&reportScript=Rep2.pl&event=19&dir=1&sia='+ia+'&ria='+oia+'&ia='+ia+'&oia='+oia+'&aay='+aay+'&ay=15-16&dora='+dora;
      request(url2, function(error, response, html)
      {
        if(!error)
        {
          var url3 = getIframe(html);

          // The iframe data.
          request(url3, function(error, response, html)
          {
            if(!error){
              var $ = cheerio.load(html);
              var text = $('body').text();
              res.send(
              {
                "data": getArticulations(text)
              });
            }
            else
            {
              res.send(JSON.stringify(
              {
                error: "Error with major name"
              }));
            }
          });
        }
        else
        {
          res.send(JSON.stringify(
          {
            error: "Error with school name"
          }));
        }
      });
    }
  });
}

/**~*~*
  Gets the aay value for institutions that have an older articulation agreement.
*~**/
function getAay(html)
{
  var aay = '15-16';
  var $ = cheerio.load(html);

  $('input').each(function(i, elem)
  {
    if($(this).parent().attr('name') == 'major' &&
      $(this).attr('name') == 'aay')
    {
      aay = $(this).attr('value');
    }
  });

  return aay;
}

/**~*~*
  Gets the iframe that contains the articulation agreement between the two institutions.
*~**/
function getIframe(html)
{
  var url;
  var $ = cheerio.load(html);

  $('iframe').each(function(i, elem)
  {
    url = $(this).attr('src');
  });

  return url;
}

/**~*~*
  Gets the articulated courses from the two institutions.
*~**/
function getArticulations(text)
{
  text = text.replace(/  +/g, ' ');
  var result = [];
  var from = false;
  var iaCourse = '';
  var oiaCourse = '';
  var courses = [];

  // Splits the text into course boxes.
  courses = text.match(/---[^-]+\|[^-]+---/g);

  // Split each box into from and to.
  courses.forEach(function(course)
  {
    // Remove dashes and extra notes.
    course = course.replace(/---[^-]*?\n(.*\|[^-]+)---/g, '$1').trim();

    for (var i = 0; i < course.length; ++i)
    {
      if (course[i] == '|' || course[i] == '\n')
      {
        oiaCourse += '\n';
        iaCourse += '\n';
        from = !from;
      }
      else if (!from)
      {
        oiaCourse += course[i];
      }
      else if (from)
      {
        iaCourse += course[i];
      }
    }

    if (/\(\d+\.?\d*\)/.test(oiaCourse) || /\(\d+\.?\d*\)/.test(iaCourse) || !isArticulated(oiaCourse) || !isArticulated(iaCourse))
    {
      result.push({ iaCourse: parseCourse(iaCourse), oiaCourse: parseCourse(oiaCourse) });
    }
    oiaCourse = '';
    iaCourse = '';
    from = !from;
  });
  return result;
}

/**~*~*
  Extracts the course information from raw course data.
*~**/
function parseCourse(text)
{
  // Splits each course using the units as a marker for the starting line.
  var courses = text.replace(/(^.*\(\d+\.?\d*\).|\n*)(^.*\(\d+\.?\d*\))/mg, '$1|$2')
    .replace(/\s\s+/g, ' ')
    .trim()
    .split('|')
    .filter(function(course)
    {
      return course !== '' && course !== '\n';
    });

  courses.forEach(function(elem, i, arr)
  {
    // Move & to end of line.
    var re = new RegExp('(.*)' + conjunctions.amp + '(.*?\\\(\\\d+\.?\\\d*\\\).*)');
    arr[i] = elem.replace(re, '$1 $2' + conjunctions.amp);
  });

  return conjunctionSplit(courses);
}

/**~*~*
  Splits the courses into individual courses connected by conjunctions.
*~**/
function conjunctionSplit(array)
{
  var result = [];
  var line = array.join(' ');

  if (line.indexOf(conjunctions.andEither) > -1)
  {
    // More complicated...
  }
  else if (line.indexOf(conjunctions.and) > -1)
  {
    result.push({ and: getAndSplitted(line) });
  }
  else if (line.indexOf(conjunctions.or) > -1)
  {
    result.push({ or: getOrSplitted(line) });
  }
  else if (line.indexOf(conjunctions.amp) > -1)
  {
    result.push({ amp: getAmpSplitted(line) });
  }
  else
  {
    result.push(parseCourseData(line));
  }
  return result;
}

function getAndSplitted(line)
{
  var result = [];
  var andSplitted = line.split(conjunctions.and);

  andSplitted.forEach(function(elem)
  {
    if (elem.indexOf(conjunctions.or) > -1)
    {
      result.push({ or: getOrSplitted(elem) });
    }
    else if (elem.indexOf(conjunctions.amp) > -1)
    {
      result.push({ amp: getAmpSplitted(elem) });
    }
    else
    {
        result.push(parseCourseData(elem));
    }
  });
  return result;
}

function getOrSplitted(line)
{
  var result = [];
  var orSplitted = line.split(conjunctions.or);

  orSplitted.forEach(function(elem)
  {
    if (elem.indexOf(conjunctions.amp) > -1)
    {
      result.push({ amp: getAmpSplitted(elem) });
    }
    else
    {
      result.push(parseCourseData(elem));
    }
  });
  return result;
}

function getAmpSplitted(line)
{
  var result = [];
  var ampSplitted = line.split(conjunctions.amp);
  var course;
  ampSplitted.forEach(function(elem)
  {
    result.push(parseCourseData(elem));
  });
  return result;
}

function parseCourseData(line)
{
  // If course not articulated, result is empty.
  if (!isArticulated(line))
  {
    return;
  }

  var unit = line.match(/\(\d+\.?\d*\)/);
  var code = line.replace(/(^.+?[0-9]+.*?)\s.+/, '$1');
  var title;
  if (unit)
  {
    unit = unit[0];

    title = line.replace(unit, '')
      .replace(code, '')
      .replace(/\s\s+/g, ' ')
      .trim();
    unit = unit.slice(1, -1).trim();
    code = code.replace(/\s\s+/g, ' ').trim();

    return { code: code, title: title, unit: unit };
  }
  return;
}

function isArticulated(line)
{
  var notArticulated  =
  [
    'no course articulated',
    'no articulation',
    'not articulated',
    'no comparable lab',
    'no comparable courses',
    'this course is never articulated'
  ];

  for (var i = 0; i < notArticulated.length; ++i)
  {
    if (line.toLowerCase().indexOf(notArticulated[i]) > -1)
    {
      return false;
    }
  }
  return true;
}

app.get('/ias', get_ias);
app.get('/:ia/oias', get_oias);
app.get('/:ia/:oia/dora', get_doras);
app.get('/:ia/:oia/:dora/courses', getCourses);

module.exports = app;<|endoftext|>


<commit_before>import test from 'tape'
import queryBuilder from '../src/query-builder'

test('queryBuilder | match_all', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_all')

  t.deepEqual(result.getQuery(), {
    match_all: {}
  })
})

test('queryBuilder | match_all with boost', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_all', { boost: 1.2 })

  t.deepEqual(result.getQuery(), {
    match_all: {
      boost: 1.2
    }
  })
})

test('queryBuilder | match_none', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_none')

  t.deepEqual(result.getQuery(), {
    match_none: {}
  })
})

test('queryBuilder | match', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match', 'message', 'this is a test')

  t.deepEqual(result.getQuery(), {
    match: {
      message: 'this is a test'
    }
  })
})

test('queryBuilder | match with options', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match', 'message', {
    query: 'this is a test',
    operator: 'and'
  })

  t.deepEqual(result.getQuery(), {
    match: {
      message: {
        query: 'this is a test',
        operator: 'and'
      }
    }
  })
})

test('queryBuilder | match_phrase', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_phrase', 'message', 'this is a test')

  t.deepEqual(result.getQuery(), {
    match_phrase: {
      message: 'this is a test'
    }
  })
})

test('queryBuilder | match_phrase with options', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_phrase', 'message', {
    query: 'this is a test',
    analyzer: 'my_analyzer'
  })

  t.deepEqual(result.getQuery(), {
    match_phrase: {
      message: {
        query: 'this is a test',
        analyzer: 'my_analyzer'
      }
    }
  })
})

test('queryBuilder | common', (t) => {
  t.plan(1)

  const result = queryBuilder().query('common', 'body', {
    query: 'this is bonsai cool',
    cutoff_frequency: 0.001
  })

  t.deepEqual(result.getQuery(), {
    common: {
      body: {
        query: 'this is bonsai cool',
        cutoff_frequency: 0.001
      }
    }
  })
})

test('queryBuilder | common', (t) => {
  t.plan(1)

  const result = queryBuilder().query('common', 'body', {
    query: 'this is bonsai cool',
    cutoff_frequency: 0.001
  })

  t.deepEqual(result.getQuery(), {
    common: {
      body: {
        query: 'this is bonsai cool',
        cutoff_frequency: 0.001
      }
    }
  })
})

test('queryBuilder | query_string', (t) => {
  t.plan(1)

  const result = queryBuilder().query('query_string', 'query', 'this AND that OR thus')

  t.deepEqual(result.getQuery(), {
    query_string: {
      query: 'this AND that OR thus'
    }
  })
})

test('queryBuilder | query_string with options', (t) => {
  t.plan(1)

  const result = queryBuilder().query('query_string', 'query', 'this AND that OR thus', {
    fields: ['content', 'name']
  })

  t.deepEqual(result.getQuery(), {
    query_string: {
      query: 'this AND that OR thus',
      fields: ['content', 'name']
    }
  })
})

test('queryBuilder | query_string alternative', (t) => {
  t.plan(1)

  const result = queryBuilder().query('query_string', {
    query: 'this AND that OR thus',
    fields: ['content', 'name']
  })

  t.deepEqual(result.getQuery(), {
    query_string: {
      query: 'this AND that OR thus',
      fields: ['content', 'name']
    }
  })
})

test('queryBuilder | simple_query_string', (t) => {
  t.plan(1)

  const result = queryBuilder().query('simple_query_string', 'query', 'foo bar baz')

  t.deepEqual(result.getQuery(), {
    simple_query_string: {
      query: 'foo bar baz'
    }
  })
})

test('queryBuilder | term', (t) => {
  t.plan(1)

  const result = queryBuilder().query('term', 'user', 'kimchy')

  t.deepEqual(result.getQuery(), {
    term: {
      user: 'kimchy'
    }
  })
})

test('queryBuilder | term with boost', (t) => {
  t.plan(1)

  const result = queryBuilder().query('term', 'status', {
    value: 'urgent',
    boost: '2.0'
  })

  t.deepEqual(result.getQuery(), {
    term: {
      status: {
        value: 'urgent',
        boost: '2.0'
      }
    }
  })
})

test('queryBuilder | term multiple', (t) => {
  t.plan(1)

  const result = queryBuilder()
    .orQuery('term', 'status', {
      value: 'urgent',
      boost: '2.0'
    })
    .orQuery('term', 'status', 'normal')

  t.deepEqual(result.getQuery(), {
    bool: {
      should: [{
        term: {
          status: {
            value: 'urgent',
            boost: '2.0'
          }
        }
      }, {
        term: {
          status: 'normal'
        }
      }]
    }
  })
})

test('queryBuilder | terms', (t) => {
  t.plan(1)

  const result = queryBuilder().query('terms', 'user', ['kimchy', 'elastic'])

  t.deepEqual(result.getQuery(), {
    terms: {
      user: ['kimchy', 'elastic']
    }
  })
})

test('queryBuilder | range', (t) => {
  t.plan(1)

  const result = queryBuilder().query('range', 'age', { gte: 10 })

  t.deepEqual(result.getQuery(), {
    range: {
      age: { gte: 10 }
    }
  })
})

test('queryBuilder | exists', (t) => {
  t.plan(1)

  const result = queryBuilder().query('exists', 'user')

  t.deepEqual(result.getQuery(), {
    exists: {
      field: 'user'
    }
  })
})
<commit_msg>Add more query tests<commit_after>import test from 'tape'
import queryBuilder from '../src/query-builder'

test('queryBuilder | match_all', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_all')

  t.deepEqual(result.getQuery(), {
    match_all: {}
  })
})

test('queryBuilder | match_all with boost', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_all', { boost: 1.2 })

  t.deepEqual(result.getQuery(), {
    match_all: {
      boost: 1.2
    }
  })
})

test('queryBuilder | match_none', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_none')

  t.deepEqual(result.getQuery(), {
    match_none: {}
  })
})

test('queryBuilder | match', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match', 'message', 'this is a test')

  t.deepEqual(result.getQuery(), {
    match: {
      message: 'this is a test'
    }
  })
})

test('queryBuilder | match with options', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match', 'message', {
    query: 'this is a test',
    operator: 'and'
  })

  t.deepEqual(result.getQuery(), {
    match: {
      message: {
        query: 'this is a test',
        operator: 'and'
      }
    }
  })
})

test('queryBuilder | match_phrase', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_phrase', 'message', 'this is a test')

  t.deepEqual(result.getQuery(), {
    match_phrase: {
      message: 'this is a test'
    }
  })
})

test('queryBuilder | match_phrase with options', (t) => {
  t.plan(1)

  const result = queryBuilder().query('match_phrase', 'message', {
    query: 'this is a test',
    analyzer: 'my_analyzer'
  })

  t.deepEqual(result.getQuery(), {
    match_phrase: {
      message: {
        query: 'this is a test',
        analyzer: 'my_analyzer'
      }
    }
  })
})

test('queryBuilder | common', (t) => {
  t.plan(1)

  const result = queryBuilder().query('common', 'body', {
    query: 'this is bonsai cool',
    cutoff_frequency: 0.001
  })

  t.deepEqual(result.getQuery(), {
    common: {
      body: {
        query: 'this is bonsai cool',
        cutoff_frequency: 0.001
      }
    }
  })
})

test('queryBuilder | common', (t) => {
  t.plan(1)

  const result = queryBuilder().query('common', 'body', {
    query: 'this is bonsai cool',
    cutoff_frequency: 0.001
  })

  t.deepEqual(result.getQuery(), {
    common: {
      body: {
        query: 'this is bonsai cool',
        cutoff_frequency: 0.001
      }
    }
  })
})

test('queryBuilder | query_string', (t) => {
  t.plan(1)

  const result = queryBuilder().query('query_string', 'query', 'this AND that OR thus')

  t.deepEqual(result.getQuery(), {
    query_string: {
      query: 'this AND that OR thus'
    }
  })
})

test('queryBuilder | query_string with options', (t) => {
  t.plan(1)

  const result = queryBuilder().query('query_string', 'query', 'this AND that OR thus', {
    fields: ['content', 'name']
  })

  t.deepEqual(result.getQuery(), {
    query_string: {
      query: 'this AND that OR thus',
      fields: ['content', 'name']
    }
  })
})

test('queryBuilder | query_string alternative', (t) => {
  t.plan(1)

  const result = queryBuilder().query('query_string', {
    query: 'this AND that OR thus',
    fields: ['content', 'name']
  })

  t.deepEqual(result.getQuery(), {
    query_string: {
      query: 'this AND that OR thus',
      fields: ['content', 'name']
    }
  })
})

test('queryBuilder | simple_query_string', (t) => {
  t.plan(1)

  const result = queryBuilder().query('simple_query_string', 'query', 'foo bar baz')

  t.deepEqual(result.getQuery(), {
    simple_query_string: {
      query: 'foo bar baz'
    }
  })
})

test('queryBuilder | term', (t) => {
  t.plan(1)

  const result = queryBuilder().query('term', 'user', 'kimchy')

  t.deepEqual(result.getQuery(), {
    term: {
      user: 'kimchy'
    }
  })
})

test('queryBuilder | term with boost', (t) => {
  t.plan(1)

  const result = queryBuilder().query('term', 'status', {
    value: 'urgent',
    boost: '2.0'
  })

  t.deepEqual(result.getQuery(), {
    term: {
      status: {
        value: 'urgent',
        boost: '2.0'
      }
    }
  })
})

test('queryBuilder | term multiple', (t) => {
  t.plan(1)

  const result = queryBuilder()
    .orQuery('term', 'status', {
      value: 'urgent',
      boost: '2.0'
    })
    .orQuery('term', 'status', 'normal')

  t.deepEqual(result.getQuery(), {
    bool: {
      should: [{
        term: {
          status: {
            value: 'urgent',
            boost: '2.0'
          }
        }
      }, {
        term: {
          status: 'normal'
        }
      }]
    }
  })
})

test('queryBuilder | terms', (t) => {
  t.plan(1)

  const result = queryBuilder().query('terms', 'user', ['kimchy', 'elastic'])

  t.deepEqual(result.getQuery(), {
    terms: {
      user: ['kimchy', 'elastic']
    }
  })
})

test('queryBuilder | range', (t) => {
  t.plan(1)

  const result = queryBuilder().query('range', 'age', { gte: 10 })

  t.deepEqual(result.getQuery(), {
    range: {
      age: { gte: 10 }
    }
  })
})

test('queryBuilder | exists', (t) => {
  t.plan(1)

  const result = queryBuilder().query('exists', 'user')

  t.deepEqual(result.getQuery(), {
    exists: {
      field: 'user'
    }
  })
})

test('queryBuilder | missing', (t) => {
  t.plan(1)

  const result = queryBuilder().query('missing', 'user')

  t.deepEqual(result.getQuery(), {
    missing: {
      field: 'user'
    }
  })
})

test('queryBuilder | prefix', (t) => {
  t.plan(1)

  const result = queryBuilder().query('prefix', 'user', 'ki')

  t.deepEqual(result.getQuery(), {
    prefix: {
      user: 'ki'
    }
  })
})

test('queryBuilder | prefix with boost', (t) => {
  t.plan(1)

  const result = queryBuilder().query('prefix', 'user', {value: 'ki', boost: 2})

  t.deepEqual(result.getQuery(), {
    prefix: {
      user: {
        value: 'ki',
        boost: 2
      }
    }
  })
})

test('queryBuilder | wildcard', (t) => {
  t.plan(1)

  const result = queryBuilder().query('wildcard', 'user', 'ki*y')

  t.deepEqual(result.getQuery(), {
    wildcard: {
      user: 'ki*y'
    }
  })
})

test('queryBuilder | regexp', (t) => {
  t.plan(1)

  const result = queryBuilder().query('regexp', 'name.first', 's.*y')

  t.deepEqual(result.getQuery(), {
    regexp: {
      'name.first': 's.*y'
    }
  })
})

test('queryBuilder | fuzzy', (t) => {
  t.plan(1)

  const result = queryBuilder().query('fuzzy', 'user', 'ki')

  t.deepEqual(result.getQuery(), {
    fuzzy: {
      user: 'ki'
    }
  })
})

test('queryBuilder | type', (t) => {
  t.plan(1)

  const result = queryBuilder().query('type', 'value', 'my_type')

  t.deepEqual(result.getQuery(), {
    type: {
      value: 'my_type'
    }
  })
})

test('queryBuilder | ids', (t) => {
  t.plan(1)

  const result = queryBuilder().query('ids', 'type', 'my_ids', {
    values: ['1', '4', '100']
  })

  t.deepEqual(result.getQuery(), {
    ids: {
      type: 'my_ids',
      values: ['1', '4', '100']
    }
  })
})

test('queryBuilder | constant_score', (t) => {
  t.plan(1)

  const result = queryBuilder().query('constant_score', { boost: 1.2 }, (q) => {
    return q.filter('term', 'user', 'kimchy')
  })

  t.deepEqual(result.getQuery(), {
    constant_score: {
      filter: {
        term: { user: 'kimchy' }
      },
      boost: 1.2
    }
  })
})

test('queryBuilder | nested', (t) => {
  t.plan(1)

  const result = queryBuilder().query('nested', {path: 'obj1', score_mode: 'avg'}, (q) => {
    return q.query('match', 'obj1.name', 'blue')
            .query('range', 'obj1.count', {gt: 5})
  })

  t.deepEqual(result.getQuery(), {
    nested: {
      path: 'obj1',
      score_mode: 'avg',
      query: {
        bool: {
          must: [
            {
              match: {'obj1.name': 'blue'}
            },
            {
              range: {'obj1.count': {gt: 5}}
            }
          ]
        }
      }
    }
  })
})

test('queryBuilder | has_child', (t) => {
  t.plan(1)

  const result = queryBuilder().query('has_child', 'type', 'blog_tag', (q) => {
    return q.query('term', 'tag', 'something')
  })

  t.deepEqual(result.getQuery(), {
    has_child: {
      type: 'blog_tag',
      query: {
        term: { tag: 'something' }
      }
    }
  })
})

test('queryBuilder | has_parent', (t) => {
  t.plan(1)

  const result = queryBuilder().query('has_parent', 'parent_tag', 'blog', (q) => {
    return q.query('term', 'tag', 'something')
  })

  t.deepEqual(result.getQuery(), {
    has_parent: {
      parent_tag: 'blog',
      query: {
        term: { tag: 'something' }
      }
    }
  })
})

test('queryBuilder | geo_bounding_box', (t) => {
  t.plan(1)

  const result = queryBuilder().query('geo_bounding_box', 'pin.location', {
    top_left: { lat: 40, lon: -74 },
    bottom_right: { lat: 40, lon: -74 }
  }, {
    relation: 'within'
  })

  t.deepEqual(result.getQuery(), {
    geo_bounding_box: {
      relation: 'within',
      'pin.location': {
        top_left: { lat: 40, lon: -74 },
        bottom_right: { lat: 40, lon: -74 }
      }
    }
  })
})

test('queryBuilder | geo_distance', (t) => {
  t.plan(1)

  const result = queryBuilder().query('geo_distance', 'pin.location', {
    lat: 40,
    lon: -74
  }, {
    distance: '200km'
  })

  t.deepEqual(result.getQuery(), {
    geo_distance: {
      distance: '200km',
      'pin.location': {
        lat: 40,
        lon: -74
      }
    }
  })
})

test('queryBuilder | geo_distance_range', (t) => {
  t.plan(1)

  const result = queryBuilder().query('geo_distance_range', 'pin.location', {
    lat: 40,
    lon: -74
  }, {
    from: '100km',
    to: '200km'
  })

  t.deepEqual(result.getQuery(), {
    geo_distance_range: {
      from: '100km',
      to: '200km',
      'pin.location': {
        lat: 40,
        lon: -74
      }
    }
  })
})

test('queryBuilder | geo_polygon', (t) => {
  t.plan(1)

  const result = queryBuilder().query('geo_polygon', 'person.location', {
    points: [
      {lat : 40, lon : -70},
      {lat : 30, lon : -80},
      {lat : 20, lon : -90}
    ]
  })

  t.deepEqual(result.getQuery(), {
    geo_polygon: {
      'person.location': {
        points: [
          {lat : 40, lon : -70},
          {lat : 30, lon : -80},
          {lat : 20, lon : -90}
        ]
      }
    }
  })
})

test('queryBuilder | geohash_cell', (t) => {
  t.plan(1)

  const result = queryBuilder().query('geohash_cell', 'pin', {
    lat: 13.4080,
    lon: 52.5186
  }, {
    precision: 3,
    neighbors: true
  })

  t.deepEqual(result.getQuery(), {
    geohash_cell: {
      pin: {
        lat: 13.4080,
        lon: 52.5186
      },
      precision: 3,
      neighbors: true
    }
  })
})

test('queryBuilder | more_like_this', (t) => {
  t.plan(1)

  const result = queryBuilder().query('more_like_this', {
    fields: ['title', 'description'],
    like: "Once upon a time",
    min_term_freq: 1,
    max_query_terms: 12
  })

  t.deepEqual(result.getQuery(), {
    more_like_this: {
      fields: ['title', 'description'],
      like: "Once upon a time",
      min_term_freq: 1,
      max_query_terms: 12
    }
  })
})

test('queryBuilder | template', (t) => {
  t.plan(1)

  const result = queryBuilder().query('template', {
    inline: { match: { text: '{{query_string}}' }},
    params: {
      query_string: 'all about search'
    }
  })

  t.deepEqual(result.getQuery(), {
    template: {
      inline: { match: { text: '{{query_string}}' }},
      params: {
        query_string: 'all about search'
      }
    }
  })
})

test('queryBuilder | script', (t) => {
  t.plan(1)

  const result = queryBuilder().query('script', 'script', {
    inline: "doc['num1'].value > 1",
    lang: 'painless'
  })

  t.deepEqual(result.getQuery(), {
    script: {
      script: {
        inline: "doc['num1'].value > 1",
        lang: 'painless'
      }
    }
  })
})
<|endoftext|>