<commit_before>(function() {

  var allTests = [];
  var namespaces = [];
  var currentTest;
  var currentArgs;
  var currentMode;
  var currentMethod;
  var currentNamespace;

  // The global context
  var globalContext = typeof global !== 'undefined' ? global : this;

  // Has ability to use Object.defineProperty
  testDefinePropertySupport = !!(Object.defineProperty && Object.defineProperties);

  testInternalToString = Object.prototype.toString;

  // Global methods.
  // BE CAREFUL HERE! If you declare these using window.xxx or
  // some form thereof they will not trigger errors in IE7!

  runTests = function(fn, mode, env) {
    var time = new Date;
    var tests = getTestsToRun();
    currentMode = mode;
    environment = env;
    for (var i = 0; i < tests.length; i++) {
      currentTest = tests[i];
      if (typeof currentTest.fn != 'function') {
        throw new Error('Test ' + currentTest.name + ' has no tests.');
        continue;
      }
      if (currentTest.namespace.setup) {
        currentTest.namespace.setup();
      }
      currentTest.fn();
      if (currentTest.namespace.teardown) {
        currentTest.namespace.teardown();
      }
      currentTest = null;
    }
    var runAll = arrayFilter(namespaces, function(p) {
      return p.assertions > 0 || p.failures.length;
    });
    fn(new Date() - time, runAll);
    allTests = [];
    namespaces = [];
  }

  namespace = function (name, fn, focused) {
    var split;
    split = name.split(' | ');
    currentNamespace = {
      name: split[0],
      subname: split[1],
      focused: !!focused,
      assertions: 0,
      skipped: [],
      failures: []
    };
    namespaces.push(currentNamespace);
    // Queue the tests...
    fn.call();
    currentNamespace = null;
  }

  fnamespace = function(name, fn) {
    namespace(name, fn, true);
  }

  // Noop
  xnamespace = function() {};

  equal = function (actual, expected, message, stack) {
    currentTest.namespace.assertions++;
    if (!isEqual(actual, expected)) {
      addFailure(actual, expected, getFullMessage(message), stack);
    }
  }

  equalWithMargin = function (actual, expected, margin, message) {
    equal((actual > expected - margin) && (actual < expected + margin), true, message, null, 1);
  }

  // Array content is equal, but order may differ
  assertArrayEquivalent = function (a, b, message) {
    equal(sortOnStringValue(a), sortOnStringValue(b), message);
  }

  notEqual = function (actual, expected, message) {
    equal(actual !== expected, true, message + ' | strict equality', 1);
  }

  raisesError = function (fn, message, errorType) {
    var err;
    try {
      fn.call();
    } catch(e) {
      err = e;
    }
    if (errorType) {
      equal(err instanceof errorType, true, message, 1);
    } else {
      if (err && err.message.match(/cannot read property/i)) {
        console.warn('Possible missing method. Error:\n', err.stack);
      }
      equal(!!err, true, message, 1);
    }
  }

  method = function (name, fn, focused, ignored) {
    allTests.push({
      fn: fn,
      name: name,
      focused: !!focused,
      ignored: !!ignored,
      namespace: currentNamespace
    });
  }

  fmethod = function(name, fn) {
    method(name, fn, true);
  }

  xmethod = function(name, fn) {
    method(name, fn, false, true);
  }

  // Alias
  group = method;
  fgroup = fmethod;
  xgroup = xmethod;

  setup = function(fn) {
    currentNamespace.setup = fn;
  }

  teardown = function(fn) {
    currentNamespace.teardown = fn;
  }

  withArgs = function(args) {
    var name, fn;
    if (arguments.length === 2) {
      fn   = arguments[1];
    } else if (arguments.length === 3) {
      name = arguments[1];
      fn   = arguments[2];
    }
    currentTest.message = name || args.join(', ');
    currentArgs = args;
    fn();
    currentTest.message = null;
    currentArgs = null;
  }

  withMethod = function(name, fn) {
    var namespace = currentTest.namespace.name;
    if (!Sugar[namespace][name]) {
      var key = [namespace, currentTest.name, name].join(' | ')
      currentTest.namespace.skipped.push(key);
      return;
    }
    currentMethod = name;
    fn();
    currentMethod = null;
  }

  isDefaultMode = function() {
    return currentMode === 'default';
  }

  isChainedMode = function() {
    return currentMode === 'chained';
  }

  isExtendedMode = function() {
    return currentMode === 'extended';
  }

  test = function (subject) {
    var args, expected, message;
    switch(arguments.length) {
      case 2:
        expected = arguments[1];
        message  = subject;
        break;
      case 3:
        expected = arguments[1];
        message  = arguments[2];
        break;
      case 4:
        args     = arguments[1];
        expected = arguments[2];
        message  = arguments[3];
        break;
    }
    equal(run(subject, null, args), expected, message);
  }

  run = function (subject, methodName, args) {
    var namespace = currentTest.namespace.name;
    var isInstance = !objectIsClass(subject);
    methodName = methodName || currentMethod || currentTest.name;
    args = args || currentArgs || [];
    if (currentMode === 'extended' && isInstance) {
      return globalContext[namespace].prototype[methodName].apply(subject, args);
    } else if (currentMode === 'chained' && isInstance) {
      subject = new Sugar[namespace](subject);
      return subject[methodName].apply(subject, args).raw;
    } else {
      if (isInstance) {
        args = [subject].concat(args);
      }
      if (!Sugar[namespace][methodName]) {
        throw new Error('missing method ' + methodName);
      }
      return Sugar[namespace][methodName].apply(null, args);
    }
  }

  getCurrentTest = function() {
    return currentTest;
  }

  function getTestsToRun() {
    var focusedNamespacesExist = false;

    function namespaceIsActive(namespace) {
      if (!focusedNamespacesExist) {
        return true;
      }
      return namespace.focused;
    }

    for (var i = 0; i < namespaces.length; i++) {
      if (namespaces[i].focused) {
        focusedNamespacesExist = true;
        break;
      }
    }

    var focused = arrayFilter(allTests, function(t) {
      return t.focused && namespaceIsActive(t.namespace);
    });

    if (focused.length) {
      return focused;
    }

    return arrayFilter(allTests, function(t) {
      return !t.ignored && namespaceIsActive(t.namespace);
    });
  }

  function objectIsClass(obj) {
    switch(obj) {
      case Boolean:
      case Number:
      case String:
      case Array:
      case Object:
      case Date:
      case RegExp:
      case Function:
        return true;
    }
    return false;
  }

  function getGlobalName(global) {
    if (global && global.name) {
      return global.name;
    }
    // < IE9 environments do not have .name
    switch (global) {
      case Boolean:  return 'Boolean';
      case Number:   return 'Number';
      case String:   return 'String';
      case Array:    return 'Array';
      case Object:   return 'Object';
      case Date:     return 'Date';
      case RegExp:   return 'RegExp';
      case Function: return 'Function';
    }
  }

  function getFullMessage(tail) {
    var msg = '';
    var title = currentTest.name;
    if (title) {
      msg += title + ' | ';
    }
    if (currentTest.message) {
      msg += currentTest.message + ' | ';
    }
    msg += tail;
    return msg;
  }

  function addFailure(actual, expected, message, stack, warning) {
    var meta = getMeta(stack);
    currentTest.namespace.failures.push({
      actual: actual,
      expected: expected,
      message: message,
      file: meta.file,
      line: meta.line,
      col: meta.col,
      warning: !!warning
    });
  }

  function getMeta(stack) {
    var level = 4;
    if (stack !== undefined) {
      level += stack;
    }
    var e = new Error();
    if (!e.stack) {
      return {};
    }
    var s = e.stack.split(/@|^\s+at/m);
    var match = s[level].match(/(.+\.js):(\d+)(?::(\d+))?/);
    if (!match) match = [];
    return { file: match[1], line: match[2], col: match[3] };
  }

  // Equality test methods.

  function isEqual(one, two) {
    var type, klass;

    type = typeof one;

    if (type === 'string' || type === 'boolean' || one == null) {
      return one === two;
    } else if (type === 'number') {
      return typeof two === 'number' && ((isNaN(one) && isNaN(two)) || one === two);
    }

    klass = testInternalToString.call(one);

    if (klass === '[object Date]' && two.getTime) {
      return dateIsEqual(one, two);
    } else if (klass === '[object RegExp]') {
      return String(one) === String(two);
    } else if (klass === '[object Array]' || klass === '[object Arguments]') {
      return arrayIsEqual(one, two) && klass === testInternalToString.call(two);
    } else if (klass === '[object Object]' && ('hasOwnProperty' in one) && type === 'object') {
      return objectIsEqual(one, two) && klass === testInternalToString.call(two);
    } else if (klass === '[object Number]' && isNaN(one) && isNaN(two)) {
      return true;
    } else if (klass === '[object String]') {
      return one.valueOf() === two.valueOf();
    }

    return one === two;
  }

  // Arrays and objects must be treated separately here because in IE arrays with undefined
  // elements will not pass the .hasOwnProperty check. For example [undefined].hasOwnProperty('0')
  // will report false.
  function arrayIsEqual(one, two) {
    var i, result = true, key;
    if (one === two) {
      return true;
    }
    if (!one || !two || typeof one !== 'object' || typeof two !== 'object') {
      return false;
    }
    arrayEach(one, function(a, i) {
      if (!isEqual(one[i], two[i])) {
        result = false;
      }
    });
    if (!result) {
      return false;
    }
    var onep = 0, twop = 0;
    for(key in one) {
      if (!one.hasOwnProperty(key)) continue;
      onep++;
      if (!isEqual(one[key], two[key])) {
        return false;
      }
    }
    for(key in two) {
      if (!two.hasOwnProperty(key)) continue;
      twop++;
    }
    return result && one.length === two.length && onep === twop;
  }

  function objectIsEqual(one, two) {
    var onep = 0, twop = 0, key;
    if (one && two) {
      for(key in one) {
        if (!one.hasOwnProperty(key)) continue;
        onep++;
        if (!isEqual(one[key], two[key])) {
          return false;
        }
      }
      for(key in two) {
        if (!two.hasOwnProperty(key)) continue;
        twop++;
      }
    }
    return onep === twop && String(one) === String(two);
  }

  function dateIsEqual(a, b) {
    var buffer = 50; // Number of milliseconds of "play" to make sure these tests pass.
    if (typeof b == 'number') {
      var d = new Date();
      d.setTime(d.getTime() + b);
      b = d;
    }
    var offset = Math.abs(a.getTime() - b.getTime());
    return offset < buffer;
  }

  function sortOnStringValue(arr) {
    return arr.sort(function(a, b) {
      var aStr = getStringValueForObject(a);
      var bStr = getStringValueForObject(b);
      if (aStr === bStr) return 0;
      return aStr < bStr ? -1 : 1;
    });
  }

  function getStringValueForObject(obj) {
    var type = typeof obj, str;
    if (type === 'object') {
      str = 'obj:';
      for (var key in obj) {
        if (!obj.hasOwnProperty(key)) continue;
        str += key + getStringValueForObject(obj[key]);
      }
      return str;
    } else {
      return 'pri:' + type + String(obj);
    }
  }

  // Iteration methods

  // Tests may include sparse arrays, so need a way to iterate
  // over them safely here.
  function arrayEach(arr, fn, sparse) {
    var length = arr.length, i = 0;
    while(i < length) {
      if (!(i in arr)) {
        return iterateOverArray(arr, fn, i);
      } else if (fn.call(arr, arr[i], i, arr) === false) {
        break;
      }
      i++;
    }
  }

  function iterateOverArray(arr, fn, fromIndex) {
    var indexes = [], i;
    for(i in arr) {
      if (isArrayIndex(arr, i) && i >= fromIndex) {
        indexes.push(parseInt(i));
      }
    }
    arrayEach(indexes.sort(), function(index) {
      return fn.call(arr, arr[index], index, arr);
    });
    return arr;
  }

  function arrayFilter(arr, fn) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
      if (fn(arr[i], i)) {
        result.push(arr[i]);
      }
    }
    return result;
  }

  function isArrayIndex(arr, i) {
    return i in arr && (i >>> 0) == i && i != 0xffffffff;
  }

  if (typeof console === 'undefined') {

    if (typeof $ !== 'undefined') {
      var consoleFn = function() {
        var messages = Array.prototype.slice.call(arguments);
        messages = messages.map(function(arg) {
          return String(arg);
        })
        $('<p/>').css({
          fontFamily: 'monospace',
          fontSize: '12px'
        }).text(messages.join(',')).appendTo(document.body);
      }
      console = {
        log: consoleFn,
        info: consoleFn
      }
    } else if (typeof print !== 'undefined') {
      console = {
        log: print,
        info: print
      }
    }
  }

})();
<commit_msg>upping buffer for date tests<commit_after>(function() {

  var allTests = [];
  var namespaces = [];
  var currentTest;
  var currentArgs;
  var currentMode;
  var currentMethod;
  var currentNamespace;

  // The global context
  var globalContext = typeof global !== 'undefined' ? global : this;

  // Has ability to use Object.defineProperty
  testDefinePropertySupport = !!(Object.defineProperty && Object.defineProperties);

  testInternalToString = Object.prototype.toString;

  // Global methods.
  // BE CAREFUL HERE! If you declare these using window.xxx or
  // some form thereof they will not trigger errors in IE7!

  runTests = function(fn, mode, env) {
    var time = new Date;
    var tests = getTestsToRun();
    currentMode = mode;
    environment = env;
    for (var i = 0; i < tests.length; i++) {
      currentTest = tests[i];
      if (typeof currentTest.fn != 'function') {
        throw new Error('Test ' + currentTest.name + ' has no tests.');
        continue;
      }
      if (currentTest.namespace.setup) {
        currentTest.namespace.setup();
      }
      currentTest.fn();
      if (currentTest.namespace.teardown) {
        currentTest.namespace.teardown();
      }
      currentTest = null;
    }
    var runAll = arrayFilter(namespaces, function(p) {
      return p.assertions > 0 || p.failures.length;
    });
    fn(new Date() - time, runAll);
    allTests = [];
    namespaces = [];
  }

  namespace = function (name, fn, focused) {
    var split;
    split = name.split(' | ');
    currentNamespace = {
      name: split[0],
      subname: split[1],
      focused: !!focused,
      assertions: 0,
      skipped: [],
      failures: []
    };
    namespaces.push(currentNamespace);
    // Queue the tests...
    fn.call();
    currentNamespace = null;
  }

  fnamespace = function(name, fn) {
    namespace(name, fn, true);
  }

  // Noop
  xnamespace = function() {};

  equal = function (actual, expected, message, stack) {
    currentTest.namespace.assertions++;
    if (!isEqual(actual, expected)) {
      addFailure(actual, expected, getFullMessage(message), stack);
    }
  }

  equalWithMargin = function (actual, expected, margin, message) {
    equal((actual > expected - margin) && (actual < expected + margin), true, message, null, 1);
  }

  // Array content is equal, but order may differ
  assertArrayEquivalent = function (a, b, message) {
    equal(sortOnStringValue(a), sortOnStringValue(b), message);
  }

  notEqual = function (actual, expected, message) {
    equal(actual !== expected, true, message + ' | strict equality', 1);
  }

  raisesError = function (fn, message, errorType) {
    var err;
    try {
      fn.call();
    } catch(e) {
      err = e;
    }
    if (errorType) {
      equal(err instanceof errorType, true, message, 1);
    } else {
      if (err && err.message.match(/cannot read property/i)) {
        console.warn('Possible missing method. Error:\n', err.stack);
      }
      equal(!!err, true, message, 1);
    }
  }

  method = function (name, fn, focused, ignored) {
    allTests.push({
      fn: fn,
      name: name,
      focused: !!focused,
      ignored: !!ignored,
      namespace: currentNamespace
    });
  }

  fmethod = function(name, fn) {
    method(name, fn, true);
  }

  xmethod = function(name, fn) {
    method(name, fn, false, true);
  }

  // Alias
  group = method;
  fgroup = fmethod;
  xgroup = xmethod;

  setup = function(fn) {
    currentNamespace.setup = fn;
  }

  teardown = function(fn) {
    currentNamespace.teardown = fn;
  }

  withArgs = function(args) {
    var name, fn;
    if (arguments.length === 2) {
      fn   = arguments[1];
    } else if (arguments.length === 3) {
      name = arguments[1];
      fn   = arguments[2];
    }
    currentTest.message = name || args.join(', ');
    currentArgs = args;
    fn();
    currentTest.message = null;
    currentArgs = null;
  }

  withMethod = function(name, fn) {
    var namespace = currentTest.namespace.name;
    if (!Sugar[namespace][name]) {
      var key = [namespace, currentTest.name, name].join(' | ')
      currentTest.namespace.skipped.push(key);
      return;
    }
    currentMethod = name;
    fn();
    currentMethod = null;
  }

  isDefaultMode = function() {
    return currentMode === 'default';
  }

  isChainedMode = function() {
    return currentMode === 'chained';
  }

  isExtendedMode = function() {
    return currentMode === 'extended';
  }

  test = function (subject) {
    var args, expected, message;
    switch(arguments.length) {
      case 2:
        expected = arguments[1];
        message  = subject;
        break;
      case 3:
        expected = arguments[1];
        message  = arguments[2];
        break;
      case 4:
        args     = arguments[1];
        expected = arguments[2];
        message  = arguments[3];
        break;
    }
    equal(run(subject, null, args), expected, message);
  }

  run = function (subject, methodName, args) {
    var namespace = currentTest.namespace.name;
    var isInstance = !objectIsClass(subject);
    methodName = methodName || currentMethod || currentTest.name;
    args = args || currentArgs || [];
    if (currentMode === 'extended' && isInstance) {
      return globalContext[namespace].prototype[methodName].apply(subject, args);
    } else if (currentMode === 'chained' && isInstance) {
      subject = new Sugar[namespace](subject);
      return subject[methodName].apply(subject, args).raw;
    } else {
      if (isInstance) {
        args = [subject].concat(args);
      }
      if (!Sugar[namespace][methodName]) {
        throw new Error('missing method ' + methodName);
      }
      return Sugar[namespace][methodName].apply(null, args);
    }
  }

  getCurrentTest = function() {
    return currentTest;
  }

  function getTestsToRun() {
    var focusedNamespacesExist = false;

    function namespaceIsActive(namespace) {
      if (!focusedNamespacesExist) {
        return true;
      }
      return namespace.focused;
    }

    for (var i = 0; i < namespaces.length; i++) {
      if (namespaces[i].focused) {
        focusedNamespacesExist = true;
        break;
      }
    }

    var focused = arrayFilter(allTests, function(t) {
      return t.focused && namespaceIsActive(t.namespace);
    });

    if (focused.length) {
      return focused;
    }

    return arrayFilter(allTests, function(t) {
      return !t.ignored && namespaceIsActive(t.namespace);
    });
  }

  function objectIsClass(obj) {
    switch(obj) {
      case Boolean:
      case Number:
      case String:
      case Array:
      case Object:
      case Date:
      case RegExp:
      case Function:
        return true;
    }
    return false;
  }

  function getGlobalName(global) {
    if (global && global.name) {
      return global.name;
    }
    // < IE9 environments do not have .name
    switch (global) {
      case Boolean:  return 'Boolean';
      case Number:   return 'Number';
      case String:   return 'String';
      case Array:    return 'Array';
      case Object:   return 'Object';
      case Date:     return 'Date';
      case RegExp:   return 'RegExp';
      case Function: return 'Function';
    }
  }

  function getFullMessage(tail) {
    var msg = '';
    var title = currentTest.name;
    if (title) {
      msg += title + ' | ';
    }
    if (currentTest.message) {
      msg += currentTest.message + ' | ';
    }
    msg += tail;
    return msg;
  }

  function addFailure(actual, expected, message, stack, warning) {
    var meta = getMeta(stack);
    currentTest.namespace.failures.push({
      actual: actual,
      expected: expected,
      message: message,
      file: meta.file,
      line: meta.line,
      col: meta.col,
      warning: !!warning
    });
  }

  function getMeta(stack) {
    var level = 4;
    if (stack !== undefined) {
      level += stack;
    }
    var e = new Error();
    if (!e.stack) {
      return {};
    }
    var s = e.stack.split(/@|^\s+at/m);
    var match = s[level].match(/(.+\.js):(\d+)(?::(\d+))?/);
    if (!match) match = [];
    return { file: match[1], line: match[2], col: match[3] };
  }

  // Equality test methods.

  function isEqual(one, two) {
    var type, klass;

    type = typeof one;

    if (type === 'string' || type === 'boolean' || one == null) {
      return one === two;
    } else if (type === 'number') {
      return typeof two === 'number' && ((isNaN(one) && isNaN(two)) || one === two);
    }

    klass = testInternalToString.call(one);

    if (klass === '[object Date]' && two.getTime) {
      return dateIsEqual(one, two);
    } else if (klass === '[object RegExp]') {
      return String(one) === String(two);
    } else if (klass === '[object Array]' || klass === '[object Arguments]') {
      return arrayIsEqual(one, two) && klass === testInternalToString.call(two);
    } else if (klass === '[object Object]' && ('hasOwnProperty' in one) && type === 'object') {
      return objectIsEqual(one, two) && klass === testInternalToString.call(two);
    } else if (klass === '[object Number]' && isNaN(one) && isNaN(two)) {
      return true;
    } else if (klass === '[object String]') {
      return one.valueOf() === two.valueOf();
    }

    return one === two;
  }

  // Arrays and objects must be treated separately here because in IE arrays with undefined
  // elements will not pass the .hasOwnProperty check. For example [undefined].hasOwnProperty('0')
  // will report false.
  function arrayIsEqual(one, two) {
    var i, result = true, key;
    if (one === two) {
      return true;
    }
    if (!one || !two || typeof one !== 'object' || typeof two !== 'object') {
      return false;
    }
    arrayEach(one, function(a, i) {
      if (!isEqual(one[i], two[i])) {
        result = false;
      }
    });
    if (!result) {
      return false;
    }
    var onep = 0, twop = 0;
    for(key in one) {
      if (!one.hasOwnProperty(key)) continue;
      onep++;
      if (!isEqual(one[key], two[key])) {
        return false;
      }
    }
    for(key in two) {
      if (!two.hasOwnProperty(key)) continue;
      twop++;
    }
    return result && one.length === two.length && onep === twop;
  }

  function objectIsEqual(one, two) {
    var onep = 0, twop = 0, key;
    if (one && two) {
      for(key in one) {
        if (!one.hasOwnProperty(key)) continue;
        onep++;
        if (!isEqual(one[key], two[key])) {
          return false;
        }
      }
      for(key in two) {
        if (!two.hasOwnProperty(key)) continue;
        twop++;
      }
    }
    return onep === twop && String(one) === String(two);
  }

  function dateIsEqual(a, b) {
    var buffer = 80; // Number of milliseconds of "play" to make sure these tests pass.
    if (typeof b == 'number') {
      var d = new Date();
      d.setTime(d.getTime() + b);
      b = d;
    }
    var offset = Math.abs(a.getTime() - b.getTime());
    return offset < buffer;
  }

  function sortOnStringValue(arr) {
    return arr.sort(function(a, b) {
      var aStr = getStringValueForObject(a);
      var bStr = getStringValueForObject(b);
      if (aStr === bStr) return 0;
      return aStr < bStr ? -1 : 1;
    });
  }

  function getStringValueForObject(obj) {
    var type = typeof obj, str;
    if (type === 'object') {
      str = 'obj:';
      for (var key in obj) {
        if (!obj.hasOwnProperty(key)) continue;
        str += key + getStringValueForObject(obj[key]);
      }
      return str;
    } else {
      return 'pri:' + type + String(obj);
    }
  }

  // Iteration methods

  // Tests may include sparse arrays, so need a way to iterate
  // over them safely here.
  function arrayEach(arr, fn, sparse) {
    var length = arr.length, i = 0;
    while(i < length) {
      if (!(i in arr)) {
        return iterateOverArray(arr, fn, i);
      } else if (fn.call(arr, arr[i], i, arr) === false) {
        break;
      }
      i++;
    }
  }

  function iterateOverArray(arr, fn, fromIndex) {
    var indexes = [], i;
    for(i in arr) {
      if (isArrayIndex(arr, i) && i >= fromIndex) {
        indexes.push(parseInt(i));
      }
    }
    arrayEach(indexes.sort(), function(index) {
      return fn.call(arr, arr[index], index, arr);
    });
    return arr;
  }

  function arrayFilter(arr, fn) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
      if (fn(arr[i], i)) {
        result.push(arr[i]);
      }
    }
    return result;
  }

  function isArrayIndex(arr, i) {
    return i in arr && (i >>> 0) == i && i != 0xffffffff;
  }

  if (typeof console === 'undefined') {

    if (typeof $ !== 'undefined') {
      var consoleFn = function() {
        var messages = Array.prototype.slice.call(arguments);
        messages = messages.map(function(arg) {
          return String(arg);
        })
        $('<p/>').css({
          fontFamily: 'monospace',
          fontSize: '12px'
        }).text(messages.join(',')).appendTo(document.body);
      }
      console = {
        log: consoleFn,
        info: consoleFn
      }
    } else if (typeof print !== 'undefined') {
      console = {
        log: print,
        info: print
      }
    }
  }

})();
<|endoftext|>


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

function IN_BROWSER() { return typeof vm == "undefined" || ! vm.runInThisContext; }
function IN_NODEJS() { return ! IN_BROWSER(); }

var files = [
//  ['ServiceWorker', function() { return window.navigator && navigator.serviceWorker; }],
  ['firefox',  function() { return window.navigator && navigator.userAgent.indexOf('Firefox') != -1; }],
  ['funcName', function() { return ! Number.name; }],
  ['safari',   function() { return window.navigator && navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1; }],
  [ 'i18n',    function() { return typeof vm == "undefined" || vm.Script !== vm; } ],
  'stdlib',
  ['WeakMap',  function() { return ! this['WeakMap']; }],
  'io',
  'writer',
  'socket',
  'base64',
  'encodings',
  'utf8',
  'async',
  'parse',
  'event',
  'JSONUtil',
  'XMLUtil',
  'context',
  'JSONParser',
  'TemplateUtil',
  'FOAM',
  // To use FO, uncomment the next line
  // and comment out all lines from FObject to mm5Misc
  // inclusively
//  'experimental/fo',
//  'experimental/protobuffeatures',
  'FObject',
  'BootstrapModel',
  'mm1Model',
  'mm2Property',
  'mm3Types',
  'mm4Method',
  'mm5Misc',
  'LayoutTraits', // generic, non-view specific, so no predicate
  [ 'value', IN_BROWSER ],
  [ 'view', IN_BROWSER ],
  [ 'view2', IN_BROWSER ],
  [ 'layout', IN_BROWSER ],
  [ 'AbstractDAOView', IN_BROWSER ],
  [ 'DAOListView', IN_BROWSER ],
  [ 'daoView', IN_BROWSER ],
  [ 'ChoiceView', IN_BROWSER ],
  [ 'DetailView', IN_BROWSER ],
  [ 'TableView', IN_BROWSER ],
  [ 'cview', IN_BROWSER ],
  [ 'RichTextView', IN_BROWSER ],
  [ 'listchoiceview', IN_BROWSER ],
  [ 'scroll', IN_BROWSER ],
  [ 'CViewPrimitives', IN_BROWSER ],
  [ 'Diagramming', IN_BROWSER ],
  'HTMLParser',
  'mlang',
  'mlang2',
  'QueryParser',
  'search',
  'oam',
  'visitor',
  'messaging',
  'dao',
  'dao2',
  'arrayDAO',
  'ClientDAO',
  'diff',
  'SplitDAO',
  'index',
  [ 'StackView', IN_BROWSER ],
  [ 'MementoMgr', IN_BROWSER ],
  [ 'DAOController', IN_BROWSER ],
  [ 'ThreePaneController', IN_BROWSER ],
  'experimental/protobufparser',
  'experimental/protobuf',
  'models',
  [ 'touch', IN_BROWSER ],
  [ 'glang', IN_BROWSER ],
  'oauth',
  'busy',
  [ '../apps/mailreader/view', IN_BROWSER ],
  [ '../apps/mailreader/email', IN_BROWSER ],
  [ '../lib/email/email', IN_BROWSER ],
  [ 'turntable', IN_BROWSER ],
  [ 'CORE', IN_BROWSER ],
  [ '../js/foam/core/bootstrap/ModelFileDAO', IN_BROWSER ],
  [ '../js/node/dao/JSModelFileDAO', IN_NODEJS ]
];
<commit_msg>Fix custom check for i18n to be IN_BROWSER<commit_after>/**
 * @license
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function IN_BROWSER() { return typeof vm == "undefined" || ! vm.runInThisContext; }
function IN_NODEJS() { return ! IN_BROWSER(); }

var files = [
//  ['ServiceWorker', function() { return window.navigator && navigator.serviceWorker; }],
  ['firefox',  function() { return window.navigator && navigator.userAgent.indexOf('Firefox') != -1; }],
  ['funcName', function() { return ! Number.name; }],
  ['safari',   function() { return window.navigator && navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1; }],
  [ 'i18n',    IN_BROWSER ],
  'stdlib',
  ['WeakMap',  function() { return ! this['WeakMap']; }],
  'io',
  'writer',
  'socket',
  'base64',
  'encodings',
  'utf8',
  'async',
  'parse',
  'event',
  'JSONUtil',
  'XMLUtil',
  'context',
  'JSONParser',
  'TemplateUtil',
  'FOAM',
  // To use FO, uncomment the next line
  // and comment out all lines from FObject to mm5Misc
  // inclusively
//  'experimental/fo',
//  'experimental/protobuffeatures',
  'FObject',
  'BootstrapModel',
  'mm1Model',
  'mm2Property',
  'mm3Types',
  'mm4Method',
  'mm5Misc',
  'LayoutTraits', // generic, non-view specific, so no predicate
  [ 'value', IN_BROWSER ],
  [ 'view', IN_BROWSER ],
  [ 'view2', IN_BROWSER ],
  [ 'layout', IN_BROWSER ],
  [ 'AbstractDAOView', IN_BROWSER ],
  [ 'DAOListView', IN_BROWSER ],
  [ 'daoView', IN_BROWSER ],
  [ 'ChoiceView', IN_BROWSER ],
  [ 'DetailView', IN_BROWSER ],
  [ 'TableView', IN_BROWSER ],
  [ 'cview', IN_BROWSER ],
  [ 'RichTextView', IN_BROWSER ],
  [ 'listchoiceview', IN_BROWSER ],
  [ 'scroll', IN_BROWSER ],
  [ 'CViewPrimitives', IN_BROWSER ],
  [ 'Diagramming', IN_BROWSER ],
  'HTMLParser',
  'mlang',
  'mlang2',
  'QueryParser',
  'search',
  'oam',
  'visitor',
  'messaging',
  'dao',
  'dao2',
  'arrayDAO',
  'ClientDAO',
  'diff',
  'SplitDAO',
  'index',
  [ 'StackView', IN_BROWSER ],
  [ 'MementoMgr', IN_BROWSER ],
  [ 'DAOController', IN_BROWSER ],
  [ 'ThreePaneController', IN_BROWSER ],
  'experimental/protobufparser',
  'experimental/protobuf',
  'models',
  [ 'touch', IN_BROWSER ],
  [ 'glang', IN_BROWSER ],
  'oauth',
  'busy',
  [ '../apps/mailreader/view', IN_BROWSER ],
  [ '../apps/mailreader/email', IN_BROWSER ],
  [ '../lib/email/email', IN_BROWSER ],
  [ 'turntable', IN_BROWSER ],
  [ 'CORE', IN_BROWSER ],
  [ '../js/foam/core/bootstrap/ModelFileDAO', IN_BROWSER ],
  [ '../js/node/dao/JSModelFileDAO', IN_NODEJS ]
];
<|endoftext|>


<commit_before>'use strict';

process.env.NODE_ENV = 'test';

var path = require('path');

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

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

global.chai = chai;
global.sinon = sinon;

global.should = chai.should();
global.expect = chai.expect;
global.assert = chai.assert;
global.AssertionError = chai.AssertionError;

global.spy = sinon.spy;
global.stub = sinon.stub;
global.shared = require('./shared');

// convenience function to require modules in lib directory
global.source = function(module) {
  return require(path.normalize('./../../lib/' + module));
};

global.Spark = source('spark-api');
<commit_msg>Silence unhandled rejections in tests<commit_after>'use strict';

process.env.NODE_ENV = 'test';

var path = require('path');

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

when.Promise.onPotentiallyUnhandledRejection = function() {};
chai.use(sinonChai);
chai.use(chaiAsPromised);

global.chai = chai;
global.sinon = sinon;

global.should = chai.should();
global.expect = chai.expect;
global.assert = chai.assert;
global.AssertionError = chai.AssertionError;

global.spy = sinon.spy;
global.stub = sinon.stub;
global.shared = require('./shared');

// convenience function to require modules in lib directory
global.source = function(module) {
  return require(path.normalize('./../../lib/' + module));
};

global.Spark = source('spark-api');
<|endoftext|>


<commit_before>angular
  .module('siren', ['ui.state'])
  .provider('classRouter', function() {
      var map = {};

      this.when = function(klass, state) {
        if (!klass) {
          map[null] = { known: false, state: state };
          return this;
        }
        var c = klass.sort().join(' ');
        map[c] = { known: true, state: state };
        return this;
      };

      this.otherwise = function(state) {
        map[null] = { known: false, state: state };
      };

      this.$get = function() {
        return {
          resolve: function(klass) {
            if (!klass) {
              return map[null];
            }
            var c = klass.sort().join(' ');
            return map[c] || map[null];
          }
        };
      };
  })
  .factory('navigator', ['$http', '$rootScope', '$q', '$state', 'classRouter',
      function($http, $rootScope, $q, $state, classRouter) {
    return {
      cache: [],
      current: null,
      redirectOrFetch: function(url, params) {
        return this.fetch(url, params, true);
      },
      fetch: function(url, params, redirectIfKnown) {
        if (this.cache.length) {
          this.current = this.cache.pop();
          return $q.when(this.current.entity);
        }

        var immediateReturn = true;

        return this.transitionTo(url, params, immediateReturn, redirectIfKnown);
      },
      transitionTo: function(url, params, immediateReturn, redirectIfKnown) {
        if (typeof url === 'object' && url.href) {
          url = url.href;
        }

        var self = this;
        var deferred = $q.defer();

        $http.get(url).success(function(data, status, headers, config) {
          var state = classRouter.resolve(data.class);

          self.current = { state: state, entity: data };

          // only cache if the following state must fetch.
          if (!immediateReturn || (redirectIfKnown && state.known)) {
            self.cache.push(self.current);
          }

          $rootScope.$broadcast('entityChangeSuccess', data);

          $state.transitionTo(state.state, params);

          var stateIsUnknown = !state.known;
          var resolveIfKnown = !redirectIfKnown;

          if (immediateReturn && (stateIsUnknown || resolveIfKnown)) {
            deferred.resolve(data);
          }
        });

        if (immediateReturn) {
          return deferred.promise;
        }
      },
      execute: function(action) {
        var contentType = action.type || 'application/x-www-form-urlencoded';
        var options = {
          method: action.method || 'GET',
          url: action.href,
          headers: {
            'Content-Type': contentType,
            'Accept': 'application/vnd.siren+json, application/json, text/plain, */*'
          }
        };

        if (options.method === 'GET') {
          var params = {};

          angular.forEach(action.fields, function(field) {
            params[field.name] = field.value;
          });

          var url = options.url;

          var serialize = function(obj) {
            var str = [];
            for(var p in obj)
              if (obj.hasOwnProperty(p)) {
                console.log('obj[p]:' + obj[p]);
                if (typeof obj[p] != 'undefined') {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
              }
            return str.join("&");
          };

          url = url.split('?')[0] + '?' + serialize(params);

          $state.transitionTo('entity', { url: url });

          var deferred = $q.defer();

          deferred.resolve({ noop: true });

          return deferred.promise;
        } else {

          if (contentType === 'application/json') {
            options.data = {};
            angular.forEach(action.fields, function(field) {
              options.data[field.name] = field.value;
            });
          } else if (contentType === 'application/x-www-form-urlencoded') {
            var data = [];
            angular.forEach(action.fields, function(field) {
              data.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
            });
            if (data.length === 0) {
                options.data = {};
            } else {
                options.data = data.join('&');
            }
          }

          var deferred = $q.defer();

          $http(options).success(function(data, status, headers, config) {
            deferred.resolve({ data: data, config: config });
          })
          .error(function(data, status, headers, config) {
            deferred.reject(status);
          });

          return deferred.promise;
        }
      }
    };
  }]);
<commit_msg>Fixes 2 by allowing vendor specific formats for actions.<commit_after>angular
  .module('siren', ['ui.state'])
  .provider('classRouter', function() {
      var map = {};

      this.when = function(klass, state) {
        if (!klass) {
          map[null] = { known: false, state: state };
          return this;
        }
        var c = klass.sort().join(' ');
        map[c] = { known: true, state: state };
        return this;
      };

      this.otherwise = function(state) {
        map[null] = { known: false, state: state };
      };

      this.$get = function() {
        return {
          resolve: function(klass) {
            if (!klass) {
              return map[null];
            }
            var c = klass.sort().join(' ');
            return map[c] || map[null];
          }
        };
      };
  })
  .factory('navigator', ['$http', '$rootScope', '$q', '$state', 'classRouter',
      function($http, $rootScope, $q, $state, classRouter) {
    return {
      cache: [],
      current: null,
      redirectOrFetch: function(url, params) {
        return this.fetch(url, params, true);
      },
      fetch: function(url, params, redirectIfKnown) {
        if (this.cache.length) {
          this.current = this.cache.pop();
          return $q.when(this.current.entity);
        }

        var immediateReturn = true;

        return this.transitionTo(url, params, immediateReturn, redirectIfKnown);
      },
      transitionTo: function(url, params, immediateReturn, redirectIfKnown) {
        if (typeof url === 'object' && url.href) {
          url = url.href;
        }

        var self = this;
        var deferred = $q.defer();

        $http.get(url).success(function(data, status, headers, config) {
          var state = classRouter.resolve(data.class);

          self.current = { state: state, entity: data };

          // only cache if the following state must fetch.
          if (!immediateReturn || (redirectIfKnown && state.known)) {
            self.cache.push(self.current);
          }

          $rootScope.$broadcast('entityChangeSuccess', data);

          $state.transitionTo(state.state, params);

          var stateIsUnknown = !state.known;
          var resolveIfKnown = !redirectIfKnown;

          if (immediateReturn && (stateIsUnknown || resolveIfKnown)) {
            deferred.resolve(data);
          }
        });

        if (immediateReturn) {
          return deferred.promise;
        }
      },
      execute: function(action) {
        var contentType = action.type || 'application/x-www-form-urlencoded';
        var options = {
          method: action.method || 'GET',
          url: action.href,
          headers: {
            'Content-Type': contentType,
            'Accept': 'application/vnd.siren+json, application/json, text/plain, */*'
          }
        };

        if (options.method === 'GET') {
          var params = {};

          angular.forEach(action.fields, function(field) {
            params[field.name] = field.value;
          });

          var url = options.url;

          var serialize = function(obj) {
            var str = [];
            for(var p in obj)
              if (obj.hasOwnProperty(p)) {
                if (typeof obj[p] != 'undefined') {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
              }
            return str.join("&");
          };

          url = url.split('?')[0] + '?' + serialize(params);

          $state.transitionTo('entity', { url: url });

          var deferred = $q.defer();

          deferred.resolve({ noop: true });

          return deferred.promise;
        } else {
          if (contentType === 'application/json'
             || (contentType.startsWith('application/vnd') && contentType.endsWith('json')) ) {
            options.data = {};
            angular.forEach(action.fields, function(field) {
              options.data[field.name] = field.value;
            });
          } else if (contentType === 'application/x-www-form-urlencoded') {
            var data = [];
            angular.forEach(action.fields, function(field) {
              data.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
            });
            if (data.length === 0) {
                options.data = {};
            } else {
                options.data = data.join('&');
            }
          }

          var deferred = $q.defer();

          $http(options).success(function(data, status, headers, config) {
            deferred.resolve({ data: data, config: config });
          })
          .error(function(data, status, headers, config) {
            deferred.reject(status);
          });

          return deferred.promise;
        }
      }
    };
  }]);
<|endoftext|>


<commit_before>var WifiInfo= function() {
};
var exec = require('cordova/exec');
WifiInfo.prototype.get = function(success, fail) {
		execsuccess, success, 'WifiInfoPlugin', null, [] );
};

cordova.addConstructor(function() {

	if (!window.plugins) {
		window.plugins = {};
	}
	window.plugins.WifiInfo = new WifiInfo();
});
<commit_msg>Update WifiInfoPlugin.js<commit_after>var WifiInfo= function() {
};
var cordova = require('cordova'),
    exec = require('cordova/exec');
WifiInfo.prototype.get = function(success, fail) {
		exec(success, success, 'WifiInfoPlugin', null, [] );
};

cordova.addConstructor(function() {

	if (!window.plugins) {
		window.plugins = {};
	}
	window.plugins.WifiInfo = new WifiInfo();
});
<|endoftext|>


<commit_before>import { startRelease } from './releaseHelpers';

const packageNames = [
  'ringcentral-integration',
  'ringcentral-widgets',
  '@ringcentral-integration/i18n',
  '@ringcentral-integration/locale-loader',
  '@ringcentral-integration/phone-number',
  '@ringcentral-integration/glip-widgets',
];
const releaseBranchNames = [
  'commons-release',
  'widgets-release',
  'i18n-release',
  'locale-loader-release',
  'phone-number-release',
  'glip-widgets-release',
];

const args = process.argv.slice(2);
const packageName = args[0];
if (!packageNames.includes(packageName)) {
  console.log('package name invalid!');
  return;
}
const releaseBranchName = args[1];
if (!releaseBranchNames.includes(releaseBranchName)) {
  console.log('releaseBranchName name invalid!');
  return;
}

startRelease(packageName, releaseBranchName);
<commit_msg>fix: can not return out of function with babel-node (#1592)<commit_after>import { startRelease } from './releaseHelpers';

const packageNames = [
  'ringcentral-integration',
  'ringcentral-widgets',
  '@ringcentral-integration/i18n',
  '@ringcentral-integration/locale-loader',
  '@ringcentral-integration/phone-number',
  '@ringcentral-integration/glip-widgets',
];
const releaseBranchNames = [
  'commons-release',
  'widgets-release',
  'i18n-release',
  'locale-loader-release',
  'phone-number-release',
  'glip-widgets-release',
];

const args = process.argv.slice(2);
const packageName = args[0];
if (!packageNames.includes(packageName)) {
  console.log('package name invalid!');
  process.exit(1);
}
const releaseBranchName = args[1];
if (!releaseBranchNames.includes(releaseBranchName)) {
  console.log('releaseBranchName name invalid!');
  process.exit(1);
}

startRelease(packageName, releaseBranchName);
<|endoftext|>


<commit_before>'use strict';

// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var test = require('tape-catch');

var ohm = require('..');
var errors = require('../src/errors');

// --------------------------------------------------------------------
// Helpers
// --------------------------------------------------------------------

function makeRuleWithBody(expr) {
  ohm.grammar('G { start = ' + expr + '}');
}

// --------------------------------------------------------------------
// Tests
// --------------------------------------------------------------------

test('non-string input', function(t) {
  var g = ohm.grammar('G { start = 5 }');

  var e = g.match(42);
  t.equal(e.failed(), true);
  t.equal(e.message, 'match failed at position 0');
  t.equal(e.getPos(), 0);
  t.end();
});

test('match failure', function(t) {
  var g = ohm.grammar('G { start = "a" "b" "c" "d" }');

  var e = g.match('ab');
  t.equal(e.failed(), true);
  t.equal(e.succeeded(), false);
  t.equal(e.message, [
    'Line 1, col 3:',
    '> 1 | ab',
    '        ^',
    "Expected 'c'"].join('\n'));
  t.equal(e.shortMessage, "Line 1, col 3: expected 'c'");
  t.equal(e.getPos(), 2);

  e = g.match('abcde');
  t.equal(e.failed(), true);
  t.equal(e.succeeded(), false);
  t.equal(e.message, [
    'Line 1, col 5:',
    '> 1 | abcde',
    '          ^',
    'Expected end of input'].join('\n'));
  t.equal(e.shortMessage, 'Line 1, col 5: expected end of input');
  t.equal(e.getPos(), 4);

  var m = g.match('abcd');
  t.equal(m.succeeded(), true, 'succeeded() is true for root CST node');
  t.equal(m.failed(), false, 'failed() is false for root CST node');

  t.end();
});

test('undeclared rules', function(t) {
  t.throws(function() { makeRuleWithBody('undeclaredRule'); }, errors.UndeclaredRule);

  try {
    makeRuleWithBody('undeclaredRule');
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, 'Rule undeclaredRule is not declared in grammar G');
  }

  t.end();
});

test('many expressions with nullable operands', function(t) {
  t.throws(function() { makeRuleWithBody('("a"*)*'); }, errors.ManyExprHasNullableOperand);
  t.throws(function() { makeRuleWithBody('("a"?)*'); }, errors.ManyExprHasNullableOperand);
  t.throws(function() { makeRuleWithBody('("a"*)+'); }, errors.ManyExprHasNullableOperand);
  t.throws(function() { makeRuleWithBody('("a"?)+'); }, errors.ManyExprHasNullableOperand);

  try {
    makeRuleWithBody('("a"?)*');
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, [
      'Line 1, col 14:',
      '> 1 | G { start = ("a"?)*}',
      '                   ^~~~',
      'Nullable expression "a"? is not allowed inside \'*\' (possible infinite loop)'].join('\n'));
  }

  try {
    makeRuleWithBody('("a"?)+');
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, [
      'Line 1, col 14:',
      '> 1 | G { start = ("a"?)+}',
      '                   ^~~~',
      'Nullable expression "a"? is not allowed inside \'+\' (possible infinite loop)'].join('\n'));
  }

  t.throws(
      function() { ohm.grammar('G { x = y+  y = undeclaredRule }'); },
      errors.UndeclaredRule,
      'undeclared rule prevents ManyExprHasNullableOperand check');

  t.end();
});

test('errors from makeGrammar()', function(t) {
  var source = 'G {}\nG2 <: G {}';
  try {
    ohm.grammar(source);
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, [
      'Line 2, col 1:',
      '  1 | G {}',
      '> 2 | G2 <: G {}',
      '      ^',
      'Found more than one grammar definition -- use ohm.grammars() instead.'].join('\n'));
  }
  t.throws(function() { ohm.grammar(''); }, /Missing grammar/);
  t.throws(function() { ohm.grammar(' \t\n'); }, /Missing grammar/);

  try {
    ohm.grammar('G {');
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, [
      'Failed to parse grammar:',
      'Line 1, col 4:',
      '> 1 | G {',
      '         ^',
      "Expected an identifier or '}'"].join('\n'));
  }

  t.end();
});

test('unrecognized escape sequences', function(t) {
  try {
    ohm.grammar('G { start = "hello\\$world" }');
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, [
      'Failed to parse grammar:',
      'Line 1, col 19:',
      '> 1 | G { start = "hello\\$world" }',
      '                        ^',
      'Expected an escape sequence, not \'\\\\\', or \'"\''].join('\n'));
  }
  t.end();
});
<commit_msg>added back pat's old tests cases for unrecognized escape esquences<commit_after>'use strict';

// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var test = require('tape-catch');

var ohm = require('..');
var errors = require('../src/errors');

// --------------------------------------------------------------------
// Helpers
// --------------------------------------------------------------------

function makeRuleWithBody(expr) {
  ohm.grammar('G { start = ' + expr + '}');
}

// --------------------------------------------------------------------
// Tests
// --------------------------------------------------------------------

test('non-string input', function(t) {
  var g = ohm.grammar('G { start = 5 }');

  var e = g.match(42);
  t.equal(e.failed(), true);
  t.equal(e.message, 'match failed at position 0');
  t.equal(e.getPos(), 0);
  t.end();
});

test('match failure', function(t) {
  var g = ohm.grammar('G { start = "a" "b" "c" "d" }');

  var e = g.match('ab');
  t.equal(e.failed(), true);
  t.equal(e.succeeded(), false);
  t.equal(e.message, [
    'Line 1, col 3:',
    '> 1 | ab',
    '        ^',
    "Expected 'c'"].join('\n'));
  t.equal(e.shortMessage, "Line 1, col 3: expected 'c'");
  t.equal(e.getPos(), 2);

  e = g.match('abcde');
  t.equal(e.failed(), true);
  t.equal(e.succeeded(), false);
  t.equal(e.message, [
    'Line 1, col 5:',
    '> 1 | abcde',
    '          ^',
    'Expected end of input'].join('\n'));
  t.equal(e.shortMessage, 'Line 1, col 5: expected end of input');
  t.equal(e.getPos(), 4);

  var m = g.match('abcd');
  t.equal(m.succeeded(), true, 'succeeded() is true for root CST node');
  t.equal(m.failed(), false, 'failed() is false for root CST node');

  t.end();
});

test('undeclared rules', function(t) {
  t.throws(function() { makeRuleWithBody('undeclaredRule'); }, errors.UndeclaredRule);

  try {
    makeRuleWithBody('undeclaredRule');
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, 'Rule undeclaredRule is not declared in grammar G');
  }

  t.end();
});

test('many expressions with nullable operands', function(t) {
  t.throws(function() { makeRuleWithBody('("a"*)*'); }, errors.ManyExprHasNullableOperand);
  t.throws(function() { makeRuleWithBody('("a"?)*'); }, errors.ManyExprHasNullableOperand);
  t.throws(function() { makeRuleWithBody('("a"*)+'); }, errors.ManyExprHasNullableOperand);
  t.throws(function() { makeRuleWithBody('("a"?)+'); }, errors.ManyExprHasNullableOperand);

  try {
    makeRuleWithBody('("a"?)*');
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, [
      'Line 1, col 14:',
      '> 1 | G { start = ("a"?)*}',
      '                   ^~~~',
      'Nullable expression "a"? is not allowed inside \'*\' (possible infinite loop)'].join('\n'));
  }

  try {
    makeRuleWithBody('("a"?)+');
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, [
      'Line 1, col 14:',
      '> 1 | G { start = ("a"?)+}',
      '                   ^~~~',
      'Nullable expression "a"? is not allowed inside \'+\' (possible infinite loop)'].join('\n'));
  }

  t.throws(
      function() { ohm.grammar('G { x = y+  y = undeclaredRule }'); },
      errors.UndeclaredRule,
      'undeclared rule prevents ManyExprHasNullableOperand check');

  t.end();
});

test('errors from makeGrammar()', function(t) {
  var source = 'G {}\nG2 <: G {}';
  try {
    ohm.grammar(source);
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, [
      'Line 2, col 1:',
      '  1 | G {}',
      '> 2 | G2 <: G {}',
      '      ^',
      'Found more than one grammar definition -- use ohm.grammars() instead.'].join('\n'));
  }
  t.throws(function() { ohm.grammar(''); }, /Missing grammar/);
  t.throws(function() { ohm.grammar(' \t\n'); }, /Missing grammar/);

  try {
    ohm.grammar('G {');
    t.fail('Expected an exception to be thrown');
  } catch (e) {
    t.equal(e.message, [
      'Failed to parse grammar:',
      'Line 1, col 4:',
      '> 1 | G {',
      '         ^',
      "Expected an identifier or '}'"].join('\n'));
  }

  t.end();
});

test('unrecognized escape sequences', function(t) {
  function testBadEscapeSequence(bes) {
    try {
      ohm.grammar('G { start = "hello' + bes + 'world" }');
      t.fail('Expected an exception to be thrown');
    } catch (e) {
      t.equal(e.message, [
        'Failed to parse grammar:',
        'Line 1, col 19:',
        '> 1 | G { start = "hello' + bes + 'world" }',
        '                        ^',
        'Expected an escape sequence, not \'\\\\\', or \'"\''].join('\n'));
    }
  }
  testBadEscapeSequence('\\$');
  testBadEscapeSequence('\\!');
  testBadEscapeSequence('\\w');
  t.end();
});
<|endoftext|>


<commit_before>'use strict'

// initialize Hoodie
var hoodie = new Hoodie();

// on ready calls all binds
$(function() {
  if (hoodie.account.username) {
    hoodie.store.find('settings', 'user-settings')
      .done(function(settings) {
        $('#username').append(settings.name || hoodie.account.username)
        $('h2.welcoming').append(settings.name || hoodie.account.username)
      })
      .fail(function() {
        $('#username').append(hoodie.account.username)
        $('h2.welcoming').append(hoodie.account.username)
        // console.log((!$('#main') && hoodie.account.username == undefined))
        // location.href = 'index.html';
      })
  }

 if($('#dashboard')) {
  animateDays({total: 240, left: 77},{total: 24, left: 17});
  }
  $('#logout').bind('click', signOutUsr);
  $('#sign-up').bind('submit', submitSignUp);
  $('#go-on-vacation').bind('click', result);
  $('.day-ani').bind('live', animateDays)
})

// animation of work/vac days in dashboard
function animateDays(vacDay, workDay) {
  var overlay = $('.day-ani')
  var factorWorkDays = factorForAni(workDay.total, workDay.left);
  var factorVacDays = factorForAni(vacDay.total, vacDay.left, workDay.total, workDay.left);

  $('#vac-days').animate({
    'border-width': (1.25 * factorVacDays)
  }, 1400, function() {
    $('#vac-days .overlay').append(vacDay.left + ' / ' + vacDay.total).fadeIn();
  });

  $('#work-days').animate({
    'border-width': (1.25 * factorWorkDays)
  }, 1400, function() {
    $('#work-days .overlay').append(workDay.left + ' / ' + workDay.total).fadeIn();
  });

 }

function factorForAni(total, left) {
  var factor = (-(left / total) * 100) + 100;
  return factor;
}

// sign-in on main page
var submitSignUp = function submitSignUp() {
  var usr = $('#email').val();
  var pwd = $('#pwd').val();

  hoodie.account.signIn(usr, pwd).done(function() {
    if (hoodie.account.username) {
      location.href = 'dashboard.html';
    }
  }).fail(function() {
    hoodie.account.signUp(usr, pwd, pwd)
      .done(function() {
        if (hoodie.account.username) {
          location.href = 'settings-init.html';
        }
      })
      .fail(function() {
        alert('Your credentials are wrong!');
      })
  })
  return false;
}

var signOutUsr = function signOutUsr() {
  hoodie.account.signOut().done(function() {
    location.href = 'index.html';
  })
}

var workDays = function workDays() {
  return {
    total: totalWorkDays(dates),
    left: leftWorkDays(dates).leftWorkDays
  };
}

var vecDays = function vecDays(settings) {
  return {
    total: settings.totalVecDays,
    left: settings.vecDays
  };
}

var buildUrl = function buildUrl(from, to) {
  var base = "http://justrelax.rrbone.io/booking/holiday?"

  var urlReq = base + "from=" + from + "&to=" + to;

  return hoodie.store.find("settings", "user-settings")
    .then(function(s) {
      urlReq += "&location=" + s.favDestination;

      var adults = parseInt(s.adults, 10);
      var kids = parseInt(s.kids, 10);
      var budget = parseInt(s.budget, 10);

      if (adults > 0) {
        urlReq += "&adults=" + adults;
      }
      if (kids > 0) {
        urlReq += "&kids=" + kids;
      }
      if (budget > 0) {
        urlReq += "&budget=" + budget;
      }

      return urlReq;
    })
}

function deserializeDaterange(str) {
  var start = moment(str.split(' - ')[0])
  var end = moment(str.split(' - ')[1])

  return {
    from: start.format('YYYY-MM-DD'),
    end: end.format('YYYY-MM-DD'),
    days: end.diff(start, 'days')
  }
}

// return results
var result = function result(event) {
  var e = event.target;
  hoodie.store.find("settings", "user-settings")
    .then(function(s) {
      var blockedVac = s['daterange-vacation']
      var blockedWork = s['daterange-work']
      blockedVac = blockedVac || []
      blockedWork = blockedWork || []
      blockedVac = blockedVac.map(deserializeDaterange)
      blockedWork = blockedWork.map(deserializeDaterange)

      var engine = recommender({
        dates: dates,
        lastVacation: moment(),
        blockedWork: blockedVac,
        blockedVac: blockedWork
      });

      var scores = engine.scores()
      var recommends = engine.blocks(scores);

      for (var i = 1; i <= 3; i++) {
        (function(i) {
          var from = recommends[i - 1].start.date;
          var to = recommends[i - 1].end.date;
          buildUrl(from, to).then(function(urlReq) {
            $.ajax({
              url: urlReq
            })
              .done(function(data) {
                var dom = $(".output");
                var res = data.results;

                var f = moment(from).format("DD.MM.YYYY");
                var t = moment(to).format("DD.MM.YYYY");
                $(".output-option-" + i).text(
                  "Option " + i + ": " + f + " - " + t
                )

                $(".output").fadeIn().removeClass('hide');

                res.slice(0, 3).forEach(function(obj) {
                  var li = '
' + obj.price + ' € / p. n. & p.
 Book now!
' + obj.name + '
' + obj.city + '

'
                  $(".output-" + i).append(li).fadeIn().removeClass('hide');
                  ;
                })
              });
          });
        })(i);
      }
      $('#dashboard').fadeOut().addClass('hide');
    })
}
<commit_msg>Fix main<commit_after>'use strict'

// initialize Hoodie
var hoodie = new Hoodie();

// on ready calls all binds
$(function() {
  if (hoodie.account.username) {
    hoodie.store.find('settings', 'user-settings')
      .done(function(settings) {
        $('#username').append(settings.name || hoodie.account.username)
        $('h2.welcoming').append(settings.name || hoodie.account.username)
      })
      .fail(function() {
        $('#username').append(hoodie.account.username)
        $('h2.welcoming').append(hoodie.account.username)
        // console.log((!$('#main') && hoodie.account.username == undefined))
        // location.href = 'index.html';
      })
  }

  if($('#dashboard')) {
    hoodie.store.find('settings', 'user-settings')
    .done(function(settings) {
      animateDays(vacDays(settings), workDays());
    });
  }
  $('#logout').bind('click', signOutUsr);
  $('#sign-up').bind('submit', submitSignUp);
  $('#go-on-vacation').bind('click', result);
})

// animation of work/vac days in dashboard
function animateDays(vacDay, workDay) {
  var overlay = $('.day-ani')
  var factorWorkDays = factorForAni(workDay.total, workDay.left);
  var factorVacDays = factorForAni(vacDay.total, vacDay.left, workDay.total, workDay.left);

  $('#vac-days').animate({
    'border-width': (1.25 * factorVacDays)
  }, 1400, function() {
    $('#vac-days .overlay').append(vacDay.left + ' / ' + vacDay.total).fadeIn();
  });

  $('#work-days').animate({
    'border-width': (1.25 * factorWorkDays)
  }, 1400, function() {
    $('#work-days .overlay').append(workDay.left + ' / ' + workDay.total).fadeIn();
  });

 }

function factorForAni(total, left) {
  var factor = (-(left / total) * 100) + 100;
  return factor;
}

// sign-in on main page
var submitSignUp = function submitSignUp() {
  var usr = $('#email').val();
  var pwd = $('#pwd').val();

  hoodie.account.signIn(usr, pwd).done(function() {
    if (hoodie.account.username) {
      location.href = 'dashboard.html';
    }
  }).fail(function() {
    hoodie.account.signUp(usr, pwd, pwd)
      .done(function() {
        if (hoodie.account.username) {
          location.href = 'settings-init.html';
        }
      })
      .fail(function() {
        alert('Your credentials are wrong!');
      })
  })
  return false;
}

var signOutUsr = function signOutUsr() {
  hoodie.account.signOut().done(function() {
    location.href = 'index.html';
  })
}

var workDays = function workDays() {
  return {
    total: totalWorkDays(dates),
    left: leftWorkDays(dates).leftWorkDays
  };
}

var vacDays = function vacDays(settings) {
  return {
    total: parseInt(settings.totalVacDays || 0, 10),
    left:  parseInt(settings.vacDays || 0, 10)
  };
}

var buildUrl = function buildUrl(from, to) {
  var base = "http://justrelax.rrbone.io/booking/holiday?"

  var urlReq = base + "from=" + from + "&to=" + to;

  return hoodie.store.find("settings", "user-settings")
    .then(function(s) {
      urlReq += "&location=" + s.favDestination;

      var adults = parseInt(s.adults, 10);
      var kids = parseInt(s.kids, 10);
      var budget = parseInt(s.budget, 10);

      if (adults > 0) {
        urlReq += "&adults=" + adults;
      }
      if (kids > 0) {
        urlReq += "&kids=" + kids;
      }
      if (budget > 0) {
        urlReq += "&budget=" + budget;
      }

      return urlReq;
    })
}

function deserializeDaterange(str) {
  var start = moment(str.split(' - ')[0])
  var end = moment(str.split(' - ')[1])

  return {
    from: start.format('YYYY-MM-DD'),
    end: end.format('YYYY-MM-DD'),
    days: end.diff(start, 'days')
  }
}

// return results
var result = function result(event) {
  var e = event.target;
  hoodie.store.find("settings", "user-settings")
    .then(function(s) {
      var blockedVac = s['daterange-vacation']
      var blockedWork = s['daterange-work']
      blockedVac = blockedVac || []
      blockedWork = blockedWork || []
      blockedVac = blockedVac.map(deserializeDaterange)
      blockedWork = blockedWork.map(deserializeDaterange)

      var engine = recommender({
        dates: dates,
        lastVacation: moment(),
        blockedWork: blockedVac,
        blockedVac: blockedWork
      });

      var scores = engine.scores()
      var recommends = engine.blocks(scores);

      for (var i = 1; i <= 3; i++) {
        (function(i) {
          var from = recommends[i - 1].start.date;
          var to = recommends[i - 1].end.date;
          buildUrl(from, to).then(function(urlReq) {
            $.ajax({
              url: urlReq
            })
              .done(function(data) {
                var dom = $(".output");
                var res = data.results;

                var f = moment(from).format("DD.MM.YYYY");
                var t = moment(to).format("DD.MM.YYYY");
                $(".output-option-" + i).text(
                  "Option " + i + ": " + f + " - " + t
                )

                $(".output").fadeIn().removeClass('hide');

                res.slice(0, 3).forEach(function(obj) {
                  var li = '
' + obj.price + ' € / p. n. & p.
 Book now!
' + obj.name + '
' + obj.city + '

'
                  $(".output-" + i).append(li).fadeIn().removeClass('hide');
                  ;
                })
              });
          });
        })(i);
      }
      $('#dashboard').fadeOut().addClass('hide');
    })
}
<|endoftext|>


<commit_before>var fs = require('fs'),
    assert = require('chai').assert,
    sinon = require('sinon'),
    mktemp = require('../');

suite('mktempのテスト', function() {

  suiteSetup(function() {
    sinon.stub(fs, 'open').callsArgWith(3, null);
    sinon.stub(fs, 'close').callsArgWith(1, null);
    sinon.stub(fs, 'openSync');
    sinon.stub(fs, 'closeSync');
    sinon.stub(fs, 'mkdir').callsArgWith(2, null);
    sinon.stub(fs, 'mkdirSync');
  });

  suiteTeardown(function() {
    fs.open.restore();
    fs.openSync.restore();
    fs.close.restore();
    fs.closeSync.restore();
    fs.mkdir.restore();
    fs.mkdirSync.restore();
  });

  test('createFileのテスト', function(done) {
    mktemp.createFile('file-XXXXX', function(err, path) {
      assert.isTrue(/^file-[\da-zA-Z]{5}$/.test(path),
          'create file of random filename');
      assert.isFalse(/^file-X{5}$/.test(path),
          'path is replaced to random filename');
      done();
    });
  });

  test('createFileSyncのテスト', function() {
    var path = mktemp.createFileSync('file-XXX');

    assert.isTrue(/^file-[\da-zA-Z]{3}$/.test(path),
        'create file of random filename');
    assert.isFalse(/^file-X{3}$/.test(path),
        'path is replaced to random filename');
  });

  test('createDirのテスト', function(done) {
    mktemp.createDir('dir-X', function(err, path) {
      assert.isTrue(/^dir-[\da-zA-Z]$/.test(path),
          'create dir of random dirname');
      assert.isFalse(/^dir-X$/.test(path),
          'path is replaced to random dirname');
      done();
    });
  });

  test('createDirSyncのテスト', function() {
    var path = mktemp.createDirSync('dir-XXXXXXX');

    assert.isTrue(/^dir-[\da-zA-Z]{7}$/.test(path),
        'create dir of random dirname');
    assert.isFalse(/^dir-X{7}$/.test(path),
        'path is replaced to random dirname');
  });

});
<commit_msg>rewrote unit test of mktemp<commit_after>var fs = require('fs'),
    assert = require('chai').assert,
    sinon = require('sinon'),
    mktemp = require('../');

suite('mktemp', function() {

  suiteSetup(function() {
    sinon.stub(fs, 'open').callsArgWith(3, null);
    sinon.stub(fs, 'close').callsArgWith(1, null);
    sinon.stub(fs, 'openSync');
    sinon.stub(fs, 'closeSync');
    sinon.stub(fs, 'mkdir').callsArgWith(2, null);
    sinon.stub(fs, 'mkdirSync');
  });

  suiteTeardown(function() {
    fs.open.restore();
    fs.openSync.restore();
    fs.close.restore();
    fs.closeSync.restore();
    fs.mkdir.restore();
    fs.mkdirSync.restore();
  });

  suite('#createFile()', function() {

    test('generate random filename', function(done) {
      mktemp.createFile('file-XXXXX', function(err, path) {
        assert.isTrue(
            /^file-[\da-zA-Z]{5}$/.test(path),
            'path should be match in /^file-[\\da-zA-Z]{5}$/');
        assert.notStrictEqual(
            path,
            'file-XXXXX',
            'path should not be "file-XXXXX"');
        done();
      });
    });

  });

  suite('#createFileSync()', function() {

    test('generate random filename', function() {
      var path = mktemp.createFileSync('file-XXX');

      assert.isTrue(
          /^file-[\da-zA-Z]{3}$/.test(path),
          'path should be match in /^file-[\\da-zA-Z]{3}$/');
      assert.notStrictEqual(
          path,
          'file-XXX',
          'path should not be "file-XXX"');
    });

  });

  suite('#createDir()', function() {

    test('generate random dirname', function(done) {
      mktemp.createDir('dir-XXXXX', function(err, path) {
        assert.isTrue(
            /^dir-[\da-zA-Z]{5}$/.test(path),
            'path should be match in /^dir-[\\da-zA-Z]{5}$/');
        assert.notStrictEqual(
            path,
            'dir-XXXXX',
            'path should not be "dir-XXXXX"');
        done();
      });
    });

  });

  suite('#createDirSync()', function() {

    test('generate random dirname', function() {
      var path = mktemp.createDirSync('dir-XXX');

      assert.isTrue(
          /^dir-[\da-zA-Z]{3}$/.test(path),
          'path should be match in /^dir-[\\da-zA-Z]{3}$/');
      assert.notStrictEqual(
          path,
          'dir-XXX',
          'path should not be "dir-XXX"');
    });

  });

});
<|endoftext|>


<commit_before>const THREE = require('three');
global.THREE = THREE;
const createTextGeometry = require('three-bmfont-text');
const createMSDFShader = require('./createMSDFShader');
const fontPreloader = require('./fontPreloader');

let scene, camera, renderer, mesh;

function init () {
  const canvas = document.createElement('canvas');
  document.body.appendChild(canvas);

  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.z = 250;

  renderer = new THREE.WebGLRenderer({canvas});
  renderer.setClearColor(0xffffff);
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate () {
  render();
  window.requestAnimationFrame(animate);
}

function render () {
  renderer.render(scene, camera);
}

init();
animate();

fontPreloader((err, data) => {
  if (err) console.log(err);
  const material = new THREE.RawShaderMaterial(createMSDFShader({
    map: data.texture,
    side: THREE.DoubleSide,
    transparent: true,
    depthTest: false,
    depthWrite: false,
    color: '#000000'
  }));
  var geometry = createTextGeometry({
    font: data.font
  });
  geometry.update('Sweet text, bro!');
  mesh = new THREE.Mesh(geometry, material);
  mesh.rotation.x = Math.PI;
  mesh.position.x = -140;
  scene.add(mesh);
});
<commit_msg>fix up render test a bit with sizing<commit_after>const THREE = require('three');
global.THREE = THREE;
const createTextGeometry = require('three-bmfont-text');
const createMSDFShader = require('./createMSDFShader');
const fontPreloader = require('./fontPreloader');

let scene, camera, renderer, mesh;

function init () {
  const canvas = document.createElement('canvas');
  canvas.style.display = 'block';
  document.body.style.margin = '0';
  document.body.style.overfow = 'hidden';
  document.body.appendChild(canvas);

  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.z = 250;

  renderer = new THREE.WebGLRenderer({canvas});
  renderer.setClearColor(0xffffff);
  renderer.setPixelRatio(window.devicePixelRatio);
  window.addEventListener('resize', resize);
  resize();
}

function resize () {
  renderer.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
}

function animate () {
  render();
  window.requestAnimationFrame(animate);
}

function render () {
  renderer.render(scene, camera);
}

init();
animate();

fontPreloader((err, data) => {
  if (err) console.log(err);
  const material = new THREE.RawShaderMaterial(createMSDFShader({
    map: data.texture,
    side: THREE.DoubleSide,
    transparent: true,
    depthTest: false,
    depthWrite: false,
    color: '#000000'
  }));
  var geometry = createTextGeometry({
    font: data.font,
    width: 300
  });
  geometry.update('The quick brown fox jumped over the lazy dogs.');
  mesh = new THREE.Mesh(geometry, material);
  mesh.rotation.x = Math.PI;
  mesh.position.x = -160;
  mesh.position.y = -10;
  scene.add(mesh);
});
<|endoftext|>


<commit_before>// Not supported objects/types:
//  undefined, null, NaN, functions (can be .toStringed)
var testSubjects = {
  // should not even work...
  'number': {
    subject: 7,
    result: 7
  },
  // should (de)serialize correctly
  'boolean': {
    subject: false,
    result: false
  },
  // no support for functions
  // could be undergone toString first
  // but... who the hell uses localStorage
  // to store functions?
  /*'function': {
    subject: function(){},
    result: undefined
  },*/
  'object': {
    subject: {test: 'object', sup: 'man'},
    result: {test: 'object', sup: 'man'}
  },
  'basic array of numbers': {
    subject: [1, 2, 3],
    result: [1, 2, 3]
  },
  'array of multiple types': {
    subject: [1, 'h', true, {test: 'ing'}],
    result: [1, 'h', true, {test: 'ing'}]
  }
};

describe('#set()', function() {
  it('should be asynchronous', function(done) {
    storey.set('hello', 'world', function() {
      done();
    });
  });
  it('should be set', function() {
    localStorage.getItem('hello').should.equal('world');
  });
});

// reuse 'hello'=>'world' from before
describe('#get()', function() {
  it('should be able to get', function(done) {
    storey.get('hello', function(value) {
      value.should.equal('world');
      done();
    });
  });
});

// now remove 'hello'=>'world'
describe('#remove()', function() {
  it('should be able to remove', function(done) {
    storey.remove('hello', function() {
      storey.get('hello', function(value) {
        value.should.not.be.ok;
      });
      done();
    });
  });
});

// now that basic functions are nailed,
// do a variation of types inserted and extracted
describe('testing types (async)', function() {
  var types = Object.keys(testSubjects);
  for (var i = 0; i < types.length; i++) {
    // for localization of i in for loop
    // if this is not done, async functions
    // will just use last index in loop
    (function(i) {
      var typeName = types[i];
      var type = testSubjects[typeName];
      it('should set ' + typeName, function(done) {
        storey.set(typeName, type.subject, function() {
          done();
        });
      });
      it('should get ' + typeName, function(done) {
        storey.get(typeName, function(value) {
          value.should.eql(type.result);
          /*
          if (typeof value === 'object') value.should.eql(type.result);
          else value.should.equal(type.result);*/
          done();
        });
      });
    })(i);
  }
});

// lame synchronous functions
describe('testing types (sync)', function() {
  var types = Object.keys(testSubjects);
  for (var i = 0; i < types.length; i++) {
    (function(i) {
      var typeName = types[i];
      var type = testSubjects[typeName];
      var value;
      it('should set ' + typeName, function() {
        storey.setSync(typeName, type.subject);
      });
      it('should get ' + typeName, function() {
        value = storey.getSync(typeName);
        // use eql to check for contents
        value.should.eql(type.result);
      });
  })(i);
  }
});

// types are nailed!
// moving on to multi functions
describe('#setMulti()', function() {
  it('should set multiple', function(done) {
    storey.setMulti({
      'this': 'is',
      'amazing': 'right',
      'oh': 'yeah'
    }, function(){
      done();
    });
  });
  it('should be set correctly', function(){
    // just use sync functions...
    // why the hassle
    var is = storey.getSync('this');
    var right = storey.getSync('amazing');
    var yeah = storey.getSync('oh');
    is.should.equal('is');
    right.should.equal('right');
    yeah.should.equal('yeah');
  });
});

describe('#getMulti()', function() {
  it('should be in right order', function(done) {
    // shuffled their order?
    storey.getMulti(['amazing', 'this', 'oh'], function(values) {
      // .eql matches contents
      values.should.eql(['right', 'is', 'yeah']);
      done();
    });
  });
});

describe('#removeMulti()', function() {
  it('should remove perfectly', function(done) {
    var keys = ['amazing', 'this', 'oh'];
    storey.removeMulti(keys, function() {
      // getMulti passed test and usable
      storey.getMulti(keys, function(values) {
        values.should.eql([undefined, undefined, undefined]);
      });
      done();
    });
  });
});

describe('Not in storage', function() {
  it('should return null', function(done) {
    storey.get('some unknown key', function(value) {
      (value === null).should.be.true;
    });
    done();
  });
});

describe('#clear()', function() {
  it('should clear perfectly', function(done) {
    storey.clear();
    done();
  });
  // this clears out storage
  // and all is left for 'null' to be returned
  it('should only return null', function(done) {
    var types = Object.keys(testSubjects);
    for (var i = 0; i < types.length; i++) {
      (function(i) {
        var type = types[i];
        storey.get(type, function(value) {
          (value === null).should.be.true;
        });
      })(i);
    }
    done();
  });
});

// for callbacks, this check is sufficient:
// if (typeof callback === 'function') callback();

describe('#forEach()', function() {
  storage.set()
});
<commit_msg>Tested and fixed major bugs<commit_after>// Not supported objects/types:
//  undefined, null, NaN, functions (can be .toStringed)
var testSubjects = {
  // should not even work...
  'number': {
    subject: 7,
    result: 7
  },
  // should (de)serialize correctly
  'boolean': {
    subject: false,
    result: false
  },
  // no support for functions
  // could be undergone toString first
  // but... who the hell uses localStorage
  // to store functions?
  /*'function': {
    subject: function(){},
    result: undefined
  },*/
  'object': {
    subject: {test: 'object', sup: 'man'},
    result: {test: 'object', sup: 'man'}
  },
  'basic array of numbers': {
    subject: [1, 2, 3],
    result: [1, 2, 3]
  },
  'array of multiple types': {
    subject: [1, 'h', true, {test: 'ing'}],
    result: [1, 'h', true, {test: 'ing'}]
  }
};

describe('#set()', function() {
  it('should be asynchronous', function(done) {
    storey.set('hello', 'world', function() {
      done();
    });
  });
  it('should be set', function() {
    localStorage.getItem('hello').should.equal('world');
  });
});

// reuse 'hello'=>'world' from before
describe('#get()', function() {
  it('should be able to get', function(done) {
    storey.get('hello', function(value) {
      value.should.equal('world');
      done();
    });
  });
});

// now remove 'hello'=>'world'
describe('#remove()', function() {
  it('should be able to remove', function(done) {
    storey.remove('hello', function() {
      storey.get('hello', function(value) {
        value.should.not.be.ok;
      });
      done();
    });
  });
});

// now that basic functions are nailed,
// do a variation of types inserted and extracted
describe('testing types (async)', function() {
  var types = Object.keys(testSubjects);
  for (var i = 0; i < types.length; i++) {
    // for localization of i in for loop
    // if this is not done, async functions
    // will just use last index in loop
    (function(i) {
      var typeName = types[i];
      var type = testSubjects[typeName];
      it('should set ' + typeName, function(done) {
        storey.set(typeName, type.subject, function() {
          done();
        });
      });
      it('should get ' + typeName, function(done) {
        storey.get(typeName, function(value) {
          value.should.eql(type.result);
          /*
          if (typeof value === 'object') value.should.eql(type.result);
          else value.should.equal(type.result);*/
          done();
        });
      });
    })(i);
  }
});

// lame synchronous functions
describe('testing types (sync)', function() {
  var types = Object.keys(testSubjects);
  for (var i = 0; i < types.length; i++) {
    (function(i) {
      var typeName = types[i];
      var type = testSubjects[typeName];
      var value;
      it('should set ' + typeName, function() {
        storey.setSync(typeName, type.subject);
      });
      it('should get ' + typeName, function() {
        value = storey.getSync(typeName);
        // use eql to check for contents
        value.should.eql(type.result);
      });
  })(i);
  }
});

// types are nailed!
// moving on to multi functions
describe('#setMulti()', function() {
  it('should set multiple', function(done) {
    storey.setMulti({
      'this': 'is',
      'amazing': 'right',
      'oh': 'yeah'
    }, function(){
      done();
    });
  });
  it('should be set correctly', function(){
    // just use sync functions...
    // why the hassle
    var is = storey.getSync('this');
    var right = storey.getSync('amazing');
    var yeah = storey.getSync('oh');
    is.should.equal('is');
    right.should.equal('right');
    yeah.should.equal('yeah');
  });
});

describe('#getMulti()', function() {
  it('should be in right order', function(done) {
    // shuffled their order?
    storey.getMulti(['amazing', 'this', 'oh'], function(values) {
      // .eql matches contents
      values.should.eql(['right', 'is', 'yeah']);
      done();
    });
  });
});

describe('#removeMulti()', function() {
  it('should remove perfectly', function(done) {
    var keys = ['amazing', 'this', 'oh'];
    storey.removeMulti(keys, function() {
      // getMulti passed test and usable
      storey.getMulti(keys, function(values) {
        values.should.eql([undefined, undefined, undefined]);
      });
      done();
    });
  });
});

describe('Not in storage', function() {
  it('should return null', function(done) {
    storey.get('some unknown key', function(value) {
      (value === null).should.be.true;
      done();
    });
  });
});

describe('#clear()', function() {
  it('should clear perfectly', function(done) {
    storey.clear(function() {
      done();
    });
  });
  // this clears out storage
  // and all is left for 'null' to be returned
  it('should only return null', function(done) {
    var types = Object.keys(testSubjects);
    for (var i = 0; i < types.length; i++) {
      (function(i) {
        var type = types[i];
        storey.get(type, function(value) {
          (value === null).should.be.true;
          done();
        });
      })(i);
    }
  });
});

// for callbacks, this check is sufficient:
// if (typeof callback === 'function') callback();

// storage is clear, set new items
describe('#forEach()', function() {
  it('should do function on each item', function(done) {
    storey.setMulti({
      a: 1,
      b: 2,
      c: 3
    });
    storey.forEach(function(value) {
      done();
      return value * 2;
    });
    storey.getMulti(['a', 'b', 'c'], function(values) {
      values[0].should.be.equal(2);
      values[1].should.be.equal(4);
      values[2].should.be.equal(6);
    });
  });
});

// lame tests for size
describe('#left()', function() {
  it('should be 500 MB - storey.size()', function() {
    var MAX_SIZE = 1024 * 1024 * 5;
    storey.left().should.be.equal(MAX_SIZE - storey.size());
  });
});
<|endoftext|>


<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

/*
    ENABLE THIS WHEN ADAPTER RUNS IN DEAMON MODE TO CHECK THAT IT HAS STARTED SUCCESSFULLY
*/
    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });
/**/

/*
    PUT YOUR OWN TESTS HERE USING
    it('Testname', function ( done) {
        ...
    });

    You can also use "sendTo" method to send messages to the started adapter
*/

    it('tvspielfilm: feeds to be parsed', function (done) {
        this.timeout(20000);
        states.getState('tvspielfilm.0.json.heute2200', function (err, fileName) {
            expect(err).to.be.not.ok;
            expect(fileName).to.be.ok;
            expect(fileName.ack).to.be.true;
            states.getState('tvspielfilm.0.json.filme', function (err, fileName) {
                expect(err).to.be.not.ok;
                expect(fileName).to.be.ok;
                expect(fileName.ack).to.be.true;
                states.getState('tvspielfilm.0.json.heute2015', function (err, fileName) {
                    expect(err).to.be.not.ok;
                    expect(fileName).to.be.ok;
                    expect(fileName.ack).to.be.true;
                    states.getState('tvspielfilm.0.json.jetzt', function (err, fileName) {
                        expect(err).to.be.not.ok;
                        expect(fileName).to.be.ok;
                        expect(fileName.ack).to.be.true;
                        done();
                    });
                });
            });
        });
    });

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<commit_msg>Update testAdapter.js<commit_after>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

/*
    ENABLE THIS WHEN ADAPTER RUNS IN DEAMON MODE TO CHECK THAT IT HAS STARTED SUCCESSFULLY
*/
    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });
/**/

/*
    PUT YOUR OWN TESTS HERE USING
    it('Testname', function ( done) {
        ...
    });

    You can also use "sendTo" method to send messages to the started adapter
*/
    it('rtv: feeds to be parsed', function (done) {
        this.timeout(20000);
        states.getState('rtv.0.json.heute2200', function (err, fileName) {
            expect(err).to.be.not.ok;
            expect(fileName).to.be.ok;
            expect(fileName.ack).to.be.true;
            states.getState('rtv.0.json.tipps', function (err, fileName) {
                expect(err).to.be.not.ok;
                expect(fileName).to.be.ok;
                expect(fileName.ack).to.be.true;
                states.getState('rtv.0.json.heute2015', function (err, fileName) {
                    expect(err).to.be.not.ok;
                    expect(fileName).to.be.ok;
                    expect(fileName.ack).to.be.true;
                    states.getState('rtv.0.json.jetzt', function (err, fileName) {
                        expect(err).to.be.not.ok;
                        expect(fileName).to.be.ok;
                        expect(fileName.ack).to.be.true;
                        done();
                    });
                });
            });
        });
    });

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<|endoftext|>