<commit_before>
var System, Loader, Module, tests, test;

var testCnt = 0, passed = 0, failed = 0;
var test = function(name, initialize) {
  if (typeof initialize != 'function') {
    var val = initialize;
    var exp = arguments[2];
    initialize = function(assert) {
      assert(val, exp);
    }
  }
  var testId = testCnt++;
  tests.addTest(testId, name);
  function assert(value, expected) {
    if (value != expected)
      return 'Got "' + value + '" instead of "' + expected + '"';
  }
  initialize(function(value, expected) {
    var failure;
    if (value instanceof Array) {
      for (var i = 0; i < arguments.length; i++)
        failure = failure || assert(arguments[i][0], arguments[i][1]);
    }
    else
      failure = assert(value, expected);
    if (failure)
      failed++;
    else
      passed++;
    tests.completeTest(testId, name, failure, { passed: passed, failed: failed, total: testCnt });
  });
}

if (typeof window != 'undefined') {
  // browser
  document.body.innerHTML = "

Summary
";
  tests = {
    addTest: function(id, name) {
      var p = document.createElement('tr');
      p.innerHTML = '' + name + '		'
      document.querySelector('.test tbody').appendChild(p);
    },
    completeTest: function(id, name, failure, summary) {
      document.querySelector('.test .result-' + id).innerHTML = !failure ? 'Passed' : 'Failed: ' + failure;
      document.querySelector('.summary').innerHTML = summary.passed + '/' + summary.total + ' tests passed';
    }
  }
  window.test = test;
  window.runTests = runTests;
}
else {
  // nodejs
  var ml = require('../lib/es6-module-loader');

  System = ml.System;
  Loader = ml.Loader;
  Module = ml.Module;

  tests = {
    addTest: function(id, name) {},
    completeTest: function(id, name, failure, summary) {
      console.log(name + ': ' + (!failure ? 'Passed' : 'Failed: ' + result.failedAssertion));
      console.log(summary.passed + '/' + summary.total + ' passed. ');
    },
  };

  runTests();
}

function runTests() {
  // Normalize tests - identical to https://github.com/google/traceur-compiler/blob/master/test/unit/runtime/System.js

  var oldBaseURL = System.baseURL;
  System.baseURL = 'http://example.org/a/b.html';

  test('Normalize - No Referer', System.normalize('d/e/f'), 'd/e/f');
  // test('Normalize - Below baseURL', System.normalize('../e/f'), '../e/f');

  var refererName = 'dir/file';
  test('Normalize - Relative paths', System.normalize('./d/e/f', refererName), 'dir/d/e/f');
  test('Normalize - Relative paths', System.normalize('../e/f', refererName), 'e/f');

  test('Normalize - name undefined', function(assert) {
    try {
      System.normalize(undefined, refererName);
    }
    catch(e) {
      assert(e.message, 'Module name must be a string');
    }
  });

  test('Normalize - embedded ..', function(assert) {
    try {
      System.normalize('a/b/../c');
    }
    catch(e) {
      assert(e.message, 'Illegal module name"a/b/../c"');
    }
  });
  test('Normalize - embedded ..', function(assert) {
    try {
      System.normalize('a/../b', refererName);
    }
    catch(e) {
      assert(e.message, 'Illegal module name"a/../b"');
    }
  });
  test('Normalize - embedded ..', function(assert) {
    try {
      System.normalize('a/b/../c', refererName);
    }
    catch(e) {
      assert(e.message, 'Illegal module name"a/b/../c"');
    }
  });

  // test('Normalize - below referer', System.normalize('../../e/f', refererName), '../e/f');

  test('Normalize - backwards compat', System.normalize('./a.js'), 'a.js');

  test('Normalize - URL', function(assert) {
    try {
      System.normalize('http://example.org/a/b.html');
    }
    catch(e) {
      assert();
    }
  });

  System.baseURL = 'http://example.org/a/';

  test('Locate', System.locate({ name: '@abc/def' }), 'http://example.org/a/@abc/def.js');
  test('Locate', System.locate({ name: 'abc/def' }), 'http://example.org/a/abc/def.js');

  // paths
  System.paths['path/*'] = '/test/*.js';
  test('Locate paths', System.locate({ name: 'path/test' }), 'http://example.org/test/test.js');

  System.baseURL = oldBaseURL;

  // More Normalize tests

  test('Normalize test 1', function(assert) {
    assert(System.normalize('./a/b', 'c'), 'a/b');
  });
  test('Normalize test 2', function(assert) {
    assert(System.normalize('./a/b', 'c/d'), 'c/a/b');
  });
  test('Normalize test 3', function(assert) {
    assert(System.normalize('./a/b', '../c/d'), '../c/a/b');
  });
  test('Normalize test 4', function(assert) {
    assert(System.normalize('./a/b', '../c/d'), '../c/a/b');
  });
  test('Normalize test 5', function(assert) {
    assert(System.normalize('../a/b', '../../c/d'), '../../a/b');
  });

  test('Import a script', function(assert) {
    System.import('syntax/script').then(function(m) {
      assert(!!m, true);
    });
  });

  test('Import ES6', function(assert) {
    System.import('syntax/es6').then(function(m) {
      assert(m.p, 'p');
    });
  });

  test('Import ES6 with dep', function(assert) {
    System.import('syntax/es6-withdep').then(function(m) {
      assert(m.p, 'p');
    }, function(e) {
      console.log(e);
    });
  });

  test('Direct import without bindings', function(assert) {
    System.import('syntax/direct').then(function(m) {
      console.log('got direct');
      assert(!!m, true);
    });
  });

  test('Load order test: A', function(assert) {
    System.import('loads/a').then(function(m) {
      assert(
        [m.a, 'a'],
        [m.b, 'b']
      );
    });
  });

  test('Load order test: C', function(assert) {
    System.import('loads/c').then(function(m) {
      assert(
        [m.c, 'c'],
        [m.a, 'a'],
        [m.b, 'b']
      );
    });
  });

  test('Load order test: S', function(assert) {
    System.import('loads/s').then(function(m) {
      assert(
        [m.s, 's'],
        [m.c, 'c'],
        [m.a, 'a'],
        [m.b, 'b']
      );
    });
  });

  test('Load order test: _a', function(assert) {
    System.import('loads/_a').then(function(m) {
      assert(
        [m.b, 'b'],
        [m.d, 'd'],
        [m.g, 'g'],
        [m.a, 'a']
      );
    })
  });
  test('Load order test: _e', function(assert) {
    System.import('loads/_e').then(function(m) {
      assert(
        [m.c, 'c'],
        [m.e, 'e']
      );
    })
  });
  test('Load order test: _f', function(assert) {
    System.import('loads/_f').then(function(m) {
      assert(
        [m.g, 'g'],
        [m.f, 'f']
      );
    })
  });
  test('Load order test: _h', function(assert) {
    System.import('loads/_h').then(function(m) {
      assert(
        [m.i, 'i'],
        [m.a, 'a'],
        [m.h, 'h']
      );
    })
  });

  test('Export Syntax', function(assert) {
    System.import('syntax/export').then(function(m) {
      assert(
        [m.p, 5],
        [typeof m.foo, 'function'],
        [typeof m.q, 'object'],
        [m.default.name, 'bar'],
        [m.s, 4],
        [m.t, 4],
        [typeof m.m, 'object']
      );
    });
  });

  test('Re-export', function(assert) {
    System.import('syntax/reexport1').then(function(m) {
      assert(m.p, 5);
    });
  });

  test('Re-export with new name', function(assert) {
    System.import('syntax/reexport2').then(function(m) {
      assert(
        [m.q, 4],
        [m.z, 5]
      );
    }).catch(function(err) {
      console.log('error');
      console.log(err);
    });
  });

  test('Import Syntax', function(assert) {
    System.import('syntax/import').then(function(m) {
      assert(
        [m.a.name, 'bar'],
        [m.b, 4],
        [m.c, 5],
        [m.d, 4],
        [typeof m.q.foo, 'function']
      );
    });
  });

  test('ES6 Syntax', function(assert) {
    System.import('syntax/es6-file').then(function(m) {
      assert(
        [typeof m.q, 'function']
      );
    });
  });

  test('Module Name meta', function(assert) {
    System.import('loader/moduleName').then(function(m) {
      assert(
        [m.name, 'loader/moduleName']
      );
    })
  });

  test('Custom path', function(assert) {
    System.paths['bar'] = 'loader/custom-path.js';
    System.import('bar').then(function(m) {
      assert(m.bar, 'bar');
    })
  });

  test('Custom path wildcard', function(assert) {
    System.paths['bar/*'] = 'loader/custom-folder/*.js';
    System.import('bar/path').then(function(m) {
      assert(m.bar, 'baa');
    });
  });

  test('Custom path most specific', function(assert) {
    System.paths['bar/bar'] = 'loader/specific-path.js';
    System.import('bar/bar').then(function(m) {
      assert(m.path, true);
    });
  });

  var customLoader = new Loader({
    normalize: function(name, parentName, parentAddress) {
      return new Promise(function(resolve, reject) {
        if (name == 'asdfasdf') {
          return setTimeout(function() {
            resolve('loader/async-norm');
          }, 500);
        }

        if (name == 'error1')
          return setTimeout(function(){ reject('error1'); }, 100);

        var normalized = System.normalize(name, parentName, parentAddress);
        resolve(normalized);
      });
    },
    locate: function(load) {
        if (load.name == 'error2')
          return new Promise(function(resolve, reject) {
            setTimeout(function(){ reject('error2'); }, 100);
          });

      if (load.name.substr(0, 5) == 'path/')
        load.name = 'loader/' + load.name.substr(5);
      return System.locate(load);
    },
    fetch: function(load) {
      if (load.name == 'error3')
        throw 'error3';
      if (load.name == 'error4' || load.name == 'error5')
        return 'asdf';
      return System.fetch.apply(this, arguments);
    },
    translate: function(load) {
      if (load.name == 'error4')
        return new Promise(function(resolve, reject) {
          setTimeout(function(){ reject('error4'); }, 100);
        });
      return System.translate.apply(this, arguments);
    },
    instantiate: function(load) {
      if (load.name == 'error5')
        return new Promise(function(resolve, reject) {
          setTimeout(function(){ reject('error5'); }, 100);
        });
      // very bad AMD support
      if (load.source.indexOf('define') == -1)
        return System.instantiate(load);

      var factory, deps;
      var define = function(_deps, _factory) {
        deps = _deps;
        factory = _factory;
      }
      eval(load.source);
      return {
        deps: deps,
        execute: function() {
          var deps = [];
          for (var i = 0; i < arguments.length; i++)
            deps.push(customLoader.get(arguments[i]));
          return new Module(factory.apply(null, deps));
        }
      }
    }
  });

  test('Custom loader standard load', function(assert) {
    var p = customLoader.import('loader/test').then(function(m) {
      assert(m.loader, 'custom');
    });
    if (p.catch)
      p.catch(function() {});
  });
  test('Custom loader special rules', function(assert) {
    customLoader.import('path/custom').then(function(m) {
      assert(m.path, true);
    });
  });
  test('Custom loader AMD support', function(assert) {
    customLoader.import('loader/amd').then(function(m) {
      assert(m.format, 'amd');
    });
  });
  test('Custom loader hook - normalize error', function(assert) {
    customLoader.import('loader/error1-parent').then(function(m) {
      console.log('got n');
    }).catch(function(e) {
      assert(e, 'error1');
    });
  });
  test('Custom loader hook - locate error', function(assert) {
    customLoader.import('error2').then(function(m) {}, function(e) {
      assert(e, 'error2');
    });
  });
  test('Custom loader hook - fetch error', function(assert) {
    customLoader.import('error3').then(function(m) {}, function(e) {
      assert(e, 'error3');
    });
  });
  test('Custom loader hook - translate error', function(assert) {
    customLoader.import('error4').then(function(m) {}, function(e) {
      assert(e, 'error4');
    });
  });
  test('Custom loader hook - instantiate error', function(assert) {
    customLoader.import('error5').then(function(m) {}, function(e) {
      assert(e, 'error5');
    });
  });

  test('Async Normalize', function(assert) {
    customLoader.normalize('asdfasdf').then(function(normalized) {
      return customLoader.import(normalized);
    }).then(function(m) {
      assert(m.n, 'n');
    });
  });
}
<commit_msg>test double loading<commit_after>
var System, Loader, Module, tests, test;

var testCnt = 0, passed = 0, failed = 0;
var test = function(name, initialize) {
  if (typeof initialize != 'function') {
    var val = initialize;
    var exp = arguments[2];
    initialize = function(assert) {
      assert(val, exp);
    }
  }
  var testId = testCnt++;
  tests.addTest(testId, name);
  function assert(value, expected) {
    if (value != expected)
      return 'Got "' + value + '" instead of "' + expected + '"';
  }
  initialize(function(value, expected) {
    var failure;
    if (value instanceof Array) {
      for (var i = 0; i < arguments.length; i++)
        failure = failure || assert(arguments[i][0], arguments[i][1]);
    }
    else
      failure = assert(value, expected);
    if (failure)
      failed++;
    else
      passed++;
    tests.completeTest(testId, name, failure, { passed: passed, failed: failed, total: testCnt });
  });
}

if (typeof window != 'undefined') {
  // browser
  document.body.innerHTML = "

Summary
";
  tests = {
    addTest: function(id, name) {
      var p = document.createElement('tr');
      p.innerHTML = '' + name + '		'
      document.querySelector('.test tbody').appendChild(p);
    },
    completeTest: function(id, name, failure, summary) {
      document.querySelector('.test .result-' + id).innerHTML = !failure ? 'Passed' : 'Failed: ' + failure;
      document.querySelector('.summary').innerHTML = summary.passed + '/' + summary.total + ' tests passed';
    }
  }
  window.test = test;
  window.runTests = runTests;
}
else {
  // nodejs
  var ml = require('../lib/es6-module-loader');

  System = ml.System;
  Loader = ml.Loader;
  Module = ml.Module;

  tests = {
    addTest: function(id, name) {},
    completeTest: function(id, name, failure, summary) {
      console.log(name + ': ' + (!failure ? 'Passed' : 'Failed: ' + result.failedAssertion));
      console.log(summary.passed + '/' + summary.total + ' passed. ');
    },
  };

  runTests();
}

function runTests() {
  // Normalize tests - identical to https://github.com/google/traceur-compiler/blob/master/test/unit/runtime/System.js

  var oldBaseURL = System.baseURL;
  System.baseURL = 'http://example.org/a/b.html';

  test('Normalize - No Referer', System.normalize('d/e/f'), 'd/e/f');
  // test('Normalize - Below baseURL', System.normalize('../e/f'), '../e/f');

  var refererName = 'dir/file';
  test('Normalize - Relative paths', System.normalize('./d/e/f', refererName), 'dir/d/e/f');
  test('Normalize - Relative paths', System.normalize('../e/f', refererName), 'e/f');

  test('Normalize - name undefined', function(assert) {
    try {
      System.normalize(undefined, refererName);
    }
    catch(e) {
      assert(e.message, 'Module name must be a string');
    }
  });

  test('Normalize - embedded ..', function(assert) {
    try {
      System.normalize('a/b/../c');
    }
    catch(e) {
      assert(e.message, 'Illegal module name"a/b/../c"');
    }
  });
  test('Normalize - embedded ..', function(assert) {
    try {
      System.normalize('a/../b', refererName);
    }
    catch(e) {
      assert(e.message, 'Illegal module name"a/../b"');
    }
  });
  test('Normalize - embedded ..', function(assert) {
    try {
      System.normalize('a/b/../c', refererName);
    }
    catch(e) {
      assert(e.message, 'Illegal module name"a/b/../c"');
    }
  });

  // test('Normalize - below referer', System.normalize('../../e/f', refererName), '../e/f');

  test('Normalize - backwards compat', System.normalize('./a.js'), 'a.js');

  test('Normalize - URL', function(assert) {
    try {
      System.normalize('http://example.org/a/b.html');
    }
    catch(e) {
      assert();
    }
  });

  System.baseURL = 'http://example.org/a/';

  test('Locate', System.locate({ name: '@abc/def' }), 'http://example.org/a/@abc/def.js');
  test('Locate', System.locate({ name: 'abc/def' }), 'http://example.org/a/abc/def.js');

  // paths
  System.paths['path/*'] = '/test/*.js';
  test('Locate paths', System.locate({ name: 'path/test' }), 'http://example.org/test/test.js');

  System.baseURL = oldBaseURL;

  // More Normalize tests

  test('Normalize test 1', function(assert) {
    assert(System.normalize('./a/b', 'c'), 'a/b');
  });
  test('Normalize test 2', function(assert) {
    assert(System.normalize('./a/b', 'c/d'), 'c/a/b');
  });
  test('Normalize test 3', function(assert) {
    assert(System.normalize('./a/b', '../c/d'), '../c/a/b');
  });
  test('Normalize test 4', function(assert) {
    assert(System.normalize('./a/b', '../c/d'), '../c/a/b');
  });
  test('Normalize test 5', function(assert) {
    assert(System.normalize('../a/b', '../../c/d'), '../../a/b');
  });

  test('Import a script', function(assert) {
    System.import('syntax/script').then(function(m) {
      assert(!!m, true);
    });
  });

  test('Import a script once loaded', function(assert) {
    System.import('syntax/script').then(function(m) {
      System.import('syntax/script').then(function(m) {
        assert(!!m, true);
      });
    });
  });

  test('Import ES6', function(assert) {
    System.import('syntax/es6').then(function(m) {
      assert(m.p, 'p');
    });
  });

  test('Import ES6 with dep', function(assert) {
    System.import('syntax/es6-withdep').then(function(m) {
      assert(m.p, 'p');
    }, function(e) {
      console.log(e);
    });
  });

  test('Direct import without bindings', function(assert) {
    System.import('syntax/direct').then(function(m) {
      console.log('got direct');
      assert(!!m, true);
    });
  });

  test('Load order test: A', function(assert) {
    System.import('loads/a').then(function(m) {
      assert(
        [m.a, 'a'],
        [m.b, 'b']
      );
    });
  });

  test('Load order test: C', function(assert) {
    System.import('loads/c').then(function(m) {
      assert(
        [m.c, 'c'],
        [m.a, 'a'],
        [m.b, 'b']
      );
    });
  });

  test('Load order test: S', function(assert) {
    System.import('loads/s').then(function(m) {
      assert(
        [m.s, 's'],
        [m.c, 'c'],
        [m.a, 'a'],
        [m.b, 'b']
      );
    });
  });

  test('Load order test: _a', function(assert) {
    System.import('loads/_a').then(function(m) {
      assert(
        [m.b, 'b'],
        [m.d, 'd'],
        [m.g, 'g'],
        [m.a, 'a']
      );
    })
  });
  test('Load order test: _e', function(assert) {
    System.import('loads/_e').then(function(m) {
      assert(
        [m.c, 'c'],
        [m.e, 'e']
      );
    })
  });
  test('Load order test: _f', function(assert) {
    System.import('loads/_f').then(function(m) {
      assert(
        [m.g, 'g'],
        [m.f, 'f']
      );
    })
  });
  test('Load order test: _h', function(assert) {
    System.import('loads/_h').then(function(m) {
      assert(
        [m.i, 'i'],
        [m.a, 'a'],
        [m.h, 'h']
      );
    })
  });

  test('Export Syntax', function(assert) {
    System.import('syntax/export').then(function(m) {
      assert(
        [m.p, 5],
        [typeof m.foo, 'function'],
        [typeof m.q, 'object'],
        [m.default.name, 'bar'],
        [m.s, 4],
        [m.t, 4],
        [typeof m.m, 'object']
      );
    });
  });

  test('Re-export', function(assert) {
    System.import('syntax/reexport1').then(function(m) {
      assert(m.p, 5);
    });
  });

  test('Re-export with new name', function(assert) {
    System.import('syntax/reexport2').then(function(m) {
      assert(
        [m.q, 4],
        [m.z, 5]
      );
    }).catch(function(err) {
      console.log('error');
      console.log(err);
    });
  });

  test('Import Syntax', function(assert) {
    System.import('syntax/import').then(function(m) {
      assert(
        [m.a.name, 'bar'],
        [m.b, 4],
        [m.c, 5],
        [m.d, 4],
        [typeof m.q.foo, 'function']
      );
    });
  });

  test('ES6 Syntax', function(assert) {
    System.import('syntax/es6-file').then(function(m) {
      assert(
        [typeof m.q, 'function']
      );
    });
  });

  test('Module Name meta', function(assert) {
    System.import('loader/moduleName').then(function(m) {
      assert(
        [m.name, 'loader/moduleName']
      );
    })
  });

  test('Custom path', function(assert) {
    System.paths['bar'] = 'loader/custom-path.js';
    System.import('bar').then(function(m) {
      assert(m.bar, 'bar');
    })
  });

  test('Custom path wildcard', function(assert) {
    System.paths['bar/*'] = 'loader/custom-folder/*.js';
    System.import('bar/path').then(function(m) {
      assert(m.bar, 'baa');
    });
  });

  test('Custom path most specific', function(assert) {
    System.paths['bar/bar'] = 'loader/specific-path.js';
    System.import('bar/bar').then(function(m) {
      assert(m.path, true);
    });
  });

  var customLoader = new Loader({
    normalize: function(name, parentName, parentAddress) {
      return new Promise(function(resolve, reject) {
        if (name == 'asdfasdf') {
          return setTimeout(function() {
            resolve('loader/async-norm');
          }, 500);
        }

        if (name == 'error1')
          return setTimeout(function(){ reject('error1'); }, 100);

        var normalized = System.normalize(name, parentName, parentAddress);
        resolve(normalized);
      });
    },
    locate: function(load) {
        if (load.name == 'error2')
          return new Promise(function(resolve, reject) {
            setTimeout(function(){ reject('error2'); }, 100);
          });

      if (load.name.substr(0, 5) == 'path/')
        load.name = 'loader/' + load.name.substr(5);
      return System.locate(load);
    },
    fetch: function(load) {
      if (load.name == 'error3')
        throw 'error3';
      if (load.name == 'error4' || load.name == 'error5')
        return 'asdf';
      return System.fetch.apply(this, arguments);
    },
    translate: function(load) {
      if (load.name == 'error4')
        return new Promise(function(resolve, reject) {
          setTimeout(function(){ reject('error4'); }, 100);
        });
      return System.translate.apply(this, arguments);
    },
    instantiate: function(load) {
      if (load.name == 'error5')
        return new Promise(function(resolve, reject) {
          setTimeout(function(){ reject('error5'); }, 100);
        });
      // very bad AMD support
      if (load.source.indexOf('define') == -1)
        return System.instantiate(load);

      var factory, deps;
      var define = function(_deps, _factory) {
        deps = _deps;
        factory = _factory;
      }
      eval(load.source);
      return {
        deps: deps,
        execute: function() {
          var deps = [];
          for (var i = 0; i < arguments.length; i++)
            deps.push(customLoader.get(arguments[i]));
          return new Module(factory.apply(null, deps));
        }
      }
    }
  });

  test('Custom loader standard load', function(assert) {
    var p = customLoader.import('loader/test').then(function(m) {
      assert(m.loader, 'custom');
    });
    if (p.catch)
      p.catch(function() {});
  });
  test('Custom loader special rules', function(assert) {
    customLoader.import('path/custom').then(function(m) {
      assert(m.path, true);
    });
  });
  test('Custom loader AMD support', function(assert) {
    customLoader.import('loader/amd').then(function(m) {
      assert(m.format, 'amd');
    });
  });
  test('Custom loader hook - normalize error', function(assert) {
    customLoader.import('loader/error1-parent').then(function(m) {
      console.log('got n');
    }).catch(function(e) {
      assert(e, 'error1');
    });
  });
  test('Custom loader hook - locate error', function(assert) {
    customLoader.import('error2').then(function(m) {}, function(e) {
      assert(e, 'error2');
    });
  });
  test('Custom loader hook - fetch error', function(assert) {
    customLoader.import('error3').then(function(m) {}, function(e) {
      assert(e, 'error3');
    });
  });
  test('Custom loader hook - translate error', function(assert) {
    customLoader.import('error4').then(function(m) {}, function(e) {
      assert(e, 'error4');
    });
  });
  test('Custom loader hook - instantiate error', function(assert) {
    customLoader.import('error5').then(function(m) {}, function(e) {
      assert(e, 'error5');
    });
  });

  test('Async Normalize', function(assert) {
    customLoader.normalize('asdfasdf').then(function(normalized) {
      return customLoader.import(normalized);
    }).then(function(m) {
      assert(m.n, 'n');
    });
  });
}
<|endoftext|>


<commit_before>var locale = require('..'),
  assert = require('assert'),
  http = require('http'),
  express = require('express'),
  fs = require('fs');

describe('express-locale', function () {
  it('should return a function', function () {
    var type = typeof locale();
    assert.equal(type, 'function');
  });

  describe('request', function () {
    var app,
      config = {};

    function startServer(done) {
      app = express()
        .use(express.cookieParser())
        .use(locale(config))
        .use(function (req, res, next) {
          res.end(JSON.stringify(req.locale));
        })
        .listen(4000, done);
    }

    function endServer (done) {
      app.close(done);
    }

    function get(headers, callback) {
      var data = '';

      if (typeof headers === 'function') {
        callback = headers;
        headers = {};
      }

      http.get({
          host: 'localhost',
          port: 4000,
          headers: headers
        }, function (res) {
          res.on('data', function (chunk) {
            data += chunk;
          });
          res.on('end', function () {
            callback(JSON.parse(data));
          });
        });
    }

    beforeEach(startServer);
    afterEach(endServer);

    describe('using default configuration', function () {
      it('without any headers', function (done) {
        get(function(locale) {
          assert.equal(locale.code, 'en_UK');
          assert.equal(locale.source, 'default');
          done();
        });
      });
    });

    describe('using allowed option', function () {
      before(function () {
        config = require('./fixture/allowed.json');
      });
      it('with "Accept-Language: de,de-CH;q=0.8,en;q=0.6"', function (done) {
        get({
          'Accept-Language': 'de,de-CH;q=0.8,en;q=0.6'
        }, function(locale) {
          assert.equal(locale.code, 'de_CH');
          assert.equal(locale.source, 'accept-language');
          done();
        });
      });
    });

    describe('using map.language option', function () {
      before(function () {
        config = require('./fixture/map-language.json');
      });
      it('with "Accept-Language: de,de-CH;q=0.8,en;q=0.6"', function (done) {
        get({
          'Accept-Language': 'de,de-CH;q=0.8,en;q=0.6'
        }, function(locale) {
          assert.equal(locale.code, 'de_DE');
          assert.equal(locale.source, 'accept-language');
          done();
        });
      });
    });

    describe('using map.domain option', function () {
      before(function () {
        config = require('./fixture/map-domain.json');
      });
      it('without any headers', function (done) {
        get(function(locale) {
          assert.equal(locale.code, 'nl_BE');
          assert.equal(locale.source, 'domain');
          done();
        });
      });
    });

    describe('using cookie lookup', function () {
      before(function () {
        config = require('./fixture/cookie.json');
      });
      it('with "Cookie: locale=nl_BE"', function (done) {
        get({
          'Cookie': 'locale=nl_BE'
        }, function(locale) {
          assert.equal(locale.code, 'nl_BE');
          assert.equal(locale.source, 'cookie');
          done();
        });
      });
    });
  });
});
<commit_msg>fix failing test<commit_after>var locale = require('..'),
  assert = require('assert'),
  http = require('http'),
  express = require('express'),
  fs = require('fs');

describe('express-locale', function () {
  it('should return a function', function () {
    var type = typeof locale();
    assert.equal(type, 'function');
  });

  describe('request', function () {
    var app,
      config = {};

    function startServer(done) {
      app = express()
        .use(express.cookieParser())
        .use(locale(config))
        .use(function (req, res, next) {
          res.end(JSON.stringify(req.locale));
        })
        .listen(4000, done);
    }

    function endServer (done) {
      app.close(done);
    }

    function get(headers, callback) {
      var data = '';

      if (typeof headers === 'function') {
        callback = headers;
        headers = {};
      }

      http.get({
          host: 'localhost',
          port: 4000,
          headers: headers
        }, function (res) {
          res.on('data', function (chunk) {
            data += chunk;
          });
          res.on('end', function () {
            callback(JSON.parse(data));
          });
        });
    }

    beforeEach(startServer);
    afterEach(endServer);

    describe('using default configuration', function () {
      it('without any headers', function (done) {
        get(function(locale) {
          assert.equal(locale.code, 'en_GB');
          assert.equal(locale.source, 'default');
          done();
        });
      });
    });

    describe('using allowed option', function () {
      before(function () {
        config = require('./fixture/allowed.json');
      });
      it('with "Accept-Language: de,de-CH;q=0.8,en;q=0.6"', function (done) {
        get({
          'Accept-Language': 'de,de-CH;q=0.8,en;q=0.6'
        }, function(locale) {
          assert.equal(locale.code, 'de_CH');
          assert.equal(locale.source, 'accept-language');
          done();
        });
      });
    });

    describe('using map.language option', function () {
      before(function () {
        config = require('./fixture/map-language.json');
      });
      it('with "Accept-Language: de,de-CH;q=0.8,en;q=0.6"', function (done) {
        get({
          'Accept-Language': 'de,de-CH;q=0.8,en;q=0.6'
        }, function(locale) {
          assert.equal(locale.code, 'de_DE');
          assert.equal(locale.source, 'accept-language');
          done();
        });
      });
    });

    describe('using map.domain option', function () {
      before(function () {
        config = require('./fixture/map-domain.json');
      });
      it('without any headers', function (done) {
        get(function(locale) {
          assert.equal(locale.code, 'nl_BE');
          assert.equal(locale.source, 'domain');
          done();
        });
      });
    });

    describe('using cookie lookup', function () {
      before(function () {
        config = require('./fixture/cookie.json');
      });
      it('with "Cookie: locale=nl_BE"', function (done) {
        get({
          'Cookie': 'locale=nl_BE'
        }, function(locale) {
          assert.equal(locale.code, 'nl_BE');
          assert.equal(locale.source, 'cookie');
          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var Logsene = require('../index.js')
var token = process.env.LOGSENE_TOKEN || 'YOUR_TEST_TOKEN'
process.env.LOGSENE_URL='http://127.0.0.1:19200/_bulk'
if (!process.env.LOGSENE_URL) {
  process.env.LOGSENE_URL='http://apps1.test.sematext.com:8088/_bulk'
}

console.log('Receiver: ' + process.env.LOGSENE_URL)
console.log('Token: ' + process.env.LOGSENE_TOKEN)
var http = require('http')
http.createServer(function (req, res) {
          res.writeHead(200, {'Content-Type': 'text/plain'})
          req.on('data', function (data) {
            // console.log(data.toString().substring(0,10))
          })
          req.on('end', function () {
            res.end('{"code":"200"}\n')
          })
          // console.log(req.path)
  }).listen(19200, '127.0.0.1')

var MAX_MB = Number(process.env.LOAD_TEST_MAX_MB)||30
describe('Logsene Load Test ', function () {
  it('memory keeps below ' + MAX_MB + ' MB since start', function (done) {
    this.timeout(120000)
    try {
      console.log('\t\tLOAD_TEST_MAX_MB: ' + MAX_MB)
      var logCount = Number(process.env.LOAD_TEST_SIZE) || 50000
      console.log('\t\tLOAD_TEST_SIZE: ' + logCount)

      var memory = process.memoryUsage().heapUsed
      var counter = 0

      var logsene = new Logsene(token, 'test', process.env.LOGSENE_URL, './')
      var start = new Date().getTime()
      var doneCalled = false
      console.log('\tRSS: ' + process.memoryUsage().rss / 1024 / 1024 + ' MB')
      console.log('\tHeap used: ' + process.memoryUsage().heapUsed / 1024 / 1024 + ' MB')

      function evtH (event) {
        if (doneCalled) {
          return
        }
        counter = counter + event.count
        var memory2 = 0
        if (counter >= logCount) {
          memory2 = process.memoryUsage().heapUsed
          var heapDiff = ((memory2 - memory) / 1024 / 1024)
          console.log('\tHeap diff: ' + heapDiff + ' MB')
          console.log('\tHeap used: ' + process.memoryUsage().heapUsed / 1024 / 1024 + ' MB')
          console.log('\tRSS: ' + process.memoryUsage().rss / 1024 / 1024 + ' MB')
          console.log('\tTransmission duration for ' + counter + ' logs: ' + (new Date().getTime() - start) / 1000 + ' sec.')
          if (heapDiff < MAX_MB) {
            doneCalled = true
            done()
          } else {
            done(new Error('Too much memory used:' + heapDiff + ' MB'))
          }
        }
      }

      logsene.on('log', evtH)
      logsene.once('error', function (event) {
        done(event)
      })
      logsene.on('error', console.log)
      for (var i = 0; i < logCount; i++)
        logsene.log('info', 'test message ' + i, {testField: 'Test custom field ' + i, counter: i})
    } catch (err) {
      done(err)
    }
  })
})

describe('Logsene constructor', function () {
  it('should fail without a token', function (done) {
    var emptyTokens = [undefined, null, '']
    emptyTokens.forEach(function (token) {
      try {
        new Logsene(token)
        done(new Error('Should throw exception'))
      } catch(err) {}
    })
    done()
  })
})

describe('Logsene log ', function () {
  it('should not throw circular reference error', function (done) {
    var logsene = new Logsene(token, 'test')
    logsene.on('error', console.log)
    function Foo () {
      this.abc = 'Hello'
      this.circular = this
    }
    var foo = new Foo()
    try {
      logsene.log('info', 'circular test', foo)
      if (logsene.bulkReq.getContentsAsString('utf-8').indexOf('[Circular') !== -1) {
        done()
      } else {
        done(new Error('The circular reference was not caught'))
      }
    } catch(err) {
      done(err)
    }
  })
  it('logs have default fields message, @timestamp, host, ip + custom fields', function (done) {
    this.timeout(20000)
    try {
      var logsene = new Logsene(token, 'test', process.env.LOGSENE_URL)
      // check for all required fields!
      logsene.once('logged', function (event) {
        if (!event.msg.testField || !event.msg.message || !event.msg['@timestamp'] || !event.msg.severity || !event.msg.host || !event.msg.ip) {
          done(new Error('missing fields in log: ' + JSON.stringify(event.msg)))
        } else {
          if (event.msg.message == 'test')
            done()
        }
      })
      logsene.once('error', function (event) {
        done(event)
      })
      logsene.log('info', 'test', {testField: 'Test custom field '})
    } catch (err) {
      done(err)
    }
  })
  it('transmit', function (done) {
    this.timeout(20000)
    try {
      var logsene = new Logsene(token, 'test', process.env.LOGSENE_URL)
      // check for all required fields!
      logsene.on('logged', function (event) {
        if (!event.msg.message || !event.msg['@timestamp'] || !event.msg.severity || !event.msg.host || !event.msg.ip) {
          done(new Error('missing fields in log:' + JSON.tringify(event.msg)))
        }
      })
      logsene.once('log', function (event) {
        done()
      })
      logsene.once('error', function (event) {
        done(event)
      })
      logsene.on('error', console.log)
      for (var i = 0; i <= 100; i++)
        logsene.log('info', 'test message ' + i, {testField: 'Test custom field ' + i, counter: i})
    } catch (err) {
      done(err)
    }
  })
})

describe('Logsene DiskBuffer ', function () {
  it('re-transmit', function (done) {
    this.timeout(50000)
    process.env.DEBUG_LOGSENE_DISK_BUFFER = true
    var DiskBuffer = require('../DiskBuffer.js')
    var db = DiskBuffer.createDiskBuffer({
      tmpDir: './tmp',
      interval: 2000
    })
    db.syncFileListFromDir()
    db.on('retransmit-req', function (event) {
        db.rmFile(event.fileName)
        db.retransmitNext()
    })
    db.once('removed', function () {
      done()
    })
    setTimeout (function () {
      db.store({message: 'hello'}, function () {
        db.retransmitNext()
      })
    }, 1000)

  })
})

describe('Logsene persistance ', function () {
  it('re-transmit', function (done) {
    this.timeout(70000)
    try {
      process.env.LOGSENE_DISK_BUFFER_INTERVAL = 2000
      var logsene = new Logsene(token, 'test', process.env.LOGSENE_URL, './mocha-test')
      var url = logsene.url
      logsene.diskBuffer(true, './mocha-test')
      logsene.setUrl('http://notreachable.test')
      logsene.db.once('removed', function (event) {
        done()
      })
      logsene.on('error', function (err) {
        if (err) {
          logsene.setUrl(process.env.LOGSENE_URL)
        }
      })
      setTimeout(function () {
        for (var i = 0; i <= 1001; i++) {
          logsene.log('info', 'test retransmit message ' + i, {_id: 'hey', testField: 'Test custom field ' + i, counter: i, _type: 'test_type', 'dot.sep.field': 34 })
        }
      }, 1000)

    } catch (err) {
      done(err)
    }
  })
})
<commit_msg>standardized (syntax check/format), fix typo<commit_after>var Logsene = require('../index.js')
var token = process.env.LOGSENE_TOKEN || 'YOUR_TEST_TOKEN'
process.env.LOGSENE_URL = 'http://127.0.0.1:19200/_bulk'
if (!process.env.LOGSENE_URL) {
  process.env.LOGSENE_URL = 'http://apps1.test.sematext.com:8088/_bulk'
}

console.log('Receiver: ' + process.env.LOGSENE_URL)
console.log('Token: ' + process.env.LOGSENE_TOKEN)
var http = require('http')
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  req.on('data', function (data) {
    // console.log(data.toString().substring(0,10))
  })
  req.on('end', function () {
    res.end('{"code":"200"}\n')
  })
// console.log(req.path)
}).listen(19200, '127.0.0.1')

var MAX_MB = Number(process.env.LOAD_TEST_MAX_MB) || 30
describe('Logsene Load Test ', function () {
  it('memory keeps below ' + MAX_MB + ' MB since start', function (done) {
    this.timeout(120000)
    try {
      console.log('\t\tLOAD_TEST_MAX_MB: ' + MAX_MB)
      var logCount = Number(process.env.LOAD_TEST_SIZE) || 50000
      console.log('\t\tLOAD_TEST_SIZE: ' + logCount)

      var memory = process.memoryUsage().heapUsed
      var counter = 0

      var logsene = new Logsene(token, 'test', process.env.LOGSENE_URL, './')
      var start = new Date().getTime()
      var doneCalled = false
      console.log('\tRSS: ' + process.memoryUsage().rss / 1024 / 1024 + ' MB')
      console.log('\tHeap used: ' + process.memoryUsage().heapUsed / 1024 / 1024 + ' MB')

      function evtH (event) {
        if (doneCalled) {
          return
        }
        counter = counter + event.count
        var memory2 = 0
        if (counter >= logCount) {
          memory2 = process.memoryUsage().heapUsed
          var heapDiff = ((memory2 - memory) / 1024 / 1024)
          console.log('\tHeap diff: ' + heapDiff + ' MB')
          console.log('\tHeap used: ' + process.memoryUsage().heapUsed / 1024 / 1024 + ' MB')
          console.log('\tRSS: ' + process.memoryUsage().rss / 1024 / 1024 + ' MB')
          console.log('\tTransmission duration for ' + counter + ' logs: ' + (new Date().getTime() - start) / 1000 + ' sec.')
          if (heapDiff < MAX_MB) {
            doneCalled = true
            done()
          } else {
            done(new Error('Too much memory used:' + heapDiff + ' MB'))
          }
        }
      }

      logsene.on('log', evtH)
      logsene.once('error', function (event) {
        done(event)
      })
      logsene.on('error', console.log)
      for (var i = 0; i < logCount; i++) {
        logsene.log('info', 'test message ' + i, {testField: 'Test custom field ' + i, counter: i})
      }
    } catch (err) {
      done(err)
    }
  })
})

describe('Logsene constructor', function () {
  it('should fail without a token', function (done) {
    var emptyTokens = [undefined, null, '']
    emptyTokens.forEach(function (token) {
      try {
        new Logsene(token)
        done(new Error('Should throw exception'))
      } catch (err) {
        // nothing to do here
      }
    })
    done()
  })
})

describe('Logsene log ', function () {
  it('should not throw circular reference error', function (done) {
    var logsene = new Logsene(token, 'test')
    logsene.on('error', console.log)
    function Foo () {
      this.abc = 'Hello'
      this.circular = this
    }
    var foo = new Foo()
    try {
      logsene.log('info', 'circular test', foo)
      if (logsene.bulkReq.getContentsAsString('utf-8').indexOf('[Circular') !== -1) {
        done()
      } else {
        done(new Error('The circular reference was not caught'))
      }
    } catch(err) {
      done(err)
    }
  })
  it('logs have default fields message, @timestamp, host, ip + custom fields', function (done) {
    this.timeout(20000)
    try {
      var logsene = new Logsene(token, 'test', process.env.LOGSENE_URL)
      // check for all required fields!
      logsene.once('logged', function (event) {
        if (!event.msg.testField || !event.msg.message || !event.msg['@timestamp'] || !event.msg.severity || !event.msg.host || !event.msg.ip) {
          done(new Error('missing fields in log: ' + JSON.stringify(event.msg)))
        } else {
          if (event.msg.message == 'test') {
            done()
          }
        }
      })
      logsene.once('error', function (event) {
        done(event)
      })
      logsene.log('info', 'test', {testField: 'Test custom field '})
    } catch (err) {
      done(err)
    }
  })
  it('transmit', function (done) {
    this.timeout(20000)
    try {
      var logsene = new Logsene(token, 'test', process.env.LOGSENE_URL)
      // check for all required fields!
      logsene.on('logged', function (event) {
        if (!event.msg.message || !event.msg['@timestamp'] || !event.msg.severity || !event.msg.host || !event.msg.ip) {
          done(new Error('missing fields in log:' + JSON.stringify(event.msg)))
        }
      })
      logsene.once('log', function (event) {
        done()
      })
      logsene.once('error', function (event) {
        done(event)
      })
      logsene.on('error', console.log)
      for (var i = 0; i <= 100; i++)
        logsene.log('info', 'test message ' + i, {testField: 'Test custom field ' + i, counter: i})
    } catch (err) {
      done(err)
    }
  })
})

describe('Logsene DiskBuffer ', function () {
  it('re-transmit', function (done) {
    this.timeout(50000)
    process.env.DEBUG_LOGSENE_DISK_BUFFER = true
    var DiskBuffer = require('../DiskBuffer.js')
    var db = DiskBuffer.createDiskBuffer({
      tmpDir: './tmp',
      interval: 2000
    })
    db.syncFileListFromDir()
    db.on('retransmit-req', function (event) {
      db.rmFile(event.fileName)
      db.retransmitNext()
    })
    db.once('removed', function () {
      done()
    })
    setTimeout(function () {
      db.store({message: 'hello'}, function () {
        db.retransmitNext()
      })
    }, 1000)
  })
})

describe('Logsene persistance ', function () {
  it('re-transmit', function (done) {
    this.timeout(70000)
    try {
      process.env.LOGSENE_DISK_BUFFER_INTERVAL = 2000
      var logsene = new Logsene(token, 'test', process.env.LOGSENE_URL, './mocha-test')
      var url = logsene.url
      logsene.diskBuffer(true, './mocha-test')
      logsene.setUrl('http://notreachable.test')
      logsene.db.once('removed', function (event) {
        done()
      })
      logsene.on('error', function (err) {
        if (err) {
          logsene.setUrl(process.env.LOGSENE_URL)
        }
      })
      setTimeout(function () {
        for (var i = 0; i <= 1001; i++) {
          logsene.log('info', 'test retransmit message ' + i, {_id: 'hey', testField: 'Test custom field ' + i, counter: i, _type: 'test_type', 'dot.sep.field': 34 })
        }
      }, 1000)
    } catch (err) {
      done(err)
    }
  })
})
<|endoftext|>


<commit_before>'use strict';

var esprintf = require('../');
var assert = require('assert');

/* global describe, it */

describe('esprintf', function() {
	describe('%s', function() {
		it('Does not delete dashes from the formatted string', function() {
			assert.equal(esprintf('%s', '-'), '-');
		});

		it('Correctly formats 3 string values of length 1', function() {
			assert.equal(esprintf('%s %s %s', 'a', 'b', 'c'), 'a b c');
		});

		it('Correctly formats 3 string values of length 1 with left justification and no min width', function() {
			assert.equal(esprintf('%-s %-s %-s', 'a', 'b', 'c'), 'a b c');
		});

		it('Correctly padds a format with 6 dynamic strings with dynamic length', function() {
			assert.equal(
				esprintf('%-*s %-*s %-*s %-*s %-*s', 'asda', 20, 'asdas', 21, 'asda', 22, 'asdasd', 23, 'asdasd', 24),
				'asda                 asdas                 asda                   asdasd                  asdasd                  '
			);
		});

		it('Correctly truncates the string length for a string with a dynamic width of 0', function() {
			assert.equal(esprintf('%*s', 'asda', 0), '');
		});
	});

	describe('%i', function() {
		it('Correctly formats a single integer', function() {
			assert.equal(esprintf('%i', 123456), '123456');
		});

		it('Correctly formats a single integer with forced prefix', function() {
			assert.equal(esprintf('%+i', 123456), '+123456');
		});

		it('Correctly truncates a single integer with fixed length', function() {
			assert.equal(esprintf('%3i', 123456), '123');
		});

		it('Correctly padds a single integer with zeros', function() {
			assert.equal(esprintf('%07i', 123456), '0123456');
		});

		it('Correctly rounds to an integer value', function() {
			assert.equal(esprintf('%i', 3.1415), '3');
		});
	});

	describe('%f', function() {
		it('Correctly formats a single float', function() {
			assert.equal(esprintf('%f', 123456.12345), '123456.12345');
		});

		it('Correctly formats a single float with forced prefix', function() {
			assert.equal(esprintf('%+f', 12346.123), '+12346.123');
		});

		it('Correctly truncates a single float with fixed length', function() {
			assert.equal(esprintf('%3f', 123456.123), '123');
		});

		it('Correctly padds a single float with zeros', function() {
			assert.equal(esprintf('%09f', 123456), '000123456');
		});

		it('Correctly padds a single float with zeros and a floating point length of 2', function() {
			assert.equal(esprintf('%010.2f', 123456.12), '0123456.12');
		});
	});

	describe('%x', function() {
		it('Single value', function() {
			assert.equal(esprintf('%x', 0xff), 'ff');
		});

		it('Single value with forced prefix', function() {
			assert.equal(esprintf('%#x', 0xff), '0xff');
		});
	});

	describe('%c', function() {
		it('Single value', function() {
			assert.equal(esprintf('%c', 'a'.charCodeAt(0)), 'a');
		});
	});

	describe('%b', function() {
		it('Single value', function() {
			assert.equal(esprintf('%b', 15), '1111');
		});
	});

	describe('%j', function() {
		it('Single value', function() {
			assert.equal(esprintf('%j', {
				top: 'kek'
			}), '{"top":"kek"}');
		});

		it('Single value with custom padding', function() {
			assert.equal(esprintf('%\'\tj', {
				top: 'kek'
			}), '{\n\t"top": "kek"\n}');
		});
	});

	describe('Index based formatting', function() {
		it('Works with a single value', function() {
			assert.equal(
				esprintf('%1$s', 'woo'),
				'woo'
			);
		});

		it('Works with more than 1 value', function() {
			assert.equal(
				esprintf('%2$s %1$s', 'wuff', 'waff'),
				'waff wuff'
			);
		});

		it('Works with more than 1 referencing the same value', function() {
			assert.equal(
				esprintf('%1$s %1$s', 'wuff'),
				'wuff wuff'
			);
		});
	});

	describe('Associative formatting', function() {
		it('Works with a single value', function() {
			assert.equal(
				esprintf('%(test)s', {
					test: 'woo'
				}),
				'woo'
			);
		});

		it('Works with more than 1 value', function() {
			assert.equal(
				esprintf('%(test2)s %(test)s', {
					test: 'wuff',
					test2: 'waff'
				}),
				'waff wuff'
			);
		});

		it('Works with more than 1 referencing the same value', function() {
			assert.equal(
				esprintf('%(test)s %(test)s', {
					test:'wuff'
				}),
				'wuff wuff'
			);
		});
	});

	describe('madness', function() {
		it('Is probably not a valid usecase', function() {
			assert.equal(
				esprintf(
					'%b %d %i %u %o %x %X %f %F %e %E %g %G %a %A %c %s',
					111,//b
					42,//d
					42,//i
					42,//u
					42,//o
					42,//x
					42,//X
					42.42,//f
					42.42,//F
					42154654.42,//e
					42154654.42,//E
					42154654.42,//g
					42154654.42,//G
					42154654.42,//a
					42154654.42,//A
					'a'.charCodeAt(0),//c
					'aefiosf'//s
				),
				//jscs:disable
				'110111 42 42 42 52 2a 2A 42.42 42.420000 4.215465e+7 4.215465E+7 4.21547e+7 4.21547E+7 2833a9e.6b851ep0 2833A9E.6B851EP0 a aefiosf'// jshint ignore:line
				//jscs:enable
			);
		});
	});
});
<commit_msg>Fixed tests to use locale on %f<commit_after>'use strict';

var esprintf = require('../');
var assert = require('assert');

/* global describe, it */

describe('esprintf', function() {
	describe('%s', function() {
		it('Does not delete dashes from the formatted string', function() {
			assert.equal(esprintf('%s', '-'), '-');
		});

		it('Correctly formats 3 string values of length 1', function() {
			assert.equal(esprintf('%s %s %s', 'a', 'b', 'c'), 'a b c');
		});

		it('Correctly formats 3 string values of length 1 with left justification and no min width', function() {
			assert.equal(esprintf('%-s %-s %-s', 'a', 'b', 'c'), 'a b c');
		});

		it('Correctly padds a format with 6 dynamic strings with dynamic length', function() {
			assert.equal(
				esprintf('%-*s %-*s %-*s %-*s %-*s', 'asda', 20, 'asdas', 21, 'asda', 22, 'asdasd', 23, 'asdasd', 24),
				'asda                 asdas                 asda                   asdasd                  asdasd                  '
			);
		});

		it('Correctly truncates the string length for a string with a dynamic width of 0', function() {
			assert.equal(esprintf('%*s', 'asda', 0), '');
		});
	});

	describe('%i', function() {
		it('Correctly formats a single integer', function() {
			assert.equal(esprintf('%i', 123456), '123456');
		});

		it('Correctly formats a single integer with forced prefix', function() {
			assert.equal(esprintf('%+i', 123456), '+123456');
		});

		it('Correctly truncates a single integer with fixed length', function() {
			assert.equal(esprintf('%3i', 123456), '123');
		});

		it('Correctly padds a single integer with zeros', function() {
			assert.equal(esprintf('%07i', 123456), '0123456');
		});

		it('Correctly rounds to an integer value', function() {
			assert.equal(esprintf('%i', 3.1415), '3');
		});
	});

	describe('%f', function() {
		it('Correctly formats a single float', function() {
			assert.equal(esprintf('%f', 123456.12345), (123456.12345).toLocaleString());
		});

		it('Correctly formats a single float with forced prefix', function() {
			assert.equal(esprintf('%+f', 12346.123), '+' + (12346.123).toLocaleString());
		});

		it('Correctly truncates a single float with fixed length', function() {
			assert.equal(esprintf('%3f', 123456.123), (123).toLocaleString());
		});

		it('Correctly padds a single float with zeros', function() {
			assert.equal(esprintf('%09f', 123456), '000' + (123456).toLocaleString());
		});

		it('Correctly padds a single float with zeros and a floating point length of 2', function() {
			assert.equal(esprintf('%010.2f', 123456.12), '0' + (123456.12).toLocaleString());
		});
	});

	describe('%x', function() {
		it('Single value', function() {
			assert.equal(esprintf('%x', 0xff), 'ff');
		});

		it('Single value with forced prefix', function() {
			assert.equal(esprintf('%#x', 0xff), '0xff');
		});
	});

	describe('%c', function() {
		it('Single value', function() {
			assert.equal(esprintf('%c', 'a'.charCodeAt(0)), 'a');
		});
	});

	describe('%b', function() {
		it('Single value', function() {
			assert.equal(esprintf('%b', 15), '1111');
		});
	});

	describe('%j', function() {
		it('Single value', function() {
			assert.equal(esprintf('%j', {
				top: 'kek'
			}), '{"top":"kek"}');
		});

		it('Single value with custom padding', function() {
			assert.equal(esprintf('%\'\tj', {
				top: 'kek'
			}), '{\n\t"top": "kek"\n}');
		});
	});

	describe('Index based formatting', function() {
		it('Works with a single value', function() {
			assert.equal(
				esprintf('%1$s', 'woo'),
				'woo'
			);
		});

		it('Works with more than 1 value', function() {
			assert.equal(
				esprintf('%2$s %1$s', 'wuff', 'waff'),
				'waff wuff'
			);
		});

		it('Works with more than 1 referencing the same value', function() {
			assert.equal(
				esprintf('%1$s %1$s', 'wuff'),
				'wuff wuff'
			);
		});
	});

	describe('Associative formatting', function() {
		it('Works with a single value', function() {
			assert.equal(
				esprintf('%(test)s', {
					test: 'woo'
				}),
				'woo'
			);
		});

		it('Works with more than 1 value', function() {
			assert.equal(
				esprintf('%(test2)s %(test)s', {
					test: 'wuff',
					test2: 'waff'
				}),
				'waff wuff'
			);
		});

		it('Works with more than 1 referencing the same value', function() {
			assert.equal(
				esprintf('%(test)s %(test)s', {
					test:'wuff'
				}),
				'wuff wuff'
			);
		});
	});

	describe('madness', function() {
		it('Is probably not a valid usecase', function() {
			assert.equal(
				esprintf(
					'%b %d %i %u %o %x %X %f %F %e %E %g %G %a %A %c %s',
					111,//b
					42,//d
					42,//i
					42,//u
					42,//o
					42,//x
					42,//X
					42.42,//f
					42.42,//F
					42154654.42,//e
					42154654.42,//E
					42154654.42,//g
					42154654.42,//G
					42154654.42,//a
					42154654.42,//A
					'a'.charCodeAt(0),//c
					'aefiosf'//s
				),
				//jscs:disable
				'110111 42 42 42 52 2a 2A ' + (42.42).toLocaleString() + ' 42.420000 4.215465e+7 4.215465E+7 4.21547e+7 4.21547E+7 2833a9e.6b851ep0 2833A9E.6B851EP0 a aefiosf'// jshint ignore:line
				//jscs:enable
			);
		});
	});
});
<|endoftext|>


<commit_before>'use strict';

var config

var middleware = require('../index.js');

var lastTimestamp = null;

function addFile(path) {

}

function touchFile(path) {

}

function delFile(path) {

}

function addDir(path) {

}

function rmDir(path) {

}

function fakeReq(server, callback) {
  var headers = [];
  var buf = [];

  server(null, {
    end: function(s) {
      if (typeof s === 'string') {
        buf.push(s);
      }
      callback(headers, buf.join(''));
    },
    write: function(s) {
      if (typeof s === 'string') {
        buf.push(s);
      }
    },
    set: function(name, value) {
      headers.push({name: name, value: value});
    }
  });
}

function assertInManifest(server, line) {

}

function getManifestComment(server) {
  console.log('get comment!');
  fakeReq(server, function(headers, body) {
    console.log(body.split('\n'));
  });
}

function assertManifestChanged(server) {

}

function assertManifestNotChanged(server) {

}

middleware.generator('test', function(server) {
  getManifestComment(server);
  server.stop();
});

<commit_msg>Pull initial generator config out to variable<commit_after>'use strict';

var CONFIG = {
  file: 'test'
};

var middleware = require('../index.js');

var lastTimestamp = null;

function addFile(path) {

}

function touchFile(path) {

}

function delFile(path) {

}

function addDir(path) {

}

function rmDir(path) {

}

function fakeReq(server, callback) {
  var headers = [];
  var buf = [];

  server(null, {
    end: function(s) {
      if (typeof s === 'string') {
        buf.push(s);
      }
      callback(headers, buf.join(''));
    },
    write: function(s) {
      if (typeof s === 'string') {
        buf.push(s);
      }
    },
    set: function(name, value) {
      headers.push({name: name, value: value});
    }
  });
}

function assertInManifest(server, line) {

}

function getManifestComment(server) {
  console.log('get comment!');
  fakeReq(server, function(headers, body) {
    console.log(body.split('\n'));
  });
}

function assertManifestChanged(server) {

}

function assertManifestNotChanged(server) {

}

middleware.generator(CONFIG, function(server) {
  getManifestComment(server);
  server.stop();
});

<|endoftext|>


<commit_before>'use strict';

const ASSERT = require('assert'),
  REQUEST = require('request'),
  SPEC_GEN = require('../server');

const PORT = 3000,
  BASE_URL = 'http://localhost:3000/',
  NO_URL = '?type=foo&URL=notice-that-its-in-uppercase',
  NO_TYPE = '?url=foo&TYPE=notice-that-its-in-uppercase',
  BAD_GENERATOR = '?type=fluxor&url=http://example.com/',
  BAD_SHORTNAME = '?type=RESPEC&url=http://example.com/%3FshortName%3Ddiplodocus',
  NO_RESPEC = '?type=RESPEC&url=http://example.com/',
  SUCCESS1 = '?type=respec&url=https://w3c.github.io/manifest/',
  SUCCESS2 = '?type=respec&url=https://w3c.github.io/payment-request/',
  SUCCESS3 = '?type=respec&url=https://w3c.github.io/resource-hints/';

const FAILS_WITH = (done, expectedMessage = '{"error":"Both \'type\' and \'url\' are required."}', expectedCode = 500) =>
  (error, response, body) => {
    ASSERT.equal(error, null);
    ASSERT.equal(response.statusCode, expectedCode);
    if (expectedMessage instanceof RegExp)
      ASSERT.ok(body.match(expectedMessage));
    else
      ASSERT.equal(body, expectedMessage);
    done();
  }
;

const SUCCEEDS = (done) =>
  (error, response, body) => {
    ASSERT.equal(error, null);
    ASSERT.equal(response.statusCode, 200);
    ASSERT.equal(response.statusMessage, 'OK');
    done();
  };
;

let server;

describe('spec-generator', () => {

  before(() => {
    server = SPEC_GEN.start(PORT);
  });

  describe('fails when it should', () => {
    it('without parameters', (done) => REQUEST.get(BASE_URL, FAILS_WITH(done)));
    it('if there\'s no URL', (done) => REQUEST.get(BASE_URL + NO_URL, FAILS_WITH(done)));
    it('if there\'s no type', (done) => REQUEST.get(BASE_URL + NO_TYPE, FAILS_WITH(done)));
    it('if the generator is not valid', (done) => REQUEST.get(BASE_URL + BAD_GENERATOR, FAILS_WITH(done, '{"error":"Unknown generator: fluxor"}')));
    it('if the shortname is not valid', (done) => REQUEST.get(BASE_URL + BAD_SHORTNAME, FAILS_WITH(done, '{"error":"Not Found"}', 404)));
    it('if the URL does not point to a Respec document', (done) => REQUEST.get(BASE_URL + NO_RESPEC, FAILS_WITH(
      done,
      /That\ doesn't\ seem\ to\ be\ a\ ReSpec\ document\.\ Please\ check\ manually\:/
    )));
  });

  describe('succeeds when it should', () => {
    it('Web App Manifest ("appmanifest")', (done) => REQUEST.get(BASE_URL + SUCCESS1, SUCCEEDS(done)));
    it('Payment Request API ("payment-request")', (done) => REQUEST.get(BASE_URL + SUCCESS2, SUCCEEDS(done)));
    it('Resource Hints ("resource-hints")', (done) => REQUEST.get(BASE_URL + SUCCESS3, SUCCEEDS(done)));
  });

  after(() => server.close());

});
<commit_msg>Add $AUTHORIZATION to URLs when testing<commit_after>'use strict';

const ASSERT = require('assert'),
  REQUEST = require('request'),
  SPEC_GEN = require('../server');

const PORT = 3000,
  BASE_URL = `http://localhost:3000/?${process.env.AUTHORIZATION}`,
  NO_URL = '&type=foo&URL=notice-that-its-in-uppercase',
  NO_TYPE = '&url=foo&TYPE=notice-that-its-in-uppercase',
  BAD_GENERATOR = '&type=fluxor&url=http://example.com/',
  BAD_SHORTNAME = '&type=RESPEC&url=http://example.com/%3FshortName%3Ddiplodocus',
  NO_RESPEC = '&type=RESPEC&url=http://example.com/',
  SUCCESS1 = '&type=respec&url=https://w3c.github.io/manifest/',
  SUCCESS2 = '&type=respec&url=https://w3c.github.io/payment-request/',
  SUCCESS3 = '&type=respec&url=https://w3c.github.io/resource-hints/';

const FAILS_WITH = (done, expectedMessage = '{"error":"Both \'type\' and \'url\' are required."}', expectedCode = 500) =>
  (error, response, body) => {
    ASSERT.equal(error, null);
    ASSERT.equal(response.statusCode, expectedCode);
    if (expectedMessage instanceof RegExp)
      ASSERT.ok(body.match(expectedMessage));
    else
      ASSERT.equal(body, expectedMessage);
    done();
  }
;

const SUCCEEDS = (done) =>
  (error, response, body) => {
    ASSERT.equal(error, null);
    ASSERT.equal(response.statusCode, 200);
    ASSERT.equal(response.statusMessage, 'OK');
    done();
  };
;

let server;

describe('spec-generator', () => {

  before(() => {
    server = SPEC_GEN.start(PORT);
  });

  describe('fails when it should', () => {
    it('without parameters', (done) => REQUEST.get(BASE_URL, FAILS_WITH(done)));
    it('if there\'s no URL', (done) => REQUEST.get(BASE_URL + NO_URL, FAILS_WITH(done)));
    it('if there\'s no type', (done) => REQUEST.get(BASE_URL + NO_TYPE, FAILS_WITH(done)));
    it('if the generator is not valid', (done) => REQUEST.get(BASE_URL + BAD_GENERATOR, FAILS_WITH(done, '{"error":"Unknown generator: fluxor"}')));
    it('if the shortname is not valid', (done) => REQUEST.get(BASE_URL + BAD_SHORTNAME, FAILS_WITH(done, '{"error":"Not Found"}', 404)));
    it('if the URL does not point to a Respec document', (done) => REQUEST.get(BASE_URL + NO_RESPEC, FAILS_WITH(
      done,
      /That\ doesn't\ seem\ to\ be\ a\ ReSpec\ document\.\ Please\ check\ manually\:/
    )));
  });

  describe('succeeds when it should', () => {
    it('Web App Manifest ("appmanifest")', (done) => REQUEST.get(BASE_URL + SUCCESS1, SUCCEEDS(done)));
    it('Payment Request API ("payment-request")', (done) => REQUEST.get(BASE_URL + SUCCESS2, SUCCEEDS(done)));
    it('Resource Hints ("resource-hints")', (done) => REQUEST.get(BASE_URL + SUCCESS3, SUCCEEDS(done)));
  });

  after(() => server.close());

});
<|endoftext|>


<commit_before><commit_msg>ENH: Addition of test for user login and authentication<commit_after><|endoftext|>


<commit_before>import React from 'react';

import * as util from '../../../lib/util.js';

class NavBar extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      showNavMenu: false,
    };
    this.handleCompassClick = this.handleCompassClick.bind(this);
  }

  handleCompassClick(){
    !this.state.showNavMenu ?
      this.setState({showNavMenu: true}) :
      this.setState({showNavMenu: false});
  }

  render(){
    return(

        {util.renderIf(this.state.showNavMenu,

Projects

Community

About

Contact

)}

    );
  }
}

export default NavBar;
<commit_msg>merging to navbar branch<commit_after>import React from 'react';
import {Link} from 'react-router-dom';
import * as util from '../../../lib/util.js';

class NavBar extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      showNavMenu: false,
    };
    this.handleCompassClick = this.handleCompassClick.bind(this);
  }

  handleCompassClick(){
    !this.state.showNavMenu ?
      this.setState({showNavMenu: true}) :
      this.setState({showNavMenu: false});
  }

  render(){
    return(

        {util.renderIf(this.state.showNavMenu,

            <Link to='/projects'>Projects</Link>
            <Link to='/community'>Community</Link>
            <Link to='/about'>About</Link>
            <Link to='/contact'>Contact</Link>

)}

    );
  }
}

export default NavBar;
<|endoftext|>


<commit_before>define(['chai', 'Backbone.Advice', 'Mixin'], function(chai) {

	chai.should();

	var after = {
		getNumber: function() {
			this.number *= 2;
		}
	};

	var objMixin = {
		setDefaults: {
			number: 1
		},
		before: {
			getNumber: function () {
				this.number += 1;
			}
		},
		mixin: after
	};

	var fnMixin = function(options) {
		var temp = _.clone(objMixin);
		temp.clobber = {
			clobber: options.clobber
		};
		return temp;
	};

	describe('Backbone.Advice', function() {

		describe('#addMixin', function() {
			var A = function() {};
			Backbone.Advice.addMixin(A);
			it('should have properties added from the mixin', function() {
				A.should.have.property('mixin').and.be.a('function');
				A.should.have.property('addToObj').and.be.a('function');
				A.should.have.property('setDefaults').and.be.a('function');
				A.should.have.property('findVal').and.be.a('function');
				A.should.have.property('clobber').and.be.a('function');
				A.should.have.property('hasMixin').and.be.a('function');
			});
		});

		describe('create new object', function() {
			var A = function() {};
			Backbone.Advice.addMixin(A);
			a = new A();
			it('should have hasMixin function', function() {
				A.should.have.property('hasMixin').and.be.a('function');
			});
		});

		describe('#around', function() {
			var A = function() {};
			A.prototype = {
				number: 1,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			A.around('getNumber', function(orig) {
				return orig() + 1;
			});
			var a = new A();
			it('should multiply number is returned', function() {
				a.getNumber().should.equal(2);
			});
		});

		describe('#before', function() {
			var A = function() {};
			A.prototype = {
				number: 1,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			A.before('getNumber', objMixin.before.getNumber);
			var a = new A();
			var number = a.getNumber();
			it('should be applied before the number is returned', function() {
				number.should.equal(2);
			});
		});

		describe('#after', function() {
			var A = function() {};
			A.prototype = {
				number: 1,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			A.after('getNumber', after.getNumber);
			var a = new A();
			it('should alter the number after it is returned', function() {
				a.getNumber().should.equal(1);
				a.number.should.equal(2);
			});
		});

		describe('#mixin simple', function() {
			var A = function() {};
			A.prototype = {
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			A.mixin(objMixin);

			var a = new A();

			it('should apply the mixins from the object', function() {
				a.getNumber().should.equal(2);
				a.number.should.equal(4);
			});
		});

		describe('#mixin advanced', function() {
			var B = function() {};
			B.prototype = {
				number: 2,
				clobber: false,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(B);
			B.mixin(fnMixin, {
				clobber: true
			});

			var b = new B();

			it('should respect the default and options passed in', function() {
				b.clobber.should.be.true;
				b.getNumber().should.equal(3);
				b.number.should.equal(6);
			});
		});

		describe('#mixin more than once', function() {
			var A = function() {};
			A.prototype = {
				number: 1,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			var mixin = function() {
				this.before('getNumber', function() {
					this.number += 1;
				});
			};
			A.mixin([mixin, mixin]).mixin(mixin);
			var a = new A();
			it('should only applied once', function() {
				a.getNumber().should.equal(2);
			});
		});

		describe('#hasMixin', function() {
			var mixin = function(){};
			var mixin2 = function(){};
			var A = function(){};
			Backbone.Advice.addMixin(A);
			A.mixin(mixin);
			var a = new A();
			it('should have mixin applied to constructor', function() {
				A.hasMixin(mixin).should.be.true;
				A.hasMixin(mixin2).should.be.false;
			});
			it('should have mixin applied to instance', function() {
				a.hasMixin(mixin).should.be.true;
				a.hasMixin(mixin2).should.be.false;
			});
		});

		describe('inherit mixin through extend', function() {
			var mixin = function mixin() {};
			var mixin2 = function mixin2() {};
			var A = Backbone.View.extend({});
			it('should have mixin function', function() {
				A.should.have.property('mixin');
			});
			A.mixin(mixin);
			var a = new A();
			window.a = a;
			var B = A.extend();
			B.mixin(mixin2);
			var b = new B();
			it('should have only mixin', function() {
				A.hasMixin(mixin).should.be.true;
				A.hasMixin(mixin2).should.be.false;
				a.hasMixin(mixin).should.be.true;
				a.hasMixin(mixin2).should.be.false;
			});
			it('should have both mixins', function() {
				B.hasMixin(mixin).should.be.true;
				B.hasMixin(mixin2).should.be.true;
				b.hasMixin(mixin).should.be.true;
				b.hasMixin(mixin2).should.be.true;
			});
		});
	});

	describe('Backbone.Advice.Mixins', function() {
		describe('Mixin.all.overrideWithOptions', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.all.overrideWithOptions);
			var a = new A({
				foo: 'bar'
			});
			it('should gain any properties from the options object', function() {
				a.should.have.property('foo').and.equal('bar');
			});
		});

		describe('Mixin.view.makeSelectable', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.view.makeSelectable);
			var a = new A();
			it('should have selet and deselect methods', function() {
				a.should.have.property('select').and.be.a('function');
				a.should.have.property('deselect').and.be.a('function');
			});
			it('should be selectable', function() {
				a.should.have.property('selectable');
				a.should.have.property('isSelectable').and.be.a('function');
			});
			it('should not be selected initially', function() {
				a.isSelected().should.be.false;
			});
			it('should be selectable', function() {
				a.select();
				a.isSelected().should.be.true;
			});
			it('should be able to toggle selected', function() {
				a.toggleSelect();
				a.isSelected().should.be.false;
				a.toggleSelect();
				a.isSelected().should.be.true;
			});
		});

		describe('Mixin.view.expandable', function(){
			var A = Backbone.View.extend({}).mixin(Mixin.view.expandable);
			var a = new A();
			it('should have expand and collapse methods', function() {
				a.should.have.property('expand').and.be.a('function');
				a.should.have.property('collapse').and.be.a('function');
			});
			it('should be expandable', function() {
				a.should.have.property('expanded');
				a.should.have.property('isExpanded').and.be.a('function');
			});
			it('should be collapsed', function() {
				a.$el.hasClass('expanded').should.be.false;
				a.isExpanded().should.be.false
			});
			it('should expand', function() {
				a.expand();
				a.$el.hasClass('expanded').should.be.true;
				a.isExpanded().should.be.true
			});
			it('should collapse', function() {
				a.collapse();
				a.$el.hasClass('expanded').should.be.false;
				a.isExpanded().should.be.false
			});
		});

		describe('Mixin.view.makeFocusable', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.view.makeFocusable);
			var a = new A();
			it('should be focusable', function() {
				a.$el.appendTo(document.body);
				a.el.focus();
				a.isFocused().should.be.true;
				a.el.blur();
				a.isFocused().should.be.false;
				a.$el.remove();
			});
		});

		describe('Mixin.view.focusOnSelect', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.view.focusOnSelect);
			var a = new A();
			it('should not be focused or selected', function() {
				a.$el.appendTo(document.body);
				a.isSelected().should.be.false;
				a.isFocused().should.be.false;
			});
			it('should focus on select', function() {
				a.select();
				a.isFocused().should.be.true;
			});
			it('should blur on deselect', function() {
				a.deselect();
				a.isFocused().should.be.false;
				a.$el.remove();
			});
		});

		describe('Mixin.view.expandWhenSelected', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.view.expandWhenSelected);
			var a = new A();
			it('should not be focused or selected', function() {
				a.isSelected().should.be.false;
				a.isExpanded().should.be.false;
			});
			it('should focus on select', function() {
				a.select();
				a.isExpanded().should.be.true;
			});
			it('should blur on deselect', function() {
				a.deselect();
				a.isExpanded().should.be.false;
			});
		});
	});

});<commit_msg>more coverage<commit_after>define(['chai', 'Backbone.Advice', 'Mixin'], function(chai) {

	chai.should();

	var after = {
		getNumber: function() {
			this.number *= 2;
		}
	};

	var objMixin = {
		setDefaults: {
			number: 1
		},
		before: {
			getNumber: function () {
				this.number += 1;
			}
		},
		mixin: after,
		test: {
			test: true
		}
	};

	var fnMixin = function(options) {
		var temp = _.clone(objMixin);
		temp.clobber = {
			clobber: options.clobber
		};
		return temp;
	};

	describe('Backbone.Advice', function() {

		describe('#addMixin', function() {
			var A = function() {};
			Backbone.Advice.addMixin(A);
			it('should have properties added from the mixin', function() {
				A.should.have.property('mixin').and.be.a('function');
				A.should.have.property('addToObj').and.be.a('function');
				A.should.have.property('setDefaults').and.be.a('function');
				A.should.have.property('findVal').and.be.a('function');
				A.should.have.property('clobber').and.be.a('function');
				A.should.have.property('hasMixin').and.be.a('function');
			});
		});

		describe('create new object', function() {
			var A = function() {};
			Backbone.Advice.addMixin(A);
			a = new A();
			it('should have hasMixin function', function() {
				A.should.have.property('hasMixin').and.be.a('function');
			});
		});

		describe('#around', function() {
			var A = function() {};
			A.prototype = {
				number: 1,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			A.around('getNumber', function(orig) {
				return orig() + 1;
			});
			var a = new A();
			it('should multiply number is returned', function() {
				a.getNumber().should.equal(2);
			});
		});

		describe('#before', function() {
			var A = function() {};
			A.prototype = {
				number: 1,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			A.before('getNumber', objMixin.before.getNumber);
			var a = new A();
			var number = a.getNumber();
			it('should be applied before the number is returned', function() {
				number.should.equal(2);
			});
		});

		describe('#after', function() {
			var A = function() {};
			A.prototype = {
				number: 1,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			A.after('getNumber', after.getNumber);
			var a = new A();
			it('should alter the number after it is returned', function() {
				a.getNumber().should.equal(1);
				a.number.should.equal(2);
			});
		});

		describe('#mixin simple', function() {
			var A = function() {};
			A.prototype = {
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			A.mixin(objMixin);

			var a = new A();

			it('should apply the mixins from the object', function() {
				a.getNumber().should.equal(2);
				a.number.should.equal(4);
				a.test.test.should.equal(true);
			});
		});

		describe('#mixin advanced', function() {
			var B = function() {};
			B.prototype = {
				number: 2,
				clobber: false,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(B);
			B.mixin(fnMixin, {
				clobber: true
			});

			var b = new B();

			it('should respect the default and options passed in', function() {
				b.clobber.should.be.true;
				b.getNumber().should.equal(3);
				b.number.should.equal(6);
			});
		});

		describe('#mixin more than once', function() {
			var A = function() {};
			A.prototype = {
				number: 1,
				getNumber: function() {
					return this.number;
				}
			};
			Backbone.Advice.addMixin(A);
			var mixin = function() {
				this.before('getNumber', function() {
					this.number += 1;
				});
			};
			A.mixin([mixin, mixin]).mixin(mixin);
			var a = new A();
			it('should only applied once', function() {
				a.getNumber().should.equal(2);
			});
		});

		describe('#hasMixin', function() {
			var mixin = function(){};
			var mixin2 = function(){};
			var A = function(){};
			Backbone.Advice.addMixin(A);
			A.mixin(mixin);
			var a = new A();
			it('should have mixin applied to constructor', function() {
				A.hasMixin(mixin).should.be.true;
				A.hasMixin(mixin2).should.be.false;
			});
			it('should have mixin applied to instance', function() {
				a.hasMixin(mixin).should.be.true;
				a.hasMixin(mixin2).should.be.false;
			});
		});

		describe('inherit mixin through extend', function() {
			var mixin = function mixin() {};
			var mixin2 = function mixin2() {};
			var A = Backbone.View.extend({});
			it('should have mixin function', function() {
				A.should.have.property('mixin');
			});
			A.mixin(mixin);
			var a = new A();
			window.a = a;
			var B = A.extend();
			B.mixin(mixin2);
			var b = new B();
			it('should have only mixin', function() {
				A.hasMixin(mixin).should.be.true;
				A.hasMixin(mixin2).should.be.false;
				a.hasMixin(mixin).should.be.true;
				a.hasMixin(mixin2).should.be.false;
			});
			it('should have both mixins', function() {
				B.hasMixin(mixin).should.be.true;
				B.hasMixin(mixin2).should.be.true;
				b.hasMixin(mixin).should.be.true;
				b.hasMixin(mixin2).should.be.true;
			});
		});
	});

	describe('Backbone.Advice.Mixins', function() {
		describe('Mixin.all.overrideWithOptions', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.all.overrideWithOptions);
			var a = new A({
				foo: 'bar'
			});
			it('should gain any properties from the options object', function() {
				a.should.have.property('foo').and.equal('bar');
			});
		});

		describe('Mixin.view.makeSelectable', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.view.makeSelectable);
			var a = new A();
			it('should have selet and deselect methods', function() {
				a.should.have.property('select').and.be.a('function');
				a.should.have.property('deselect').and.be.a('function');
			});
			it('should be selectable', function() {
				a.should.have.property('selectable');
				a.should.have.property('isSelectable').and.be.a('function');
			});
			it('should not be selected initially', function() {
				a.isSelected().should.be.false;
			});
			it('should be selectable', function() {
				a.select();
				a.isSelected().should.be.true;
			});
			it('should be able to toggle selected', function() {
				a.toggleSelect();
				a.isSelected().should.be.false;
				a.toggleSelect();
				a.isSelected().should.be.true;
			});
		});

		describe('Mixin.view.expandable', function(){
			var A = Backbone.View.extend({}).mixin(Mixin.view.expandable);
			var a = new A();
			it('should have expand and collapse methods', function() {
				a.should.have.property('expand').and.be.a('function');
				a.should.have.property('collapse').and.be.a('function');
			});
			it('should be expandable', function() {
				a.should.have.property('expanded');
				a.should.have.property('isExpanded').and.be.a('function');
			});
			it('should be collapsed', function() {
				a.$el.hasClass('expanded').should.be.false;
				a.isExpanded().should.be.false
			});
			it('should expand', function() {
				a.expand();
				a.$el.hasClass('expanded').should.be.true;
				a.isExpanded().should.be.true
			});
			it('should collapse', function() {
				a.collapse();
				a.$el.hasClass('expanded').should.be.false;
				a.isExpanded().should.be.false
			});
		});

		describe('Mixin.view.makeFocusable', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.view.makeFocusable);
			var a = new A();
			it('should be focusable', function() {
				a.$el.appendTo(document.body);
				a.el.focus();
				a.isFocused().should.be.true;
				a.el.blur();
				a.isFocused().should.be.false;
				a.$el.remove();
			});
		});

		describe('Mixin.view.focusOnSelect', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.view.focusOnSelect);
			var a = new A();
			it('should not be focused or selected', function() {
				a.$el.appendTo(document.body);
				a.isSelected().should.be.false;
				a.isFocused().should.be.false;
			});
			it('should focus on select', function() {
				a.select();
				a.isFocused().should.be.true;
			});
			it('should blur on deselect', function() {
				a.deselect();
				a.isFocused().should.be.false;
				a.$el.remove();
			});
		});

		describe('Mixin.view.expandWhenSelected', function() {
			var A = Backbone.View.extend({}).mixin(Mixin.view.expandWhenSelected);
			var a = new A();
			it('should not be focused or selected', function() {
				a.isSelected().should.be.false;
				a.isExpanded().should.be.false;
			});
			it('should focus on select', function() {
				a.select();
				a.isExpanded().should.be.true;
			});
			it('should blur on deselect', function() {
				a.deselect();
				a.isExpanded().should.be.false;
			});
		});
	});

});<|endoftext|>