<commit_before>import _ from 'lodash';

export default class MQEQuery {

  /** @ngInject */
  constructor(target, templateSrv, scopedVars) {
    this.target = target;
    this.templateSrv = templateSrv;
    // this.templateSrv.formatValue = formatMQEMetric;
    this.scopedVars = scopedVars;
  }

  /////////////////////
  // Query Rendering //
  /////////////////////

  render(metricList, timeFrom, timeTo, interval) {
    let target = this.target;
    let metrics = [];

    for (let m of target.metrics) {
      let metric = m.metric;
      if (metric) {
        if (containsWildcard(metric)) {
          let filteredMetrics = filterMetrics(metric, metricList);

          // Add alias
          if (m.alias) {
            if (containsWildcard(m.alias)) {
              // Set whildcard part as metric alias
              // query: os.cpu.* alias: * -> metric: os.cpu.system -> alias: system
              filteredMetrics = _.map(filteredMetrics,
                _.partial(convertMetricWithWildcard, metric));
            } else {
              filteredMetrics = _.map(filteredMetrics,
                _.compose(_.partial(addMQEAlias, m.alias), wrapMetric));
            }
          } else {
            filteredMetrics = _.map(filteredMetrics, wrapMetric);
          }

          metrics = metrics.concat(filteredMetrics);
        } else {
          metric = wrapMetric(metric);

          // Add alias
          if (m.alias) {
            metric = addMQEAlias(m.alias, metric);
          }

          metrics = metrics.concat(metric);
        }
      }
    }
    metrics = _.uniq(metrics);

    return _.map(metrics, metric => {
      let query = "";

      // Set custom metric format function
      let formatValueOriginal = this.templateSrv.formatValue;
      this.templateSrv.formatValue = formatMQEMetric;
      metric = this.templateSrv.replace(metric, this.scopedVars);

      // Set original format function
      this.templateSrv.formatValue = formatValueOriginal;

      query += metric;

      // Render functions if any
      if(target.functions && target.functions.length) {
        query += this.addFunctions(target.functions);
      }

      // Render apps and hosts
      query += this.renderWhere(target.apps, target.hosts);

      query = MQEQuery.addTimeRange(query, timeFrom, timeTo);
      return query;
    });
  }

  addFunctions(functions) {
    var query = "";
    if (functions.length) {
      _.forEach(functions, function (fn) {
        query += "|" + fn + " ";
      });
    }
    return query;
  }
  renderWhere(apps, hosts) {
    let query = "";
    if (apps.length || hosts.length) {
      query += " where ";
      if (apps.length) {
        query += "app in (" + _.map(apps, wrapTag).join(', ') + ")";
        if (hosts.length)  {
          query += " and ";
        }
      }
      if (hosts.length) {
        query += "host in (" + _.map(hosts, wrapTag).join(', ') + ")";
      }
    }
    return query;
  }

  renderWhereClauses(whereClauses) {
    var renderedClauses = _.map(whereClauses, (clauseObj, index) => {
      var rendered = "";
      if (index !== 0) {
        rendered += clauseObj.condition + " ";
      }

      // Put non-numeric values into quotes.
      var value;
      if (_.isNumber(clauseObj.value) ||
          this.containsVariable(clauseObj.value)) {
        value = clauseObj.value;
      } else {
        value = "'" + clauseObj.value + "'";
      }
      rendered += clauseObj.column + ' ' + clauseObj.operator + ' ' + value;
      return rendered;
    });
    return renderedClauses.join(' ');
  }

  // Check for template variables
  containsVariable(str) {
    var variables = _.map(this.templateSrv.variables, 'name');
    var self = this;
    return _.some(variables, variable => {
      return self.templateSrv.containsVariable(str, variable);
    });
  }

  ////////////////////
  // Static methods //
  ////////////////////

  static getMetrics() {
    var query = "describe all";
    return query;
  }

  static getColumns(metric) {
    return "describe " + metric;
  }

  static addTimeRange(query, timeFrom, timeTo, interval) {
    var timeRangeRegex = /from.*to/;
    if(!timeRangeRegex.test(query)) {
      query = trim(query) + " from " + timeFrom + " to " + timeTo;
    }
    return query;
  }
}

function containsWildcard(str) {
  var wildcardRegex = /\*/;
  return wildcardRegex.test(str);
}

function filterMetrics(str, metrics) {
  str = str.replace(/\./g, '\\\.');
  let filterRegex = new RegExp(str.replace('*', '.*'), 'g');
  return _.filter(metrics, metric => {
    return metric.search(filterRegex) !== -1;
  });
}

function trim(str) {
  var trimRegex = /^[\s]*(.*?)[\s]*$/;
  var match = str.match(trimRegex);
  return match ? match[0] : match;
}

function convertMetricWithWildcard(metricQuery, metric) {
  let suffix = getMetricSuffix(metricQuery, metric);
  return addMQEAlias(suffix, wrapMetric(metric));
}

function getMetricSuffix(metricQuery, metric) {
  let metricPrefix = metricQuery.replace(/\./g, '\\\.');
  let suffixRegex = new RegExp(metricPrefix.replace('*', '(.*)'));
  let suffix = suffixRegex.exec(metric);
  return suffix[1];
}

function addMQEAlias(alias, metric) {
  return metric + " {" + alias + "}";
}

// Wrap metric with ``: os.cpu.user -> `os.cpu.user`
function wrapMetric(metric) {
  return '`' + metric + '`';
}

function wrapTag(tag) {
  return "'" + tag + "'";
}

// Special value formatter for MQE metric.
// Render multi-value variables for using with metric template:
// $metric => ('os.cpu.user', 'os.cpu.system')
// select `$metric` => select `os.cpu.user`, `os.cpu.system`
function formatMQEMetric(value, format, variable) {
  if (typeof value === 'string') {
    return value;
  }
  return value.join("`, `");
}
<commit_msg>Incorporated Alias indexing for metrics containing Wildcards<commit_after>import _ from 'lodash';

export default class MQEQuery {

  /** @ngInject */
  constructor(target, templateSrv, scopedVars) {
    this.target = target;
    this.templateSrv = templateSrv;
    // this.templateSrv.formatValue = formatMQEMetric;
    this.scopedVars = scopedVars;
  }

  /////////////////////
  // Query Rendering //
  /////////////////////

  render(metricList, timeFrom, timeTo, interval) {
    let target = this.target;
    let metrics = [];

    for (let m of target.metrics) {
      let metric = m.metric;
      if (metric) {
        if (containsWildcard(metric)) {
          let filteredMetrics = filterMetrics(metric, metricList);

          // Add alias
          if (m.alias) {
            if (containsWildcard(m.alias)) {
              // Set whildcard part as metric alias
              // query: os.cpu.* alias: * -> metric: os.cpu.system -> alias: system
              filteredMetrics = _.map(filteredMetrics,
                _.partial(convertMetricWithWildcard, metric));
            } else if(containsIndex(m.alias)){
                // query: springboot.gauge.* (the  metric can be very lengthy like below)
                // metric: springboot.gauge.hystrix.HystrixThreadPool.GP-API-TIERC-PRODUCT.reportingHosts
                // alias: $6 ie show only reportingHosts
                var indices = getAliasIndexArray(m.alias);
                filteredMetrics = _.map(filteredMetrics, _.partial(convertMetricWithIndex, indices));
            }
            else {
              filteredMetrics = _.map(filteredMetrics,
                _.compose(_.partial(addMQEAlias, m.alias), wrapMetric));
            }
          } else {
            filteredMetrics = _.map(filteredMetrics, wrapMetric);
          }

          metrics = metrics.concat(filteredMetrics);
        } else {
          metric = wrapMetric(metric);

          // Add alias
          if (m.alias) {
            metric = addMQEAlias(m.alias, metric);
          }

          metrics = metrics.concat(metric);
        }
      }
    }
    metrics = _.uniq(metrics);

    return _.map(metrics, metric => {
      let query = "";

      // Set custom metric format function
      let formatValueOriginal = this.templateSrv.formatValue;
      this.templateSrv.formatValue = formatMQEMetric;
      metric = this.templateSrv.replace(metric, this.scopedVars);

      // Set original format function
      this.templateSrv.formatValue = formatValueOriginal;

      query += metric;

      // Render functions if any
      if(target.functions && target.functions.length) {
        query += this.addFunctions(target.functions);
      }

      // Render apps and hosts
      query += this.renderWhere(target.apps, target.hosts);

      query = MQEQuery.addTimeRange(query, timeFrom, timeTo);
      return query;
    });
  }

  addFunctions(functions) {
    var query = "";
    if (functions.length) {
      _.forEach(functions, function (fn) {
        query += "|" + fn + " ";
      });
    }
    return query;
  }
  renderWhere(apps, hosts) {
    let query = "";
    if (apps.length || hosts.length) {
      query += " where ";
      if (apps.length) {
        query += "app in (" + _.map(apps, wrapTag).join(', ') + ")";
        if (hosts.length)  {
          query += " and ";
        }
      }
      if (hosts.length) {
        query += "host in (" + _.map(hosts, wrapTag).join(', ') + ")";
      }
    }
    return query;
  }

  renderWhereClauses(whereClauses) {
    var renderedClauses = _.map(whereClauses, (clauseObj, index) => {
      var rendered = "";
      if (index !== 0) {
        rendered += clauseObj.condition + " ";
      }

      // Put non-numeric values into quotes.
      var value;
      if (_.isNumber(clauseObj.value) ||
          this.containsVariable(clauseObj.value)) {
        value = clauseObj.value;
      } else {
        value = "'" + clauseObj.value + "'";
      }
      rendered += clauseObj.column + ' ' + clauseObj.operator + ' ' + value;
      return rendered;
    });
    return renderedClauses.join(' ');
  }

  // Check for template variables
  containsVariable(str) {
    var variables = _.map(this.templateSrv.variables, 'name');
    var self = this;
    return _.some(variables, variable => {
      return self.templateSrv.containsVariable(str, variable);
    });
  }

  ////////////////////
  // Static methods //
  ////////////////////

  static getMetrics() {
    var query = "describe all";
    return query;
  }

  static getColumns(metric) {
    return "describe " + metric;
  }

  static addTimeRange(query, timeFrom, timeTo, interval) {
    var timeRangeRegex = /from.*to/;
    if(!timeRangeRegex.test(query)) {
      query = trim(query) + " from " + timeFrom + " to " + timeTo;
    }
    return query;
  }
}

function containsWildcard(str) {
  var wildcardRegex = /\*/;
  return wildcardRegex.test(str);
}

function containsIndex(str) {
    var wildcardRegex = /\$/;
    return wildcardRegex.test(str);
}

function getAliasIndexArray(str) {
    // replace all the $ with space
    // convert it to list
    str = str.replace(/\$/g, ' ');
    str = str.trim();
    var indices = str.split(' ');
    for(var i=0; i<indices.length; i++) {
        indices[i] = parseInt(indices[i], 10);
    }
    return indices;
}

function getMetricSplits(str) {
    var metricSplits = str.split('.');
    return (metricSplits);

}

function getCustomAliasName(metricSplits, indices) {
    var aliasString = "";
    for( var i = 0; i<indices.length; i++) {
        var index = indices[i]-1;
        if(index >= 0 && index <  metricSplits.length) {

            aliasString += metricSplits[indices[i] - 1] + ".";
        }
    }
    return aliasString.slice(0, -1);
}

function convertMetricWithIndex(indices, metric) {
    var suffix = getCustomAliasName(getMetricSplits(metric),indices);
    return addMQEAlias(suffix, wrapMetric(metric));
}

function filterMetrics(str, metrics) {
  str = str.replace(/\./g, '\\\.');
  let filterRegex = new RegExp(str.replace('*', '.*'), 'g');
  return _.filter(metrics, metric => {
    return metric.search(filterRegex) !== -1;
  });
}

function trim(str) {
  var trimRegex = /^[\s]*(.*?)[\s]*$/;
  var match = str.match(trimRegex);
  return match ? match[0] : match;
}

function convertMetricWithWildcard(metricQuery, metric) {
  let suffix = getMetricSuffix(metricQuery, metric);
  return addMQEAlias(suffix, wrapMetric(metric));
}

function getMetricSuffix(metricQuery, metric) {
  let metricPrefix = metricQuery.replace(/\./g, '\\\.');
  let suffixRegex = new RegExp(metricPrefix.replace('*', '(.*)'));
  let suffix = suffixRegex.exec(metric);
  return suffix[1];
}

function addMQEAlias(alias, metric) {
  return metric + " {" + alias + "}";
}

// Wrap metric with ``: os.cpu.user -> `os.cpu.user`
function wrapMetric(metric) {
  return '`' + metric + '`';
}

function wrapTag(tag) {
  return "'" + tag + "'";
}

// Special value formatter for MQE metric.
// Render multi-value variables for using with metric template:
// $metric => ('os.cpu.user', 'os.cpu.system')
// select `$metric` => select `os.cpu.user`, `os.cpu.system`
function formatMQEMetric(value, format, variable) {
  if (typeof value === 'string') {
    return value;
  }
  return value.join("`, `");
}
<|endoftext|>


<commit_before>let dependencyChecker = {}
let logger = {}
let colors = {}

try {
  dependencyChecker = require('check-dependencies')
  logger = require('../logger')
  colors = require('colors/safe')
} catch (err) {
  console.log('Dependencies could not be checked due to "' + err.message + '" error (NOT OK)')
  process.exit(1)
}

const validateDependencies = async ({ exitOnFailure = true } = {}) => {
  let success = true
  let dependencies = {}
  try {
    dependencies = await dependencyChecker()
  } catch (err) {
    logger.warn(`Dependencies could not be checked due to "${err.message}" error (${colors.red('NOT OK')})`)
  }

  if (dependencies.depsWereOk === true) {
    logger.info(`All dependencies are satisfied (${colors.green('OK')})`)
  } else {
    logger.warn(`Dependencies are not rightly satisfied (${colors.red('NOT OK')})`)
    success = false
    for (let err of dependencies.error) {
      console.log(err)
    }
  }

  if (!success && exitOnFailure) {
    logger.error(colors.red('Exiting due to unsatisfied dependencies!'))
    process.exit(1)
  }
}

module.exports = validateDependencies
<commit_msg>Move logger, colors out of try catch block<commit_after>let dependencyChecker = {}
try {
  dependencyChecker = require('check-dependencies')
} catch (err) {
  console.error('Please run "npm install" before starting the application!')
  process.exit(1)
}
const logger = require('../logger')
const colors = require('colors/safe')

const validateDependencies = async ({ exitOnFailure = true } = {}) => {
  let success = true
  let dependencies = {}
  try {
    dependencies = await dependencyChecker()
  } catch (err) {
    logger.warn(`Dependencies could not be checked due to "${err.message}" error (${colors.red('NOT OK')})`)
  }

  if (dependencies.depsWereOk === true) {
    logger.info(`All dependencies are satisfied (${colors.green('OK')})`)
  } else {
    logger.warn(`Dependencies are not rightly satisfied (${colors.red('NOT OK')})`)
    success = false
    for (let err of dependencies.error) {
      console.log(err)
    }
  }

  if (!success && exitOnFailure) {
    logger.error(colors.red('Exiting due to unsatisfied dependencies!'))
    process.exit(1)
  }
}

module.exports = validateDependencies
<|endoftext|>


<commit_before>const { appSlug } = require('../../config/app-strings');

module.exports = {
  setUnpublishable,
};

async function setUnpublishable(config) {
  if (!config.unpublishSafe) {
    return;
  }
  const context = `${appSlug}/unpublish-safe`;
  const existingState = await platform.getBranchStatusCheck(
    config.branchName,
    context
  );
  // Set canBeUnpublished status check
  const state = config.canBeUnpublished ? 'pending' : 'success';
  const description = config.canBeUnpublished
    ? 'Packages < 24 hours old can be unpublished'
    : 'Packages cannot be unpublished';
  // Check if state needs setting
  if (existingState === state) {
    logger.debug('Status check is already up-to-date');
  } else {
    logger.debug(`Updating status check state to ${state}`);
    await platform.setBranchStatus(
      config.branchName,
      context,
      description,
      state,
      'https://renovatebot.com/docs/configuration-reference/configuration-options#unpublishsafe'
    );
  }
}
<commit_msg>fix: unpublishSafe docs url<commit_after>const { appSlug, urls } = require('../../config/app-strings');

module.exports = {
  setUnpublishable,
};

async function setUnpublishable(config) {
  if (!config.unpublishSafe) {
    return;
  }
  const context = `${appSlug}/unpublish-safe`;
  const existingState = await platform.getBranchStatusCheck(
    config.branchName,
    context
  );
  // Set canBeUnpublished status check
  const state = config.canBeUnpublished ? 'pending' : 'success';
  const description = config.canBeUnpublished
    ? 'Packages < 24 hours old can be unpublished'
    : 'Packages cannot be unpublished';
  // Check if state needs setting
  if (existingState === state) {
    logger.debug('Status check is already up-to-date');
  } else {
    logger.debug(`Updating status check state to ${state}`);
    await platform.setBranchStatus(
      config.branchName,
      context,
      description,
      state,
      urls.documentation
    );
  }
}
<|endoftext|>


<commit_before>var expect = require('expect.js'),
    rawRequestBody = require('../fixtures').requestData,
    RequestBody = require('../../lib/index.js').RequestBody,
    QueryParam = require('../../lib/index.js').QueryParam;

/* global describe, it */
describe('RequestBody', function () {
    it('should be jsonified properly', function () {
        var reqData = new RequestBody(rawRequestBody),
            jsonified = reqData.toJSON();
        expect(jsonified).to.eql(rawRequestBody);
    });

    it('should be stringified properly', function () {
        var reqData = new RequestBody(rawRequestBody),
            expectedQueryData = QueryParam.unparse(rawRequestBody.urlencoded);

        // Set the mode to URL encoded
        reqData.mode = 'urlencoded';
        expect(reqData.toString()).to.eql(expectedQueryData);
    });

    it('should support file mode', function () {
        var rawBody = {
                mode: 'formdata',
                formdata: [
                    {
                        key: 'hiya',
                        value: 'heyo'
                    },
                    {
                        key: 'alpha',
                        value: 'beta'
                    }
                ],
                raw: 'abhijitkane',
                urlencoded: [
                    {
                        key: 'haha',
                        value: 'somevalue'
                    }
                ],
                file: {
                    src: '/somewhere/in/the/file/system'
                }
            },
            reqData = new RequestBody(rawBody);
        expect(reqData.file).to.have.property('src', rawBody.file.src);
    });

    it('should convert file reference to object, if only the reference is given', function () {
        var rawBody = {
                mode: 'file',
                file: '/omg/where/is/this/file'
            },
            reqData = new RequestBody(rawBody);
        expect(reqData.file).to.have.property('src', rawBody.file);
    });

    describe('isEmpty', function () {
        it('should return true if no request body is set', function () {
            var body = new RequestBody();
            expect(body.isEmpty()).to.be(true);
        });

        it('should return true if mode is set to raw and no data is present', function () {
            var body = new RequestBody({ mode: 'raw', raw: '' });
            expect(body.isEmpty()).to.be(true);
        });

        it('should return true if mode is formdata and no data is present', function () {
            var body = new RequestBody({ mode: 'formdata', formdata: [], raw: 'something' });
            expect(body.isEmpty()).to.be(true);
        });

        it('should return true if mode is urlencoded and no data is present', function () {
            var body = new RequestBody({ mode: 'urlencoded', formdata: [] });
            expect(body.isEmpty()).to.be(true);
        });

        it('should return false if mode is raw and data is available', function () {
            var body = new RequestBody({ mode: 'raw', raw: 'yo' });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is file and file ref is available', function () {
            var body = new RequestBody({ mode: 'file', file: { src: '/somewhere/file.txt' } });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is file and file ref as well as content are available', function () {
            var body = new RequestBody({ mode: 'file', file: { src: '/somewhere/file.txt',
                    content: new Buffer('omgomg') } });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is file and file content is available', function () {
            var body = new RequestBody({ mode: 'file', file: { content: 'asjdhkashd' } });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is urlencoded and data is available', function () {
            var body = new RequestBody({
                mode: 'urlencoded',
                urlencoded: [{
                    key: 'haha',
                    value: 'somevalue'
                }]
            });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is formdata and data is available', function () {
            var body = new RequestBody({
                mode: 'urlencoded',
                urlencoded: [{
                    key: 'haha',
                    value: { some: 'random', javascript: 'object' }  // this functionality is used in the app
                }]
            });
            expect(body.isEmpty()).to.be(false);
        });
    });
});
<commit_msg>updated the test names, added a testcase for both src and content being empty<commit_after>var expect = require('expect.js'),
    rawRequestBody = require('../fixtures').requestData,
    RequestBody = require('../../lib/index.js').RequestBody,
    QueryParam = require('../../lib/index.js').QueryParam;

/* global describe, it */
describe('RequestBody', function () {
    it('should be jsonified properly', function () {
        var reqData = new RequestBody(rawRequestBody),
            jsonified = reqData.toJSON();
        expect(jsonified).to.eql(rawRequestBody);
    });

    it('should be stringified properly', function () {
        var reqData = new RequestBody(rawRequestBody),
            expectedQueryData = QueryParam.unparse(rawRequestBody.urlencoded);

        // Set the mode to URL encoded
        reqData.mode = 'urlencoded';
        expect(reqData.toString()).to.eql(expectedQueryData);
    });

    it('should support file mode', function () {
        var rawBody = {
                mode: 'formdata',
                formdata: [
                    {
                        key: 'hiya',
                        value: 'heyo'
                    },
                    {
                        key: 'alpha',
                        value: 'beta'
                    }
                ],
                raw: 'abhijitkane',
                urlencoded: [
                    {
                        key: 'haha',
                        value: 'somevalue'
                    }
                ],
                file: {
                    src: '/somewhere/in/the/file/system'
                }
            },
            reqData = new RequestBody(rawBody);
        expect(reqData.file).to.have.property('src', rawBody.file.src);
    });

    it('should convert file reference to object, if only the reference is given', function () {
        var rawBody = {
                mode: 'file',
                file: '/omg/where/is/this/file'
            },
            reqData = new RequestBody(rawBody);
        expect(reqData.file).to.have.property('src', rawBody.file);
    });

    describe('isEmpty', function () {
        it('should return true if no request body is set', function () {
            var body = new RequestBody();
            expect(body.isEmpty()).to.be(true);
        });

        it('should return true if mode is set to raw and no data is present', function () {
            var body = new RequestBody({ mode: 'raw', raw: '' });
            expect(body.isEmpty()).to.be(true);
        });

        it('should return true if mode is formdata and no data is present', function () {
            var body = new RequestBody({ mode: 'formdata', formdata: [], raw: 'something' });
            expect(body.isEmpty()).to.be(true);
        });

        it('should return true if mode is urlencoded and no data is present', function () {
            var body = new RequestBody({ mode: 'urlencoded', formdata: [] });
            expect(body.isEmpty()).to.be(true);
        });

        it('should return false if mode is raw and data is available', function () {
            var body = new RequestBody({ mode: 'raw', raw: 'yo' });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is file and file src is available', function () {
            var body = new RequestBody({ mode: 'file', file: { src: '/somewhere/file.txt' } });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is file and file src as well as content are available', function () {
            var body = new RequestBody({ mode: 'file', file: { src: '/somewhere/file.txt',
                    content: new Buffer('omgomg') } });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is file and file content is available', function () {
            var body = new RequestBody({ mode: 'file', file: { content: 'asjdhkashd' } });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is urlencoded and data is available', function () {
            var body = new RequestBody({
                mode: 'urlencoded',
                urlencoded: [{
                    key: 'haha',
                    value: 'somevalue'
                }]
            });
            expect(body.isEmpty()).to.be(false);
        });

        it('should return false if mode is formdata and data is available', function () {
            var body = new RequestBody({
                mode: 'urlencoded',
                urlencoded: [{
                    key: 'haha',
                    value: { some: 'random', javascript: 'object' }  // this functionality is used in the app
                }]
            });
            expect(body.isEmpty()).to.be(false);
        });
    });
});
<|endoftext|>


<commit_before>var { CloudContext } = require('./utils');

describe('OpenGraph story', () => {
  let ctx = new CloudContext();

  describe('When alice requests opengraph info for our blog', () => {
    ctx.requestShouldNotError(async () => {
      ctx.response = await ctx.alice.og(
        'https://getstream.io/blog/try-out-the-stream-api-with-postman',
      );
    });

    ctx.responseShould('have the expected content', () => {
      ctx.shouldEqualBesideDuration(ctx.response, {
        locale: 'en_US',
        type: 'article',
        title: 'Try out the Stream API with Postman - The Stream Blog',
        description:
          "Many of us at Stream use Postman regularly as we build and test our services. We're also always looking for ways to make it quick and easy for other developers to try the service. One of our goals is to help people see first hand how simple it is to build powerful social apps with Stream.",
        url: 'https://getstream.io/blog/try-out-the-stream-api-with-postman/',
        site_name: 'The Stream Blog',
        images: [
          {
            image:
              'https://getstream-blog.imgix.net/blog/wp-content/uploads/2018/04/stream_postman.png',
            secure_url:
              'https://getstream-blog.imgix.net/blog/wp-content/uploads/2018/04/stream_postman.png',
            width: 1600,
            height: 835,
            alt: 'Postman Collection for the Stream API',
          },
        ],
      });
    });
  });

  describe('When alice requests opengraph info for a binary blob', () => {
    ctx.requestShouldError(400, async () => {
      ctx.response = await ctx.alice.og(
        'https://github.com/buger/goreplay/releases/download/v0.16.1/gor_0.16.1_mac.tar.gz',
      );
    });

    ctx.responseShould('have the expected content', () => {
      ctx.response.should.eql({
        detail: 'document too large (>1MB)',
        status_code: 400,
      });
    });
  });
});
<commit_msg>adjust og test<commit_after>var { CloudContext } = require('./utils');

describe('OpenGraph story', () => {
  let ctx = new CloudContext();

  describe('When alice requests opengraph info for our blog', () => {
    ctx.requestShouldNotError(async () => {
      ctx.response = await ctx.alice.og(
        'https://getstream.io/blog/try-out-the-stream-api-with-postman',
      );
    });

    ctx.responseShould('have the expected content', () => {
      ctx.shouldEqualBesideDuration(ctx.response, {
        locale: 'en_US',
        type: 'article',
        title: 'Try out the Stream API with Postman - The Stream Blog',
        description:
          "Many of us at Stream use Postman regularly as we build and test our services. We're also always looking for ways to make it quick and easy for other developers to try the service. One of our goals is to help people see first hand how simple it is to build powerful social apps with Stream.",
        url: 'https://getstream.io/blog/try-out-the-stream-api-with-postman/',
        site_name: 'The Stream Blog',
        images: [
          {
            image:
              'https://getstream-blog.imgix.net/blog/wp-content/uploads/2018/04/stream_postman.png',
            secure_url:
              'https://getstream-blog.imgix.net/blog/wp-content/uploads/2018/04/stream_postman.png',
            width: 1600,
            height: 835,
            alt: 'Postman Collection for the Stream API',
          },
        ],
      });
    });
  });

  describe('When alice requests opengraph info for a binary blob', () => {
    ctx.requestShouldError(400, async () => {
      ctx.response = await ctx.alice.og(
        'https://github.com/buger/goreplay/releases/download/v0.16.1/gor_0.16.1_mac.tar.gz',
      );
    });

    ctx.responseShould('have the expected content', () => {
      ctx.shouldEqualBesideDuration(ctx.response, {
        detail: 'url content too big',
        status_code: 400,
        code: 4,
        exception: 'InputException',
      });
    });
  });
});
<|endoftext|>


<commit_before><commit_msg>Unified Superstring  tests<commit_after><|endoftext|>


<commit_before>var should   = require('should');
var helper   = require('../support/spec_helper');
var ORM      = require('../../');

describe("Model.aggregate()", function() {
	var db = null;
	var Person = null;

	var setup = function () {
		return function (done) {
			Person = db.define("person", {
				name   : String
			});

			return helper.dropSync(Person, function () {
				Person.create([{
					id  : 1,
					name: "John Doe"
				}, {
					id  : 2,
					name: "Jane Doe"
				}, {
					id  : 3,
					name: "John Doe"
				}], done);
			});
		};
	};

	before(function (done) {
		helper.connect(function (connection) {
			db = connection;

			return done();
		});
	});

	after(function () {
		return db.close();
	});

	describe("with multiple methods", function () {
		before(setup());

		it("should return value for everyone of them", function (done) {
			Person.aggregate().count('id').min('id').max('id').get(function (err, count, min, max) {
				should.equal(err, null);

				count.should.equal(3);
				min.should.equal(1);
				max.should.equal(3);

				return done();
			});
		});
	});

	describe("with select() without arguments", function () {
		before(setup());

		it("should throw", function (done) {
			Person.aggregate().select.should.throw();

			return done();
		});
	});

	describe("with select() with arguments", function () {
		before(setup());

		it("should use them as properties if 1st argument is Array", function (done) {
			Person.aggregate().select([ 'id' ]).count().groupBy('name').get(function (err, people) {
				should.equal(err, null);

				should(Array.isArray(people));
				people.length.should.be.above(0);

				people[0].should.be.a("object");
				people[0].should.have.property("id");
				people[0].should.not.have.property("name");

				return done();
			});
		});

		it("should use them as properties", function (done) {
			Person.aggregate().select('id', 'name').count().groupBy('name').get(function (err, people) {
				should.equal(err, null);

				should(Array.isArray(people));
				people.length.should.be.above(0);

				people[0].should.be.a("object");
				people[0].should.have.property("id");
				people[0].should.have.property("name");

				return done();
			});
		});
	});

	describe("with get() without callback", function () {
		before(setup());

		it("should throw", function (done) {
			Person.aggregate().count('id').get.should.throw();

			return done();
		});
	});

	describe("with get() without aggregates", function () {
		before(setup());

		it("should throw", function (done) {
			(function () {
				Person.aggregate().get(function () {});
			}).should.throw();

			return done();
		});
	});

	describe("with distinct()", function () {
		before(setup());

		it("should return a list of distinct properties", function (done) {
			Person.aggregate().distinct('name').get(function (err, names) {
				should.equal(err, null);

				names.should.be.a("object");
				names.should.have.property("length", 2);

				return done();
			});
		});

		describe("with limit(1)", function () {
			it("should return only one value", function (done) {
				Person.aggregate().distinct('name').limit(1).order("name").get(function (err, names) {
					should.equal(err, null);

					names.should.be.a("object");
					names.should.have.property("length", 1);
					names[0].should.equal("Jane Doe");

					return done();
				});
			});
		});

		describe("with limit(1, 1)", function () {
			it("should return only one value", function (done) {
				Person.aggregate().distinct('name').limit(1, 1).order("name").get(function (err, names) {
					should.equal(err, null);

					names.should.be.a("object");
					names.should.have.property("length", 1);
					names[0].should.equal("John Doe");

					return done();
				});
			});
		});
	});

	describe("with groupBy()", function () {
		before(setup());

		it("should return items grouped by property", function (done) {
			Person.aggregate().count().groupBy('name').get(function (err, rows) {
				should.equal(err, null);

				rows.should.be.a("object");
				rows.should.have.property("length", 2);

				(rows[0].count + rows[1].count).should.equal(3); // 1 + 2

				return done();
			});
		});

		describe("with order()", function () {
			before(setup());

			it("should order items", function (done) {
				Person.aggregate().count().groupBy('name').order('-count').get(function (err, rows) {
					should.equal(err, null);

					rows.should.be.a("object");
					rows.should.have.property("length", 2);

					rows[0].count.should.equal(2);
					rows[1].count.should.equal(1);

					return done();
				});
			});
		});
	});

	describe("using as()", function () {
		before(setup());

		it("should use as an alias", function (done) {
			Person.aggregate().count().as('total').groupBy('name').get(function (err, people) {
				should.equal(err, null);

				should(Array.isArray(people));
				people.length.should.be.above(0);

				people[0].should.be.a("object");
				people[0].should.have.property("total");

				return done();
			});
		});

		it("should throw if no aggregates defined", function (done) {
			(function () {
				Person.aggregate().as('total');
			}).should.throw();

			return done();
		});
	});
});
<commit_msg>Fixes previously added aggregate tests to pass on postgres<commit_after>var should   = require('should');
var helper   = require('../support/spec_helper');
var ORM      = require('../../');

describe("Model.aggregate()", function() {
	var db = null;
	var Person = null;

	var setup = function () {
		return function (done) {
			Person = db.define("person", {
				name   : String
			});

			return helper.dropSync(Person, function () {
				Person.create([{
					id  : 1,
					name: "John Doe"
				}, {
					id  : 2,
					name: "Jane Doe"
				}, {
					id  : 3,
					name: "John Doe"
				}], done);
			});
		};
	};

	before(function (done) {
		helper.connect(function (connection) {
			db = connection;

			return done();
		});
	});

	after(function () {
		return db.close();
	});

	describe("with multiple methods", function () {
		before(setup());

		it("should return value for everyone of them", function (done) {
			Person.aggregate().count('id').min('id').max('id').get(function (err, count, min, max) {
				should.equal(err, null);

				count.should.equal(3);
				min.should.equal(1);
				max.should.equal(3);

				return done();
			});
		});
	});

	describe("with select() without arguments", function () {
		before(setup());

		it("should throw", function (done) {
			Person.aggregate().select.should.throw();

			return done();
		});
	});

	describe("with select() with arguments", function () {
		before(setup());

		it("should use them as properties if 1st argument is Array", function (done) {
			Person.aggregate().select([ 'id' ]).count('id').groupBy('id').get(function (err, people) {
				should.equal(err, null);

				should(Array.isArray(people));
				people.length.should.be.above(0);

				people[0].should.be.a("object");
				people[0].should.have.property("id");
				people[0].should.not.have.property("name");

				return done();
			});
		});

		it("should use them as properties", function (done) {
			Person.aggregate().select('id').count().groupBy('id').get(function (err, people) {
				should.equal(err, null);

				should(Array.isArray(people));
				people.length.should.be.above(0);

				people[0].should.be.a("object");
				people[0].should.have.property("id");
				people[0].should.not.have.property("name");

				return done();
			});
		});
	});

	describe("with get() without callback", function () {
		before(setup());

		it("should throw", function (done) {
			Person.aggregate().count('id').get.should.throw();

			return done();
		});
	});

	describe("with get() without aggregates", function () {
		before(setup());

		it("should throw", function (done) {
			(function () {
				Person.aggregate().get(function () {});
			}).should.throw();

			return done();
		});
	});

	describe("with distinct()", function () {
		before(setup());

		it("should return a list of distinct properties", function (done) {
			Person.aggregate().distinct('name').get(function (err, names) {
				should.equal(err, null);

				names.should.be.a("object");
				names.should.have.property("length", 2);

				return done();
			});
		});

		describe("with limit(1)", function () {
			it("should return only one value", function (done) {
				Person.aggregate().distinct('name').limit(1).order("name").get(function (err, names) {
					should.equal(err, null);

					names.should.be.a("object");
					names.should.have.property("length", 1);
					names[0].should.equal("Jane Doe");

					return done();
				});
			});
		});

		describe("with limit(1, 1)", function () {
			it("should return only one value", function (done) {
				Person.aggregate().distinct('name').limit(1, 1).order("name").get(function (err, names) {
					should.equal(err, null);

					names.should.be.a("object");
					names.should.have.property("length", 1);
					names[0].should.equal("John Doe");

					return done();
				});
			});
		});
	});

	describe("with groupBy()", function () {
		before(setup());

		it("should return items grouped by property", function (done) {
			Person.aggregate().count().groupBy('name').get(function (err, rows) {
				should.equal(err, null);

				rows.should.be.a("object");
				rows.should.have.property("length", 2);

				(rows[0].count + rows[1].count).should.equal(3); // 1 + 2

				return done();
			});
		});

		describe("with order()", function () {
			before(setup());

			it("should order items", function (done) {
				Person.aggregate().count().groupBy('name').order('-count').get(function (err, rows) {
					should.equal(err, null);

					rows.should.be.a("object");
					rows.should.have.property("length", 2);

					rows[0].count.should.equal(2);
					rows[1].count.should.equal(1);

					return done();
				});
			});
		});
	});

	describe("using as()", function () {
		before(setup());

		it("should use as an alias", function (done) {
			Person.aggregate().count().as('total').groupBy('name').get(function (err, people) {
				should.equal(err, null);

				should(Array.isArray(people));
				people.length.should.be.above(0);

				people[0].should.be.a("object");
				people[0].should.have.property("total");

				return done();
			});
		});

		it("should throw if no aggregates defined", function (done) {
			(function () {
				Person.aggregate().as('total');
			}).should.throw();

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


<commit_before>import {UserAccount} from '../../src/dashboard-child-routes/user-account';
import {AuthStub, HttpMock, AppStateStub} from './commons';
import {App} from '../../src/app';

class HttpStub extends HttpMock {
  fetch(url) {
    console.log(url);
    return Promise.resolve({
      json: () => Promise.resolve([{name: 'in the jungle'}])
    });
  }
}

describe('the UserAccount Module', () => {
  let ua;
  let app;
  let auth;

  beforeEach(() => {
    auth = new AuthStub();
    auth.setToken({sub: 'aowifjawifhiawofjo'});
    app = new App(auth, new HttpStub());
    app.activate();
    ua = new UserAccount(app);
  });

  it('should activate user account', (done) => {
    ua.app.appState = new AppStateStub();
    ua.activate().then(() => {
      done();
    });
  });

  it('should activate user account with preselected attributes', (done) => {
    ua.app.appState = new AppStateStub();
    ua.app.auth.setToken({sub: '1'});
    ua.activate().then(() => {
      done();
    });
  });

  it('setup volunteer', (done) => {
    ua.app.appState = new AppStateStub();
    ua.setupVolunteer().then(() => {
      done();
    });
  });

  it('checkboxes expanded', (done) => {
    document.body.innerHTML = '

';
    ua.expanded = true;
    ua.showCheckboxes('types');
    expect(ua.expanded).toBe(false);
    done();
  });

  it('checkboxes closed', (done) => {
    document.body.innerHTML = '

';
    ua.expanded = false;
    ua.showCheckboxes('types');
    expect(ua.expanded).toBe(true);
    done();
  });

  it('causePicked without attributes', (done) => {
    ua.app.appState = new AppStateStub();
    ua.activate().then(() => {
      ua.causePicked();
      done();
    });
  });

  it('causePicked with attributes', (done) => {
    ua.app.appState = new AppStateStub();
    ua.app.auth.setToken({sub: '1'});
    ua.activate().then(() => {
      ua.causePicked();
      done();
    });
  });

  it('talentPicked without attributes', (done) => {
    ua.app.appState = new AppStateStub();
    ua.activate().then(() => {
      ua.talentPicked();
      done();
    });
  });

  it('talentPicked with attributes', (done) => {
    ua.app.appState = new AppStateStub();
    ua.app.auth.setToken({sub: '1'});
    ua.activate().then(() => {
      ua.talentPicked();
      done();
    });
  });

  it('workPicked without attributes', (done) => {
    ua.app.appState = new AppStateStub();
    ua.activate().then(() => {
      ua.workPicked();
      done();
    });
  });

  it('workPicked with attributes', (done) => {
    ua.app.appState = new AppStateStub();
    ua.app.auth.setToken({sub: '1'});
    ua.activate().then(() => {
      ua.workPicked();
      done();
    });
  });

  it('deletes the user', (done) => {
    ua.deleteUser();
    done();
  });
});
<commit_msg>unit tests<commit_after>import {UserAccount} from '../../src/dashboard-child-routes/user-account';
import {AuthStub, HttpMock, AppStateStub} from './commons';
import {App} from '../../src/app';

class HttpStub extends HttpMock {
  fetch(url) {
    console.log(url);
    return Promise.resolve({
      json: () => Promise.resolve([{name: 'in the jungle'}])
    });
  }
}

describe('the UserAccount Module', () => {
  let ua;
  let app;
  let auth;

  beforeEach(() => {
    auth = new AuthStub();
    auth.setToken({sub: 'aowifjawifhiawofjo'});
    app = new App(auth, new HttpStub());
    app.activate();
    ua = new UserAccount(app);
    ua.app.appState = new AppStateStub();
    ua.activate();
  });

  // it('should activate user account', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.activate().then(() => {
  //     done();
  //   });
  // });

  // it('should activate user account with preselected attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.app.auth.setToken({sub: '1'});
  //   ua.activate().then(() => {
  //     done();
  //   });
  // });

  it('setup volunteer', (done) => {
    ua.app.appState = new AppStateStub();
    ua.setupVolunteer().then(() => {
      done();
    });
  });

  it('checkboxes expanded', (done) => {
    document.body.innerHTML = '

';
    ua.expanded = true;
    ua.showCheckboxes('types');
    expect(ua.expanded).toBe(false);
    done();
  });

  it('checkboxes closed', (done) => {
    document.body.innerHTML = '

';
    ua.expanded = false;
    ua.showCheckboxes('types');
    expect(ua.expanded).toBe(true);
    done();
  });

  // it('causePicked without attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.activate().then(() => {
  //     ua.causePicked();
  //     done();
  //   });
  // });

  // it('causePicked with attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.app.auth.setToken({sub: '1'});
  //   ua.activate().then(() => {
  //     ua.causePicked();
  //     done();
  //   });
  // });

  // it('talentPicked without attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.activate().then(() => {
  //     ua.talentPicked();
  //     done();
  //   });
  // });

  // it('talentPicked with attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.app.auth.setToken({sub: '1'});
  //   ua.activate().then(() => {
  //     ua.talentPicked();
  //     done();
  //   });
  // });

  // it('workPicked without attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.activate().then(() => {
  //     ua.workPicked();
  //     done();
  //   });
  // });

  // it('workPicked with attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.app.auth.setToken({sub: '1'});
  //   ua.activate().then(() => {
  //     ua.workPicked();
  //     done();
  //   });
  // });

  it('deletes the user', (done) => {
    ua.deleteUser();
    done();
  });
});
<|endoftext|>


<commit_before>/**
 * lilyFilters is a container for all global lily related Angular filters
 */
angular.module('lilyFilters', [])

    /**
     * relativeDate filter is a filter that represents the date in a nice format
     *
     * relativeDate will return a relative date string given the date. If the
     * date is to far in the past, it will fallback to angulars $filter
     *
     * @param: date {date|string} : date object or date string to transform
     * @param: fallbackDateFormat string (optional): fallback $filter argument
     *
     * @returns: string : a relative date string
     *
     * usage:
     *
     * {{ '2014-11-19T12:44:15.795312+00:00' | relativeDate }}
     */
    .filter('relativeDate', ['$filter', function($filter) {
        return function(date, fallbackDateFormat) {
            // Get current date
            var now = new Date(),
                calculateDelta, day, delta, hour, minute, week, month, year;

            // If date is a string, format to date object
            if (!(date instanceof Date)) {
                date = new Date(date);
            }

            delta = null;
            minute = 60;
            hour = minute * 60;
            day = hour * 24;
            week = day * 7;
            month = day * 30;
            year = day * 365;

            // Calculate delta in seconds
            calculateDelta = function() {
                return delta = Math.round((date - now) / 1000);
            };

            calculateDelta();

            if (delta > day && delta < week) {
                date = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
                calculateDelta();
            }

            if(!fallbackDateFormat) {
                if(window.innerWidth < 992) {
                    // Display as a short version if it's a small screen (tablet, smartphone, etc.)
                    fallbackDateFormat = 'dd MMM. yyyy'; // Renders as 29 Jan. 2015
                }
                else {
                    fallbackDateFormat = 'dd MMMM yyyy'; // Renders as 29 January 2015
                }
            }

            // Check delta and return result
            if (delta < 0) {
                switch (false) {
                    case !(-delta > week):
                        return $filter('date')(date, fallbackDateFormat);
                    case !(-delta > day * 2):
                        return '' + -(Math.ceil(delta / day)) + ' days ago';
                    case !(-delta > day):
                        return 'yesterday';
                    case !(-delta > hour):
                        return '' + -(Math.ceil(delta / hour)) + ' hours ago';
                    case !(-delta > minute * 2):
                        return '' + -(Math.ceil(delta / minute)) + ' minutes ago';
                    case !(-delta > minute):
                        return 'a minutes ago';
                    case !(-delta > 30):
                        return '' + -delta + ' seconds ago';
                    default:
                        return 'just now';
                }
            } else {
                switch (false) {
                    case !(delta < 30):
                        return 'just now';
                    case !(delta < minute):
                        return '' + delta + ' seconds';
                    case !(delta < 2 * minute):
                        return 'a minute';
                    case !(delta < hour):
                        return '' + (Math.floor(delta / minute)) + ' minutes';
                    case Math.floor(delta / hour) !== 1:
                        return 'an hour';
                    case !(delta < day):
                        return '' + (Math.floor(delta / hour)) + ' hours';
                    case !(delta < day * 2):
                        return 'tomorrow';
                    case !(delta < week):
                        return '' + (Math.floor(delta / day)) + ' days';
                    case Math.floor(delta / week) !== 1:
                        return 'a week';
                    default:
                        // Use angular $filter
                        return $filter('date')(date, fallbackDateFormat);
                }
            }
        }
    }])
    .filter('minValue', function() {
        return function(values) {
            values.sort(function(a, b){return a-b});
            return values[0];
        }
    })
    .filter('nl2br', ['$sce', function($sce) {
        return function(msg,is_xhtml) {
            var is_xhtml = is_xhtml || true;
            var breakTag = (is_xhtml) ? '
' : '
';
            var msg = (msg + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
            return $sce.trustAsHtml(msg);
        }
    }])
    .filter('trustAsResourceUrl', ['$sce', function($sce) {
        return function(val) {
            return $sce.trustAsResourceUrl(val);
        };
    }]);
<commit_msg>LILY-582: Fix date comparisons in lists<commit_after>/**
 * lilyFilters is a container for all global lily related Angular filters
 */
angular.module('lilyFilters', [])

    /**
     * relativeDate filter is a filter that represents the date in a nice format
     *
     * relativeDate will return a relative date string given the date. If the
     * date is to far in the past, it will fallback to angulars $filter
     *
     * @param: date {date|string} : date object or date string to transform
     * @param: fallbackDateFormat string (optional): fallback $filter argument
     *
     * @returns: string : a relative date string
     *
     * usage:
     *
     * {{ '2014-11-19T12:44:15.795312+00:00' | relativeDate }}
     */
    .filter('relativeDate', ['$filter', function($filter) {
        return function(date, fallbackDateFormat) {
            // Get current date
            var now = new Date(),
                calculateDelta, day, delta, hour, minute, week, month, year;

            // If date is a string, format to date object
            if (!(date instanceof Date)) {
                date = new Date(date);
                // If the closing date or w/e is the current date we want to compare with midnight
                date.setHours(23);
                date.setMinutes(59);
                date.setSeconds(59);
            }

            delta = null;
            minute = 60;
            hour = minute * 60;
            day = hour * 24;
            week = day * 7;
            month = day * 30;
            year = day * 365;

            // Calculate delta in seconds
            calculateDelta = function() {
                return delta = Math.round((date - now) / 1000);
            };

            calculateDelta();

            if (delta > day && delta < week) {
                // If the closing date or w/e is the current date we want to compare with midnight
                date = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
                calculateDelta();
            }

            if(!fallbackDateFormat) {
                if(window.innerWidth < 992) {
                    // Display as a short version if it's a small screen (tablet, smartphone, etc.)
                    fallbackDateFormat = 'dd MMM. yyyy'; // Renders as 29 Jan. 2015
                }
                else {
                    fallbackDateFormat = 'dd MMMM yyyy'; // Renders as 29 January 2015
                }
            }

            // Check delta and return result
            if (delta < 0) {
                switch (false) {
                    case !(-delta > week):
                        return $filter('date')(date, fallbackDateFormat);
                    case !(-delta > day * 2):
                        return '' + -(Math.ceil(delta / day)) + ' days ago';
                    case !(-delta > day):
                        return 'yesterday';
                    case !(-delta > hour):
                        return '' + -(Math.ceil(delta / hour)) + ' hours ago';
                    case !(-delta > minute * 2):
                        return '' + -(Math.ceil(delta / minute)) + ' minutes ago';
                    case !(-delta > minute):
                        return 'a minutes ago';
                    case !(-delta > 30):
                        return '' + -delta + ' seconds ago';
                    default:
                        return 'just now';
                }
            } else {
                switch (false) {
                    case !(delta < 30):
                        return 'just now';
                    case !(delta < minute):
                        return '' + delta + ' seconds';
                    case !(delta < 2 * minute):
                        return 'a minute';
                    case !(delta < hour):
                        return '' + (Math.floor(delta / minute)) + ' minutes';
                    case Math.floor(delta / hour) !== 1:
                        return 'an hour';
                    case !(delta < day):
                        return '' + (Math.floor(delta / hour)) + ' hours';
                    case !(delta < day * 2):
                        return 'tomorrow';
                    case !(delta < week):
                        return '' + (Math.floor(delta / day)) + ' days';
                    case Math.floor(delta / week) !== 1:
                        return 'a week';
                    default:
                        // Use angular $filter
                        return $filter('date')(date, fallbackDateFormat);
                }
            }
        }
    }])
    .filter('minValue', function() {
        return function(values) {
            values.sort(function(a, b){return a-b});
            return values[0];
        }
    })
    .filter('nl2br', ['$sce', function($sce) {
        return function(msg,is_xhtml) {
            var is_xhtml = is_xhtml || true;
            var breakTag = (is_xhtml) ? '
' : '
';
            var msg = (msg + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
            return $sce.trustAsHtml(msg);
        }
    }])
    .filter('trustAsResourceUrl', ['$sce', function($sce) {
        return function(val) {
            return $sce.trustAsResourceUrl(val);
        };
    }]);
<|endoftext|>


<commit_before>include('ringo/unittest');
include('./testconsts');
var fs = require('fs-base');
var {getRingoHome} = require('ringo/engine');
var {Store} = require('ringo/storage/filestore');
var store = new Store('db');
var person, Person = store.defineClass('Person');

exports.testPersistCreation = function () {
    person = new Person();
    person.firstName = FIRST_NAME_1;
    person.lastName = LAST_NAME;
    person.birthDate = new Date(BIRTH_DATE_MILLIS);
    person.save();
    person = Person.get(1);
    assertNotNull(person);
    assertEqual(FIRST_NAME_1, person.firstName);
    assertEqual(LAST_NAME, person.lastName);
    assertEqual(new Date(BIRTH_DATE_MILLIS), person.birthDate);
};

exports.testPersistUpdating = function () {
    person = Person.all()[0];
    assertNotNull(person);
    person.firstName = FIRST_NAME_2;
    person.save();
    person = Person.get(1);
    assertNotNull(person);
    assertEqual(FIRST_NAME_2, person.firstName);
    assertEqual(LAST_NAME, person.lastName);
    assertEqual(new Date(BIRTH_DATE_MILLIS), person.birthDate);
};

exports.testBasicQuerying = function () {
    assertEqual(1, Person.all().length);
    assertEqual(LAST_NAME, Person.all()[0].lastName);
    assertEqual(LAST_NAME, Person.query().equals('lastName', LAST_NAME).
            select('lastName')[0]);
    assertEqual(1, Person.query().equals('lastName', LAST_NAME).select().
            length);
};

exports.testPersistDeletion = function () {
    person.remove();
    person = Person.get(1);
    assertNull(person);
    assertEqual(0, Person.all().length);
    fs.removeDirectory(fs.join(getRingoHome().path, 'db', 'Person'));
    fs.removeDirectory(fs.join(getRingoHome().path, 'db')); // Clean up.
};
<commit_msg>Use test/testdb as directory for filestore tests rather than db in ringo-home<commit_after>include('ringo/unittest');
include('./testconsts');
var fs = require('fs-base');
var {Store} = require('ringo/storage/filestore');
var dbPath = fs.join(system.prefix, "test", "testdb");
var store = new Store(dbPath);
var person, Person = store.defineClass('Person');

exports.testPersistCreation = function () {
    person = new Person();
    person.firstName = FIRST_NAME_1;
    person.lastName = LAST_NAME;
    person.birthDate = new Date(BIRTH_DATE_MILLIS);
    person.save();
    person = Person.get(1);
    assertNotNull(person);
    assertEqual(FIRST_NAME_1, person.firstName);
    assertEqual(LAST_NAME, person.lastName);
    assertEqual(new Date(BIRTH_DATE_MILLIS), person.birthDate);
};

exports.testPersistUpdating = function () {
    person = Person.all()[0];
    assertNotNull(person);
    person.firstName = FIRST_NAME_2;
    person.save();
    person = Person.get(1);
    assertNotNull(person);
    assertEqual(FIRST_NAME_2, person.firstName);
    assertEqual(LAST_NAME, person.lastName);
    assertEqual(new Date(BIRTH_DATE_MILLIS), person.birthDate);
};

exports.testBasicQuerying = function () {
    assertEqual(1, Person.all().length);
    assertEqual(LAST_NAME, Person.all()[0].lastName);
    assertEqual(LAST_NAME, Person.query().equals('lastName', LAST_NAME).
            select('lastName')[0]);
    assertEqual(1, Person.query().equals('lastName', LAST_NAME).select().
            length);
};

exports.testPersistDeletion = function () {
    person.remove();
    person = Person.get(1);
    assertNull(person);
    assertEqual(0, Person.all().length);
    fs.removeDirectory(fs.join(dbPath, 'Person'));
    fs.removeDirectory(dbPath); // Clean up.
};
<|endoftext|>


<commit_before>const {
  randomDroneModel,
  randomDavAddress,
  randomMissionsCompleted,
  randomCoords,
} = require('../../server/simulation/random');

describe('randomDroneModel()', () => {
  test('returns a string', () => {
    expect(
      typeof randomDroneModel()
    ).toBe('string');
  });

  test('returns at least two words', () => {
    expect(
      randomDroneModel().split(' ').length
    ).toBeGreaterThanOrEqual(2);
  });
});

describe('randomDavAddress()', () => {
  test('returns a string', () => {
    expect(
      typeof randomDavAddress()
    ).toBe('string');
  });

  test('returns a string that is 42 characters long', () => {
    expect(
      randomDavAddress().length
    ).toEqual(42);
  });

  test('returns a string that starts with 0x and followed by 40 hexadecimal chars', () => {
    expect(
      randomDavAddress()
    ).toMatch(new RegExp('^0x([0-f]{40})$'));
  });
});

describe('randomMissionsCompleted()', () => {
  test('returns an object', () => {
    expect(
      typeof randomMissionsCompleted()
    ).toBe('object');
  });

  test('returns an object containing missionsCompleted7Days which is less than or equal to missionsCompleted', () => {
    const prop = randomMissionsCompleted();
    expect(
      prop.missionsCompleted7Days
    ).toBeLessThanOrEqual(prop.missionsCompleted);

    expect(
      Number.isInteger(prop.missionsCompleted7Days)
    ).toBe(true);

    expect(
      prop.missionsCompleted7Days
    ).toBeGreaterThan(0);

  });

  test('returns an object containing missionsCompleted which is an integer between 4 and 90', () => {
    expect(
      Number.isInteger(randomMissionsCompleted().missionsCompleted)
    ).toBe(true);

    expect(
      randomMissionsCompleted().missionsCompleted
    ).toBeLessThanOrEqual(90);

    expect(
      randomMissionsCompleted().missionsCompleted
    ).toBeGreaterThanOrEqual(4);
  });
});

describe('randomCoords()', () => {
  const sampleArguments = { coords: { lat: 1, long: 1 }, radius: 1000 };
  const random = randomCoords(sampleArguments);
  const coords = {
    lat1: sampleArguments.coords.lat,
    long1: sampleArguments.coords.lat,
    lat2: random.lat,
    long2: random.long
  };
  /**
   * Haversine Formula: returns the distance from one point to another
   * @returns {Number} a number containing distance in meters
   */
  const getDistance = ({ lat1, long1, lat2, long2 }) => {
    const R = 6371; // radius of the earth in km
    const dLat = degToRad(lat2 - lat1);
    const dLong = degToRad(long2 - long1);
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const d = (R * c) * 1000;
    return d;
  };
  const degToRad = (deg) => { return deg * (Math.PI / 180); };

  test('returns a coordinate that is no further than given coordinates by given radius', () => {
    expect(
      getDistance(coords)
    ).toBeLessThanOrEqual(sampleArguments.radius);
  });
});
<commit_msg>Switched haversine function for turf on randomCoords() test.<commit_after>const {
  randomDroneModel,
  randomDavAddress,
  randomMissionsCompleted,
  randomCoords,
} = require('../../server/simulation/random');
const turf = require('@turf/turf');

describe('randomDroneModel()', () => {
  test('returns a string', () => {
    expect(
      typeof randomDroneModel()
    ).toBe('string');
  });

  test('returns at least two words', () => {
    expect(
      randomDroneModel().split(' ').length
    ).toBeGreaterThanOrEqual(2);
  });
});

describe('randomDavAddress()', () => {
  test('returns a string', () => {
    expect(
      typeof randomDavAddress()
    ).toBe('string');
  });

  test('returns a string that is 42 characters long', () => {
    expect(
      randomDavAddress().length
    ).toEqual(42);
  });

  test('returns a string that starts with 0x and followed by 40 hexadecimal chars', () => {
    expect(
      randomDavAddress()
    ).toMatch(new RegExp('^0x([0-f]{40})$'));
  });
});

describe('randomMissionsCompleted()', () => {
  test('returns an object', () => {
    expect(
      typeof randomMissionsCompleted()
    ).toBe('object');
  });

  test('returns an object containing missionsCompleted7Days which is less than or equal to missionsCompleted', () => {
    const prop = randomMissionsCompleted();
    expect(
      prop.missionsCompleted7Days
    ).toBeLessThanOrEqual(prop.missionsCompleted);

    expect(
      Number.isInteger(prop.missionsCompleted7Days)
    ).toBe(true);

    expect(
      prop.missionsCompleted7Days
    ).toBeGreaterThan(0);

  });

  test('returns an object containing missionsCompleted which is an integer between 4 and 90', () => {
    expect(
      Number.isInteger(randomMissionsCompleted().missionsCompleted)
    ).toBe(true);

    expect(
      randomMissionsCompleted().missionsCompleted
    ).toBeLessThanOrEqual(90);

    expect(
      randomMissionsCompleted().missionsCompleted
    ).toBeGreaterThanOrEqual(4);
  });
});

describe('randomCoords()', () => {
  const sampleArguments = { coords: { lat: 1, long: 1 }, radius: 1000 };
  const origin = sampleArguments.coords;
  const pickup = randomCoords(sampleArguments);
  const originPoint = turf.point([parseFloat(origin.long), parseFloat(origin.lat)]);
  const pickupPoint = turf.point([parseFloat(pickup.long), parseFloat(pickup.lat)]);

  test('returns a coordinate that is no further than given coordinates by given radius', () => {
    expect(
      turf.distance(originPoint, pickupPoint, 'meters')
    ).toBeLessThanOrEqual(sampleArguments.radius);
  });
});
<|endoftext|>


<commit_before>var assert = require('better-assert');
var Promise = require('../');

describe('synchronous-inspection-tests', function () {
  it('cannot synchronously inspect before enabling synchronous inspection', function(done) {
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve();
      }, 10);
    });
    var rejectedPromise = new Promise(function(resolve, reject) {
      setTimeout(function() {
        reject();
      }, 10);
    });

    assert(fulfilledPromise.getValue == undefined);
    assert(fulfilledPromise.getReason == undefined);
    assert(fulfilledPromise.isFulfilled == undefined);
    assert(fulfilledPromise.isPending == undefined);
    assert(fulfilledPromise.isRejected == undefined);

    assert(rejectedPromise.getValue == undefined);
    assert(rejectedPromise.getReason == undefined);
    assert(rejectedPromise.isFulfilled == undefined);
    assert(rejectedPromise.isPending == undefined);
    assert(rejectedPromise.isRejected == undefined);

    setTimeout(function() {
      assert(fulfilledPromise.getValue == undefined);
      assert(fulfilledPromise.getReason == undefined);
      assert(fulfilledPromise.isFulfilled == undefined);
      assert(fulfilledPromise.isPending == undefined);
      assert(fulfilledPromise.isRejected == undefined);

      assert(rejectedPromise.getValue == undefined);
      assert(rejectedPromise.getReason == undefined);
      assert(rejectedPromise.isFulfilled == undefined);
      assert(rejectedPromise.isPending == undefined);
      assert(rejectedPromise.isRejected == undefined);

      done()
    }, 30);

  });

  it('can poll a promise to see if it is resolved', function (done) {
    Promise.enableSynchronous();
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      var interval = setInterval(function() {
        if (finished !== null) {
          clearTimeout(interval);

          if (finished) {
            resolve(true);
          }
          else {
            reject(false);
          }
        }
      }, 10);
    });

    assert(fulfilledPromise.isPending());
    assert(!fulfilledPromise.isFulfilled());
    assert(!fulfilledPromise.isRejected());

    finished = true;

    setTimeout(function () {
      assert(fulfilledPromise.isFulfilled());
      assert(!fulfilledPromise.isRejected());
      assert(fulfilledPromise.getValue());
      assert(!fulfilledPromise.isPending());

      done();
    }, 30);
  });

  it('can poll a promise to see if it is rejected', function (done) {
    Promise.enableSynchronous();
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      var interval = setInterval(function() {
        if (finished !== null) {
          clearTimeout(interval);

          if (finished) {
            resolve(true);
          }
          else {
            reject(false);
          }
        }
      }, 10);
    });

    assert(fulfilledPromise.isPending());
    assert(!fulfilledPromise.isFulfilled());
    assert(!fulfilledPromise.isRejected());

    finished = false;

    setTimeout(function () {
      assert(!fulfilledPromise.isFulfilled());
      assert(fulfilledPromise.isRejected());
      assert(!fulfilledPromise.getReason());
      assert(!fulfilledPromise.isPending());

      done();
    }, 30);
  });

  it('will throw an error if getting a value of an unfulfilled promise', function (done) {
    Promise.enableSynchronous();
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      var interval = setInterval(function() {
        if (finished !== null) {
          clearTimeout(interval);

          if (finished) {
            resolve(true);
          }
          else {
            reject(false);
          }
        }
      }, 10);
    });

    assert(fulfilledPromise.isPending());
    assert(!fulfilledPromise.isFulfilled());
    assert(!fulfilledPromise.isRejected());

    try {
      fulfilledPromise.getValue();

      assert(false);
    }
    catch (e) {
      assert(true);
    }

    finished = false;

    setTimeout(function () {
      try {
        fulfilledPromise.getValue();

        assert(false);
      }
      catch (e) {
        assert(true);
      }

      done();
    }, 30);
  });

  it('will throw an error if getting a reason of a non-rejected promise', function (done) {
    Promise.enableSynchronous();
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      var interval = setInterval(function() {
        if (finished !== null) {
          clearTimeout(interval);

          if (finished) {
            resolve(true);
          }
          else {
            reject(false);
          }
        }
      }, 10);
    });

    assert(fulfilledPromise.isPending());
    assert(!fulfilledPromise.isFulfilled());
    assert(!fulfilledPromise.isRejected());

    try {
      fulfilledPromise.getReason();

      assert(false);
    }
    catch (e) {
      assert(true);
    }

    finished = true;

    setTimeout(function () {
      try {
        fulfilledPromise.getReason();

        assert(false);
      }
      catch (e) {
        assert(true);
      }

      done()
    }, 30);
  });

  it('can disable synchronous inspection', function() {
    Promise.enableSynchronous();
    var testPromise = Promise.resolve('someValue');
    assert(testPromise.getValue() == 'someValue');
    Promise.disableSynchronous();
    assert(testPromise.getValue == undefined);
  });
});
<commit_msg>Adding test coverage for `getState`<commit_after>var assert = require('better-assert');
var Promise = require('../');

describe('synchronous-inspection-tests', function () {
  it('cannot synchronously inspect before enabling synchronous inspection', function(done) {
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve();
      }, 10);
    });
    var rejectedPromise = new Promise(function(resolve, reject) {
      setTimeout(function() {
        reject();
      }, 10);
    });

    assert(fulfilledPromise.getValue == undefined);
    assert(fulfilledPromise.getReason == undefined);
    assert(fulfilledPromise.isFulfilled == undefined);
    assert(fulfilledPromise.isPending == undefined);
    assert(fulfilledPromise.isRejected == undefined);

    assert(rejectedPromise.getValue == undefined);
    assert(rejectedPromise.getReason == undefined);
    assert(rejectedPromise.isFulfilled == undefined);
    assert(rejectedPromise.isPending == undefined);
    assert(rejectedPromise.isRejected == undefined);

    setTimeout(function() {
      assert(fulfilledPromise.getValue == undefined);
      assert(fulfilledPromise.getReason == undefined);
      assert(fulfilledPromise.isFulfilled == undefined);
      assert(fulfilledPromise.isPending == undefined);
      assert(fulfilledPromise.isRejected == undefined);

      assert(rejectedPromise.getValue == undefined);
      assert(rejectedPromise.getReason == undefined);
      assert(rejectedPromise.isFulfilled == undefined);
      assert(rejectedPromise.isPending == undefined);
      assert(rejectedPromise.isRejected == undefined);

      done()
    }, 30);

  });

  it('can poll a promise to see if it is resolved', function (done) {
    Promise.enableSynchronous();
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      var interval = setInterval(function() {
        if (finished !== null) {
          clearTimeout(interval);

          if (finished) {
            resolve(true);
          }
          else {
            reject(false);
          }
        }
      }, 10);
    });

    assert(fulfilledPromise.getState() === 0);
    assert(fulfilledPromise.isPending());
    assert(!fulfilledPromise.isFulfilled());
    assert(!fulfilledPromise.isRejected());

    finished = true;

    setTimeout(function () {
      assert(fulfilledPromise.getState() === 1);
      assert(fulfilledPromise.isFulfilled());
      assert(!fulfilledPromise.isRejected());
      assert(fulfilledPromise.getValue());
      assert(!fulfilledPromise.isPending());

      done();
    }, 30);
  });

  it('can poll a promise to see if it is rejected', function (done) {
    Promise.enableSynchronous();
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      var interval = setInterval(function() {
        if (finished !== null) {
          clearTimeout(interval);

          if (finished) {
            resolve(true);
          }
          else {
            reject(false);
          }
        }
      }, 10);
    });

    assert(fulfilledPromise.getState() === 0);
    assert(fulfilledPromise.isPending());
    assert(!fulfilledPromise.isFulfilled());
    assert(!fulfilledPromise.isRejected());

    finished = false;

    setTimeout(function () {
      assert(fulfilledPromise.getState() === 2);
      assert(!fulfilledPromise.isFulfilled());
      assert(fulfilledPromise.isRejected());
      assert(!fulfilledPromise.getReason());
      assert(!fulfilledPromise.isPending());

      done();
    }, 30);
  });

  it('will throw an error if getting a value of an unfulfilled promise', function (done) {
    Promise.enableSynchronous();
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      var interval = setInterval(function() {
        if (finished !== null) {
          clearTimeout(interval);

          if (finished) {
            resolve(true);
          }
          else {
            reject(false);
          }
        }
      }, 10);
    });

    assert(fulfilledPromise.isPending());
    assert(!fulfilledPromise.isFulfilled());
    assert(!fulfilledPromise.isRejected());

    try {
      fulfilledPromise.getValue();

      assert(false);
    }
    catch (e) {
      assert(true);
    }

    finished = false;

    setTimeout(function () {
      try {
        fulfilledPromise.getValue();

        assert(false);
      }
      catch (e) {
        assert(true);
      }

      done();
    }, 30);
  });

  it('will throw an error if getting a reason of a non-rejected promise', function (done) {
    Promise.enableSynchronous();
    var finished = null;
    var fulfilledPromise = new Promise(function(resolve, reject) {
      var interval = setInterval(function() {
        if (finished !== null) {
          clearTimeout(interval);

          if (finished) {
            resolve(true);
          }
          else {
            reject(false);
          }
        }
      }, 10);
    });

    assert(fulfilledPromise.isPending());
    assert(!fulfilledPromise.isFulfilled());
    assert(!fulfilledPromise.isRejected());

    try {
      fulfilledPromise.getReason();

      assert(false);
    }
    catch (e) {
      assert(true);
    }

    finished = true;

    setTimeout(function () {
      try {
        fulfilledPromise.getReason();

        assert(false);
      }
      catch (e) {
        assert(true);
      }

      done()
    }, 30);
  });

  it('can disable synchronous inspection', function() {
    Promise.enableSynchronous();
    var testPromise = Promise.resolve('someValue');
    assert(testPromise.getValue() == 'someValue');
    Promise.disableSynchronous();
    assert(testPromise.getValue == undefined);
  });
});
<|endoftext|>


<commit_before>/**
 * Buttons.spec.js
 * (c) 2015~ Summernote Team
 * summernote may be freely distributed under the MIT license./
 */
define([
  'chai',
  'jquery',
  'summernote/base/core/agent',
  'summernote/base/core/range',
  'summernote/base/Context'
], function (chai, $, agent, range, Context) {
  'use strict';

  var expect = chai.expect,
    assert = chai.assert;

  // [workaround]
  //  - IE8~11 can't create range in headless mode
  if (agent.isMSIE || agent.isEdge) {
    return;
  }

  describe('Buttons', function () {
    var context, $toolbar, $editable;

    beforeEach(function () {
      $('body').empty(); //important !
      var $note = $('

hello

').appendTo('body');

      var options = $.extend({}, $.summernote.options);
      options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);
      options.toolbar = [
        ['font1', ['style', 'clear']],
        ['font2', ['bold', 'underline', 'italic', 'superscript', 'subscript', 'strikethrough']],
        ['font3', ['fontname', 'fontsize']],
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['table', ['table']],
        ['insert', ['link', 'picture', 'video']],
        ['view', ['fullscreen', 'codeview', 'help']]
      ];
      context = new Context($note, options);
      context.initialize();

      $toolbar = context.layoutInfo.toolbar;
      $editable = context.layoutInfo.editable;
    });

    describe('bold button', function () {
      it('should execute bold command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-bold').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('bold button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-bold');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('italic button', function () {
      it('should execute italic command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-italic').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('italic button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-italic');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('underline button', function () {
      it('should execute underline command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-underline').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('underline button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-underline');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('superscript button', function () {
      it('should execute superscript command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-superscript').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('superscript button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-superscript');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('subscript button', function () {
      it('should execute subscript command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-subscript').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('subscript button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-subscript');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('strikethrough button', function () {
      it('should execute strikethrough command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-strikethrough').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('strikethrough button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-strikethrough');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('clear button state not updated when clicked', function () {
      it('should never look toggled when clicked', function () {
        var $button = $toolbar.find('i.note-icon-eraser').parent();
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isFalse($button.hasClass('active'), 'button is now active');
      });
    });

    describe('font family button', function () {
      it('should select the right font family name in the dropdown list when it is clicked', function () {
        var $li = $toolbar.find('.dropdown-fontname li>a[data-value="Comic Sans MS"]');
        var $span = $toolbar.find('span.note-current-fontname');
        assert.isTrue($li.length === 1);
        assert.isTrue($span.text() !== 'Comic Sans MS');
        $li.click();
        assert.isTrue($span.text() === 'Comic Sans MS');
      });
    });

    describe('recent color button', function () {
      it('should execute color command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-current-color-button').click();

        var $span = $editable.find('span');
        expect($span).to.be.equalsStyle('#FFFF00', 'background-color');
      });
    });

    describe('fore color button', function () {
      it('should execute fore color command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        var $button = $toolbar.find('[data-event=foreColor]').eq(10);
        $button.click();

        // TODO  tag deprecated in HTML5
        //  - https://github.com/summernote/summernote/issues/745
        var $font = $editable.find('font');
        expect($font).to.be.equalsStyle($button.data('value'), 'color');
      });
    });

    describe('back color button', function () {
      it('should execute back color command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        var $button = $toolbar.find('[data-event=backColor]').eq(10);
        $button.click();

        var $span = $editable.find('span');
        expect($span).to.be.equalsStyle($button.data('value'), 'background-color');
      });
    });
  });
});
<commit_msg>Skip buttons.spec tests on firefox.<commit_after>/**
 * Buttons.spec.js
 * (c) 2015~ Summernote Team
 * summernote may be freely distributed under the MIT license./
 */
define([
  'chai',
  'jquery',
  'summernote/base/core/agent',
  'summernote/base/core/range',
  'summernote/base/Context'
], function (chai, $, agent, range, Context) {
  'use strict';

  var expect = chai.expect,
    assert = chai.assert;

  // [workaround]
  //  - Firefox need setTimeout for applying contents
  //  - IE8~11 can't create range in headless mode
  if (agent.isFF || agent.isMSIE) {
    return;
  }

  describe('Buttons', function () {
    var context, $toolbar, $editable;

    beforeEach(function () {
      $('body').empty(); //important !
      var $note = $('

hello

').appendTo('body');

      var options = $.extend({}, $.summernote.options);
      options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);
      options.toolbar = [
        ['font1', ['style', 'clear']],
        ['font2', ['bold', 'underline', 'italic', 'superscript', 'subscript', 'strikethrough']],
        ['font3', ['fontname', 'fontsize']],
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['table', ['table']],
        ['insert', ['link', 'picture', 'video']],
        ['view', ['fullscreen', 'codeview', 'help']]
      ];
      context = new Context($note, options);
      context.initialize();

      $toolbar = context.layoutInfo.toolbar;
      $editable = context.layoutInfo.editable;
    });

    describe('bold button', function () {
      it('should execute bold command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-bold').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('bold button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-bold');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('italic button', function () {
      it('should execute italic command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-italic').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('italic button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-italic');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('underline button', function () {
      it('should execute underline command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-underline').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('underline button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-underline');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('superscript button', function () {
      it('should execute superscript command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-superscript').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('superscript button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-superscript');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('subscript button', function () {
      it('should execute subscript command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-subscript').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('subscript button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-subscript');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('strikethrough button', function () {
      it('should execute strikethrough command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-btn-strikethrough').click();
        expect($editable.html()).to.equalsIgnoreCase('
hello
');
      });
    });

    describe('strikethrough button state updated', function () {
      it('should look toggled immediately when clicked', function () {
        var $button = $toolbar.find('.note-btn-strikethrough');
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isTrue($button.hasClass('active'), 'button is now active');
      });
    });

    describe('clear button state not updated when clicked', function () {
      it('should never look toggled when clicked', function () {
        var $button = $toolbar.find('i.note-icon-eraser').parent();
        assert.isTrue($button.length === 1);
        assert.isFalse($button.hasClass('active'));
        $button.click();
        assert.isFalse($button.hasClass('active'), 'button is now active');
      });
    });

    describe('font family button', function () {
      it('should select the right font family name in the dropdown list when it is clicked', function () {
        var $li = $toolbar.find('.dropdown-fontname li>a[data-value="Comic Sans MS"]');
        var $span = $toolbar.find('span.note-current-fontname');
        assert.isTrue($li.length === 1);
        assert.isTrue($span.text() !== 'Comic Sans MS');
        $li.click();
        assert.isTrue($span.text() === 'Comic Sans MS');
      });
    });

    describe('recent color button', function () {
      it('should execute color command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        $toolbar.find('.note-current-color-button').click();

        var $span = $editable.find('span');
        expect($span).to.be.equalsStyle('#FFFF00', 'background-color');
      });
    });

    describe('fore color button', function () {
      it('should execute fore color command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        var $button = $toolbar.find('[data-event=foreColor]').eq(10);
        $button.click();

        // TODO  tag deprecated in HTML5
        //  - https://github.com/summernote/summernote/issues/745
        var $font = $editable.find('font');
        expect($font).to.be.equalsStyle($button.data('value'), 'color');
      });
    });

    describe('back color button', function () {
      it('should execute back color command when it is clicked', function () {
        range.createFromNode($editable.find('p')[0]).normalize().select();

        var $button = $toolbar.find('[data-event=backColor]').eq(10);
        $button.click();

        var $span = $editable.find('span');
        expect($span).to.be.equalsStyle($button.data('value'), 'background-color');
      });
    });
  });
});
<|endoftext|>


<commit_before>import {expect} from 'chai';
import React from 'react/addons';

import Catalog from '../../../src/components/catalog';

const TestUtils = React.addons.TestUtils;

describe('Catalog component', () => {

  it('renders html headers', () => {
    const catalog = TestUtils.renderIntoDocument(
      <Catalog />
    );
    const titles = TestUtils.scryRenderedDOMComponentsWithTag(catalog, 'th');
    expect(titles[0].getDOMNode().textContent).to.equal('Class');
    expect(titles[1].getDOMNode().textContent).to.equal('Professor');
    expect(titles[2].getDOMNode().textContent).to.equal('Credits');
    expect(titles[3].getDOMNode().textContent).to.equal('Time');
  });

});
<commit_msg>1.2.0.<commit_after>import {expect} from 'chai';
import React from 'react/addons';

import Catalog from '../../../src/components/catalog';
import Course from '../../../src/components/course';

const TestUtils = React.addons.TestUtils;

describe('Catalog component', () => {

  it('renders html headers', () => {
    const catalog = TestUtils.renderIntoDocument(
      <Catalog />
    );
    const titles = TestUtils.scryRenderedDOMComponentsWithTag(catalog, 'th');
    expect(titles[0].getDOMNode().textContent).to.equal('Class');
    expect(titles[1].getDOMNode().textContent).to.equal('Professor');
    expect(titles[2].getDOMNode().textContent).to.equal('Credits');
    expect(titles[3].getDOMNode().textContent).to.equal('Time');
  });

  it('renders all courses', () => {
    const catalog = [ {
        id: 'RUN105',
        name: 'Ancient Runes',
        startTime: new Date(0, 0, 0, 13),
        professor: 'Bathsheba Babbling',
        credits: 3,
      }, {
        id: 'AST101',
        name: 'Astronomy',
        startTime: new Date(0, 0, 0, 11),
        professor: 'Aurora Sinistra',
        credits: 3,
      }, {
        id: 'DDA302-10',
        name: 'Defence Against the Dark Arts',
        startTime: new Date(0, 0, 0, 10),
        professor: 'Severus Snape',
        credits: 4,
      },
    ];

    const renderedCatalog = TestUtils.renderIntoDocument(
      <Catalog catalog={catalog}/>
    );

    const courses = TestUtils.scryRenderedComponentsWithType(renderedCatalog, Course);
    expect(courses).to.have.length(3);
  });

});
<|endoftext|>


<commit_before>'use strict';

(function() {
  describe('HeaderController', function() {
    var $scope, $rootScope, createController;

    beforeEach(module('angularMoon'));

    beforeEach(inject(function($injector) {
      $rootScope = $injector.get('$rootScope');
      $scope = $rootScope.$new();

      var $controller = $injector.get('$controller');

      createController = function() {
        return $controller('HeaderController');
      };
    }));

    it("should set the current menu item to 'home'", function() {
      createController();
      $scope.init();

      expect($rootScope.currentItem).toBe('home');

    });

  });
})();<commit_msg>Passing test for the header controller<commit_after>'use strict';

(function() {
  describe('HeaderController', function() {
    var $scope, $rootScope, createController;

    beforeEach(module('angularMoon'));

    beforeEach(inject(function($injector) {
      $rootScope = $injector.get('$rootScope');
      $scope = $rootScope.$new();

      var $controller = $injector.get('$controller');

      createController = function() {
        return $controller('HeaderController', {
          '$scope': $scope
        });
      };
    }));

    it("should set the current menu item to 'home'", function() {
      createController();
      $scope.init();
      expect($rootScope.currentItem).toBe('home');
    });

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