<commit_before>/* global describe, afterEach, it, expect */

var expect = require('chai').expect;  // jshint ignore:line
var StubGenerator = require('../lib/stub-generator');
var CachingBrowserify = require('../lib/caching-browserify');
var RSVP = require('rsvp');
RSVP.on('error', function(err){throw err;});
var fs = require('fs');
var path = require('path');
var broccoli = require('broccoli');
var quickTemp = require('quick-temp');
var copy = require('copy-dereference').sync;

var src = {};
var builder;

describe('Stub Generator', function() {

  beforeEach(function() {
    quickTemp.makeOrRemake(src, 'tmp');
    src.inputTree = path.join(src.tmp, 'inputTree');
    copy(path.join(__dirname, 'fixtures', 'stubs'), src.inputTree);
  });

  afterEach(function() {
    if (src.tmp) {
      quickTemp.remove(src, 'tmp');
    }
    if (builder) {
      return builder.cleanup();
    }
  });

  it('generates stub file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
    });
  });

  it('adds deps from new file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
      fs.writeFileSync(path.join(src.inputTree, 'new.js'), "import SomethingNew from \"npm:something-new\"\n");
      return builder.build();
    }).then(function(result){
      expectFile('browserify_stubs.js').toMatch('second.js').in(result);
    });
  });

  it('removes deps from deleted file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
      fs.unlinkSync(path.join(src.inputTree, 'sample.js'));
      return builder.build();
    }).then(function(result){
      expectFile('browserify_stubs.js').toMatch('third.js').in(result);
    });
  });

  it('adds deps in modified file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
      var was = fs.readFileSync(path.join(src.inputTree, 'sample.js'));
      was += "\nimport Additional from 'npm:additional-thing';";
      fs.writeFileSync(path.join(src.inputTree, 'sample.js'), was);
      return builder.build();
    }).then(function(result){
      expectFile('browserify_stubs.js').toMatch('fourth.js').in(result);
    });
  });

  it('removes deps in modified file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
      var was = fs.readFileSync(path.join(src.inputTree, 'inner', 'other.js'), 'utf-8');
      was = was.split("\n").slice(1).join("\n");
      fs.writeFileSync(path.join(src.inputTree, 'inner', 'other.js'), was);
      return builder.build();
    }).then(function(result){
      expectFile('browserify_stubs.js').toMatch('fifth.js').in(result);
    });
  });

});

describe('CachingBrowserify', function() {
  beforeEach(function() {
    quickTemp.makeOrRemake(src, 'tmp');
    src.inputTree = path.join(src.tmp, 'inputTree');
    copy(path.join(__dirname, 'fixtures', 'modules'), src.inputTree);
    src.entryTree = path.join(src.inputTree, 'src');
  });

  afterEach(function() {
    if (src.tmp) {
      quickTemp.remove(src, 'tmp');
    }
    if (builder) {
      return builder.cleanup();
    }
  });

  it('builds successfully', function() {
    var tree = new CachingBrowserify(src.entryTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle1.js').in(result);
    });
  });

  it('rebuilds when an npm module changes', function(){
    var tree = new CachingBrowserify(src.entryTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle1.js').in(result);
      var target = path.join(src.inputTree, 'node_modules', 'my-module', 'index.js');
      var code = fs.readFileSync(target, 'utf-8');
      code = code.replace('other.something()', 'other.something()+1');
      fs.writeFileSync(target, code);
      return builder.build();
    }).then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle2.js').in(result);
    });
  });

  it('rebuilds when the entry file changes', function(){
    var tree = new CachingBrowserify(src.entryTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle1.js').in(result);
      fs.unlinkSync(path.join(src.entryTree, 'browserify_stubs.js'));
      copy(path.join(src.entryTree, 'second_stubs.js'), path.join(src.entryTree, 'browserify_stubs.js'));
      return builder.build();
    }).then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle3.js').in(result);
    });
  });

});

function expectFile(filename) {
  var stripURL = false;
  var expectedFilename = filename;
  return {
      in: function(result) {
        var actualContent = fs.readFileSync(path.join(result.directory, filename), 'utf-8');
        fs.writeFileSync(path.join(__dirname, 'actual', expectedFilename), actualContent);

        var expectedContent;
        try {
          expectedContent = fs.readFileSync(path.join(__dirname, 'expected', expectedFilename), 'utf-8');
          if (stripURL) {
            expectedContent = expectedContent.replace(/\/\/# sourceMappingURL=.*$/, '');
          }

        } catch (err) {
          console.warn("Missing expcted file: " + path.join(__dirname, 'expected', filename));
        }
        expectSameFiles(actualContent, expectedContent, filename);
        return this;
      },
    notIn: function(result) {
      expect(fs.existsSync(path.join(result.directory, filename))).to.equal(false, filename + ' should not have been present');
      return this;
    },
    toMatch: function(expectedName) {
      expectedFilename = expectedName;
      return this;
    },
    withoutSrcURL: function() {
      stripURL = true;
      return this;
    }
  };
}

function expectSameFiles(actualContent, expectedContent, filename) {
  if (/\.map$/.test(filename)) {
    expect(JSON.parse(actualContent)).to.deep.equal(JSON.parse(expectedContent), 'discrepancy in ' + filename);
  } else {
    expect(actualContent).to.equal(expectedContent, 'discrepancy in ' + filename);
  }
}
<commit_msg>fix hint<commit_after>/* global describe, afterEach, it, expect, beforeEach */

var expect = require('chai').expect;  // jshint ignore:line
var StubGenerator = require('../lib/stub-generator');
var CachingBrowserify = require('../lib/caching-browserify');
var RSVP = require('rsvp');
RSVP.on('error', function(err){throw err;});
var fs = require('fs');
var path = require('path');
var broccoli = require('broccoli');
var quickTemp = require('quick-temp');
var copy = require('copy-dereference').sync;

var src = {};
var builder;

describe('Stub Generator', function() {

  beforeEach(function() {
    quickTemp.makeOrRemake(src, 'tmp');
    src.inputTree = path.join(src.tmp, 'inputTree');
    copy(path.join(__dirname, 'fixtures', 'stubs'), src.inputTree);
  });

  afterEach(function() {
    if (src.tmp) {
      quickTemp.remove(src, 'tmp');
    }
    if (builder) {
      return builder.cleanup();
    }
  });

  it('generates stub file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
    });
  });

  it('adds deps from new file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
      fs.writeFileSync(path.join(src.inputTree, 'new.js'), "import SomethingNew from \"npm:something-new\"\n");
      return builder.build();
    }).then(function(result){
      expectFile('browserify_stubs.js').toMatch('second.js').in(result);
    });
  });

  it('removes deps from deleted file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
      fs.unlinkSync(path.join(src.inputTree, 'sample.js'));
      return builder.build();
    }).then(function(result){
      expectFile('browserify_stubs.js').toMatch('third.js').in(result);
    });
  });

  it('adds deps in modified file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
      var was = fs.readFileSync(path.join(src.inputTree, 'sample.js'));
      was += "\nimport Additional from 'npm:additional-thing';";
      fs.writeFileSync(path.join(src.inputTree, 'sample.js'), was);
      return builder.build();
    }).then(function(result){
      expectFile('browserify_stubs.js').toMatch('fourth.js').in(result);
    });
  });

  it('removes deps in modified file', function() {
    var tree = new StubGenerator(src.inputTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result) {
      expectFile('browserify_stubs.js').toMatch('first.js').in(result);
      var was = fs.readFileSync(path.join(src.inputTree, 'inner', 'other.js'), 'utf-8');
      was = was.split("\n").slice(1).join("\n");
      fs.writeFileSync(path.join(src.inputTree, 'inner', 'other.js'), was);
      return builder.build();
    }).then(function(result){
      expectFile('browserify_stubs.js').toMatch('fifth.js').in(result);
    });
  });

});

describe('CachingBrowserify', function() {
  beforeEach(function() {
    quickTemp.makeOrRemake(src, 'tmp');
    src.inputTree = path.join(src.tmp, 'inputTree');
    copy(path.join(__dirname, 'fixtures', 'modules'), src.inputTree);
    src.entryTree = path.join(src.inputTree, 'src');
  });

  afterEach(function() {
    if (src.tmp) {
      quickTemp.remove(src, 'tmp');
    }
    if (builder) {
      return builder.cleanup();
    }
  });

  it('builds successfully', function() {
    var tree = new CachingBrowserify(src.entryTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle1.js').in(result);
    });
  });

  it('rebuilds when an npm module changes', function(){
    var tree = new CachingBrowserify(src.entryTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle1.js').in(result);
      var target = path.join(src.inputTree, 'node_modules', 'my-module', 'index.js');
      var code = fs.readFileSync(target, 'utf-8');
      code = code.replace('other.something()', 'other.something()+1');
      fs.writeFileSync(target, code);
      return builder.build();
    }).then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle2.js').in(result);
    });
  });

  it('rebuilds when the entry file changes', function(){
    var tree = new CachingBrowserify(src.entryTree);
    builder = new broccoli.Builder(tree);
    return builder.build().then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle1.js').in(result);
      fs.unlinkSync(path.join(src.entryTree, 'browserify_stubs.js'));
      copy(path.join(src.entryTree, 'second_stubs.js'), path.join(src.entryTree, 'browserify_stubs.js'));
      return builder.build();
    }).then(function(result){
      expectFile('browserify/browserify.js').toMatch('bundle3.js').in(result);
    });
  });

});

function expectFile(filename) {
  var stripURL = false;
  var expectedFilename = filename;
  return {
      in: function(result) {
        var actualContent = fs.readFileSync(path.join(result.directory, filename), 'utf-8');
        fs.writeFileSync(path.join(__dirname, 'actual', expectedFilename), actualContent);

        var expectedContent;
        try {
          expectedContent = fs.readFileSync(path.join(__dirname, 'expected', expectedFilename), 'utf-8');
          if (stripURL) {
            expectedContent = expectedContent.replace(/\/\/# sourceMappingURL=.*$/, '');
          }

        } catch (err) {
          console.warn("Missing expcted file: " + path.join(__dirname, 'expected', filename));
        }
        expectSameFiles(actualContent, expectedContent, filename);
        return this;
      },
    notIn: function(result) {
      expect(fs.existsSync(path.join(result.directory, filename))).to.equal(false, filename + ' should not have been present');
      return this;
    },
    toMatch: function(expectedName) {
      expectedFilename = expectedName;
      return this;
    },
    withoutSrcURL: function() {
      stripURL = true;
      return this;
    }
  };
}

function expectSameFiles(actualContent, expectedContent, filename) {
  if (/\.map$/.test(filename)) {
    expect(JSON.parse(actualContent)).to.deep.equal(JSON.parse(expectedContent), 'discrepancy in ' + filename);
  } else {
    expect(actualContent).to.equal(expectedContent, 'discrepancy in ' + filename);
  }
}
<|endoftext|>


<commit_before>var blobSupport = (function() {
  try {
    new Blob();
    return true
  } catch(e) {
    return false
  }
})();

asyncTest('populates response body', 2, function() {
  fetch('/hello').then(function(response) {
    equal(response.status, 200)
    return response.text()
  }).then(function(body) {
    equal(body, 'hi')
    start()
  })
})

asyncTest('sends request headers', 2, function() {
  fetch('/request', {
    headers: {
      'Accept': 'application/json',
      'X-Test': '42'
    }
  }).then(function(response) {
    return response.json()
  }).then(function(json) {
    equal(json.headers['accept'], 'application/json')
    equal(json.headers['x-test'], '42')
    start()
  })
})

asyncTest('parses response headers', 2, function() {
  fetch('/headers?' + new Date().getTime()).then(function(response) {
    equal(response.headers.get('Date'), 'Mon, 13 Oct 2014 21:02:27 GMT')
    equal(response.headers.get('Content-Type'), 'text/html; charset=utf-8')
    start()
  })
})

asyncTest('resolves promise on 500 error', 2, function() {
  fetch('/boom').then(function(response) {
    equal(response.status, 500)
    return response.text()
  }).then(function(body) {
    equal(body, 'boom')
    start()
  })
})

asyncTest('rejects promise for network error', 1, function() {
  fetch('/error').then(function(response) {
    ok(false, 'HTTP status ' + response.status + ' was treated as success')
    start()
  }).catch(function() {
    ok(true)
    start()
  })
})

asyncTest('handles 204 No Content response', 2, function() {
  fetch('/empty').then(function(response) {
    equal(response.status, 204)
    return response.text()
  }).then(function(body) {
    equal(body, '')
    start()
  })
})

asyncTest('resolves text promise', 1, function() {
  fetch('/hello').then(function(response) {
    return response.text()
  }).then(function(text) {
    equal(text, 'hi')
    start()
  })
})

asyncTest('parses form encoded response', 1, function() {
  fetch('/form').then(function(response) {
    return response.formData()
  }).then(function(form) {
    ok(form instanceof FormData, 'Parsed a FormData object')
    start()
  })
})

asyncTest('parses json response', 2, function() {
  fetch('/json').then(function(response) {
    return response.json()
  }).then(function(json) {
    equal(json.name, 'Hubot')
    equal(json.login, 'hubot')
    start()
  })
})

asyncTest('handles json parse error', 2, function() {
  fetch('/json-error').then(function(response) {
    return response.json()
  }).catch(function(error) {
    ok(error instanceof Error, 'JSON exception is an Error instance')
    ok(error.message, 'JSON exception has an error message')
    start()
  })
})

if (blobSupport) {
  asyncTest('resolves blob promise', 2, function() {
    fetch('/hello').then(function(response) {
      return response.blob()
    }).then(function(blob) {
      ok(blob instanceof Blob, 'blob is a Blob instance')
      equal(blob.size, 2)
      start()
    })
  })
}

asyncTest('post sets content-type header', 2, function() {
  fetch('/request', {
    method: 'post',
    body: new FormData()
  }).then(function(response) {
    return response.json()
  }).then(function(json) {
    equal(json.method, 'POST')
    ok(/^multipart\/form-data;/.test(json.headers['content-type']))
    start()
  })
})

if (blobSupport) {
  asyncTest('rejects blob promise after body is consumed', 2, function() {
    fetch('/hello').then(function(response) {
      response.blob()
      return response.blob()
    }).catch(function(error) {
      ok(error instanceof TypeError, 'Promise rejected after body consumed')
      ok(error.message === 'Body already consumed', 'Promise rejected for incorrect reason')
      start()
    })
  })
}

asyncTest('rejects json promise after body is consumed', 2, function() {
  fetch('/json').then(function(response) {
    response.json()
    return response.json()
  }).catch(function(error) {
    ok(error instanceof TypeError, 'Promise rejected after body consumed')
    ok(error.message === 'Body already consumed', 'Promise rejected for incorrect reason')
    start()
  })
})

asyncTest('rejects text promise after body is consumed', 2, function() {
  fetch('/hello').then(function(response) {
    response.text()
    return response.text()
  }).catch(function(error) {
    ok(error instanceof TypeError, 'Promise rejected after body consumed')
    ok(error.message === 'Body already consumed', 'Promise rejected for incorrect reason')
    start()
  })
})

asyncTest('supports HTTP PUT', 2, function() {
  fetch('/request', {
    method: 'put',
    body: {
      name: 'Hubot',
      title: 'Hubot Robawt',
    }
  }).then(function(response) {
    return response.json()
  }).then(function(request) {
    equal(request.method, 'PUT')
    equal(request.data, 'name=Hubot&title=Hubot+Robawt')
    start()
  })
})

asyncTest('supports HTTP PATCH', 2, function() {
  fetch('/request', {
    method: 'PATCH',
    body: {
      name: 'Hubot',
      title: 'Hubot Robawt',
    }
  }).then(function(response) {
    return response.json()
  }).then(function(request) {
    equal(request.method, 'PATCH')
    if (/PhantomJS/.test(navigator.userAgent)) {
      equal(request.data, '')
    } else {
      equal(request.data, 'name=Hubot&title=Hubot+Robawt')
    }
    start()
  })
})

asyncTest('supports HTTP DELETE', 2, function() {
  fetch('/request', {
    method: 'delete',
  }).then(function(response) {
    return response.json()
  }).then(function(request) {
    equal(request.method, 'DELETE')
    equal(request.data, '')
    start()
  })
})
<commit_msg>Posting object literal as request body is not supported.<commit_after>var blobSupport = (function() {
  try {
    new Blob();
    return true
  } catch(e) {
    return false
  }
})();

asyncTest('populates response body', 2, function() {
  fetch('/hello').then(function(response) {
    equal(response.status, 200)
    return response.text()
  }).then(function(body) {
    equal(body, 'hi')
    start()
  })
})

asyncTest('sends request headers', 2, function() {
  fetch('/request', {
    headers: {
      'Accept': 'application/json',
      'X-Test': '42'
    }
  }).then(function(response) {
    return response.json()
  }).then(function(json) {
    equal(json.headers['accept'], 'application/json')
    equal(json.headers['x-test'], '42')
    start()
  })
})

asyncTest('parses response headers', 2, function() {
  fetch('/headers?' + new Date().getTime()).then(function(response) {
    equal(response.headers.get('Date'), 'Mon, 13 Oct 2014 21:02:27 GMT')
    equal(response.headers.get('Content-Type'), 'text/html; charset=utf-8')
    start()
  })
})

asyncTest('resolves promise on 500 error', 2, function() {
  fetch('/boom').then(function(response) {
    equal(response.status, 500)
    return response.text()
  }).then(function(body) {
    equal(body, 'boom')
    start()
  })
})

asyncTest('rejects promise for network error', 1, function() {
  fetch('/error').then(function(response) {
    ok(false, 'HTTP status ' + response.status + ' was treated as success')
    start()
  }).catch(function() {
    ok(true)
    start()
  })
})

asyncTest('handles 204 No Content response', 2, function() {
  fetch('/empty').then(function(response) {
    equal(response.status, 204)
    return response.text()
  }).then(function(body) {
    equal(body, '')
    start()
  })
})

asyncTest('resolves text promise', 1, function() {
  fetch('/hello').then(function(response) {
    return response.text()
  }).then(function(text) {
    equal(text, 'hi')
    start()
  })
})

asyncTest('parses form encoded response', 1, function() {
  fetch('/form').then(function(response) {
    return response.formData()
  }).then(function(form) {
    ok(form instanceof FormData, 'Parsed a FormData object')
    start()
  })
})

asyncTest('parses json response', 2, function() {
  fetch('/json').then(function(response) {
    return response.json()
  }).then(function(json) {
    equal(json.name, 'Hubot')
    equal(json.login, 'hubot')
    start()
  })
})

asyncTest('handles json parse error', 2, function() {
  fetch('/json-error').then(function(response) {
    return response.json()
  }).catch(function(error) {
    ok(error instanceof Error, 'JSON exception is an Error instance')
    ok(error.message, 'JSON exception has an error message')
    start()
  })
})

if (blobSupport) {
  asyncTest('resolves blob promise', 2, function() {
    fetch('/hello').then(function(response) {
      return response.blob()
    }).then(function(blob) {
      ok(blob instanceof Blob, 'blob is a Blob instance')
      equal(blob.size, 2)
      start()
    })
  })
}

asyncTest('post sets content-type header', 2, function() {
  fetch('/request', {
    method: 'post',
    body: new FormData()
  }).then(function(response) {
    return response.json()
  }).then(function(json) {
    equal(json.method, 'POST')
    ok(/^multipart\/form-data;/.test(json.headers['content-type']))
    start()
  })
})

if (blobSupport) {
  asyncTest('rejects blob promise after body is consumed', 2, function() {
    fetch('/hello').then(function(response) {
      response.blob()
      return response.blob()
    }).catch(function(error) {
      ok(error instanceof TypeError, 'Promise rejected after body consumed')
      ok(error.message === 'Body already consumed', 'Promise rejected for incorrect reason')
      start()
    })
  })
}

asyncTest('rejects json promise after body is consumed', 2, function() {
  fetch('/json').then(function(response) {
    response.json()
    return response.json()
  }).catch(function(error) {
    ok(error instanceof TypeError, 'Promise rejected after body consumed')
    ok(error.message === 'Body already consumed', 'Promise rejected for incorrect reason')
    start()
  })
})

asyncTest('rejects text promise after body is consumed', 2, function() {
  fetch('/hello').then(function(response) {
    response.text()
    return response.text()
  }).catch(function(error) {
    ok(error instanceof TypeError, 'Promise rejected after body consumed')
    ok(error.message === 'Body already consumed', 'Promise rejected for incorrect reason')
    start()
  })
})

asyncTest('supports HTTP PUT', 2, function() {
  fetch('/request', {
    method: 'put',
    body: 'name=Hubot'
  }).then(function(response) {
    return response.json()
  }).then(function(request) {
    equal(request.method, 'PUT')
    equal(request.data, 'name=Hubot')
    start()
  })
})

asyncTest('supports HTTP PATCH', 2, function() {
  fetch('/request', {
    method: 'PATCH',
    body: 'name=Hubot'
  }).then(function(response) {
    return response.json()
  }).then(function(request) {
    equal(request.method, 'PATCH')
    if (/PhantomJS/.test(navigator.userAgent)) {
      equal(request.data, '')
    } else {
      equal(request.data, 'name=Hubot')
    }
    start()
  })
})

asyncTest('supports HTTP DELETE', 2, function() {
  fetch('/request', {
    method: 'delete',
  }).then(function(response) {
    return response.json()
  }).then(function(request) {
    equal(request.method, 'DELETE')
    equal(request.data, '')
    start()
  })
})
<|endoftext|>


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

const path = require('path');
const should = require('should');
const session = require('express-session');
const FirebaseStore = require(path.normalize(`${__dirname}/../lib/connect-session-firebase.js`))(session);

require('dotenv').config({ silent: true });

const store = new FirebaseStore({
  database: {
    serviceAccount: process.env.FIREBASE_SERVICE_ACCOUNT,
    databaseURL: process.env.FIREBASE_DATABASE_URL
  }
});

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

  after(() => {
    store.clear();
  });

  describe('Instantiation', () => {
    it('should be able to be created', () => {
      store.should.be.an.instanceOf(FirebaseStore);
    });
  });

  describe('Setting', () => {
    it('should set data correctly', done => {
      store.set('1234_#$[]', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, (err, res) => {
        if (err) throw err;

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

  describe('Getting', () => {
    before(() => {
      store.set('1234', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should get data correctly', done => {
      store.get('1234', (err, res) => {
        if (err) throw err;

        res.name.should.eql('tj');
        res.cookie.should.eql({
          maxAge: 2000
        });

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

  describe('Destroying', () => {
    before(() => {
      store.set('12345', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should destroy data correctly', done => {
      store.destroy('12345', (err, res) => {
        if (err) throw err;

        store.get('12345', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

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

  describe('Clearing', () => {
    before(() => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});

      store.set('abcdef', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should clear sessions correctly', done => {
      store.clear((err, res) => {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

          store.get('abcdef', (err, res) => {
            if (err) throw err;

            should.not.exist(res);

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

  describe('Reaping', () => {
    before(done => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: -2000
        }
      }, done);
    });

    it('should reap data correctly', done => {
      store.reap((err, res) => {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

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

  describe('Touching', () => {
    before(done => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, done);
    });

    it('should touch data correctly', done => {
      store.touch('abcd', {
        name: 'bn',
        cookie: {
          maxAge: 3000
        }
      }, function (err) {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          res.name.should.eql('tj');
          res.cookie.should.eql({
            maxAge: 3000
          });

          done();
        });
      });
    });
  });
});
<commit_msg>Add JS linting to mocha tests<commit_after>/* global describe, it, before, after */
'use strict';

const path = require('path');
const lint = require('mocha-eslint');
const should = require('should');
const session = require('express-session');
const FirebaseStore = require(path.normalize(`${__dirname}/../lib/connect-session-firebase.js`))(session);

require('dotenv').config({ silent: true });

const store = new FirebaseStore({
  database: {
    serviceAccount: process.env.FIREBASE_SERVICE_ACCOUNT,
    databaseURL: process.env.FIREBASE_DATABASE_URL
  }
});

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

  after(() => {
    store.clear();
  });

  lint(['**/*.js', '!node_modules/**']);

  describe('Instantiation', () => {
    it('should be able to be created', () => {
      store.should.be.an.instanceOf(FirebaseStore);
    });
  });

  describe('Setting', () => {
    it('should set data correctly', done => {
      store.set('1234_#$[]', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, (err, res) => {
        if (err) throw err;

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

  describe('Getting', () => {
    before(() => {
      store.set('1234', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should get data correctly', done => {
      store.get('1234', (err, res) => {
        if (err) throw err;

        res.name.should.eql('tj');
        res.cookie.should.eql({
          maxAge: 2000
        });

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

  describe('Destroying', () => {
    before(() => {
      store.set('12345', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should destroy data correctly', done => {
      store.destroy('12345', (err, res) => {
        if (err) throw err;

        store.get('12345', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

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

  describe('Clearing', () => {
    before(() => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});

      store.set('abcdef', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should clear sessions correctly', done => {
      store.clear((err, res) => {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

          store.get('abcdef', (err, res) => {
            if (err) throw err;

            should.not.exist(res);

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

  describe('Reaping', () => {
    before(done => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: -2000
        }
      }, done);
    });

    it('should reap data correctly', done => {
      store.reap((err, res) => {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

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

  describe('Touching', () => {
    before(done => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, done);
    });

    it('should touch data correctly', done => {
      store.touch('abcd', {
        name: 'bn',
        cookie: {
          maxAge: 3000
        }
      }, function (err) {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          res.name.should.eql('tj');
          res.cookie.should.eql({
            maxAge: 3000
          });

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


<commit_before>this.Luther = function(conf) {
  this.config = conf;

  this.run = function() {
   var Slack, autoMark, autoReconnect, slack, token;
  var request = require('request');
  Slack = require('slack-client');

  token = this.config.lutherbotToken;

  autoReconnect = true;

  autoMark = true;

  slack = new Slack(token, autoReconnect, autoMark);

  slack.on('open', function () {
    var channel, channels, group, groups, id, messages, unreads;
    channels = [];
    groups = [];
    unreads = slack.getUnreadCount();
    channels = (function () {
      var _ref, _results;
      _ref = slack.channels;
      _results = [];
      for (id in _ref) {
        channel = _ref[id];
        if (channel.is_member) {
          _results.push("#" + channel.name);
        }
      }
      return _results;
    })();
    groups = (function () {
      var _ref, _results;
      _ref = slack.groups;
      _results = [];
      for (id in _ref) {
        group = _ref[id];
        if (group.is_open && !group.is_archived) {
          _results.push(group.name);
        }
      }
      return _results;
    })();
    console.log("Welcome to Slack. You are @" + slack.self.name + " of " + slack.team.name);
    console.log('You are in: ' + channels.join(', '));
    console.log('As well as: ' + groups.join(', '));
    messages = unreads === 1 ? 'message' : 'messages';
    return console.log("You have " + unreads + " unread " + messages);
  });

  function containsText(text, isThisInside) {
    return text.toUpperCase().indexOf(isThisInside.toUpperCase()) >= 0;
  }

  function getVerse(text, callback) {
    var options = {
      proxy: process.env.http_proxy,
      url: 'http://lutherbot.herokuapp.com/getVerse?text=' + text,
      method: 'GET',
    };

    request.get(options, function (err, res, body) {
      callback(body);
    });
  }

  function isMessageToLuther(messageType, channel, text) {
    return messageType === 'message' && channel != null && text != null && (containsText(text, "luther") || containsText(text, "<@U08ANELP7>"));
  }

  function isMessageTimeRequest(message) {
    return containsText(message, "time") && containsText(message, ":");
  }

  var timeZones = [{
    name: 'cdt',
    houroffset: -6,
    minoffset: 0
  },{
    name: 'pdt',
    houroffset: -5,
    minoffset: 0
  },{
    name: 'at',
    houroffset: 9,
    minoffset: 30
  }];

  var timeList = [{
    name: "rtankersley",
    display: "Ryan",
    timezone: timeZones[0]
  },{
    name: "benjaminjrobin",
    display: "Ben",
    timezone: timeZones[0]
  },{
    name: "themast",
    display: "Derek",
    timezone: timeZones[1]
  },{
    name: "craigelliss",
    display: "Craig",
    timezone: timeZones[2]
  }]

  function getTime(text, colonIndex) {
    var one = 0;
    var two = 0;
    var three = 0;
    var four = 0;
    var five = null;
    var six = null;

    if(colonIndex - 1 > 0)
      two = text[colonIndex - 1];
    if(colonIndex - 2 > 0)
      one = text[colonIndex - 2];
    if(colonIndex + 1 < text.length)
      three = text[colonIndex + 1];
    if(colonIndex + 2 < text.length)
      four = text[colonIndex + 2];

    if(colonIndex + 4 < text.length) {
      five = text[colonIndex + 3];
      six = text[colonIndex + 4];
    }
    var hour = 0;
    var min = 0;
    if(one != ' ' && two != ' ' && !isNaN(Number(one)) && !isNaN(Number(two))) {
      hour = Number(one + two);
    }
    else if(two != ' ' && !isNaN(Number(two))) {
      hour = Number(two);
    }
    else
      return null;

    if(three != ' ' && four != ' ' && !isNaN(Number(three)) && !isNaN(Number(four)))
      min = Number(three + four);
    else
      return null;

    var isMorning = true;

    if(hour < 0 || hour > 24 || min < 0 || min > 59)
      return null;
    if(hour > 12) {
      hour -= 12;
      isMorning = false;
    }
    else if(five != null && (six === 'M' || six == 'm') &&  (five === 'P' || five === 'p')) {
        isMorning = false;
    }

    return {hour: hour, min: min, isMorning: isMorning};
  }
  slack.on('team_join', function(user) {

  });

  slack.on('message', function (message) {
    try {
      var channel, channelError, channelName, errors, response, text, textError, ts, messageType, typeError, user, userName;

      channel = slack.getChannelGroupOrDMByID(message.channel);
      user = slack.getUserByID(message.user);
      response = '';
      messageType = message.type;
      ts = message.ts;
      text = message.text;
      channelName = (channel != null ? channel.is_channel : void 0) ? '#' : '';
      channelName = channelName + (channel ? channel.name : 'UNKNOWN_CHANNEL');
      userName = (user != null ? user.name : void 0) != null ? "@" + user.name : "UNKNOWN_USER";

      if (isMessageToLuther(messageType, channel, text)) {
        if(isMessageTimeRequest(text)) {
          var userTime = null;
          for(var i = 0; i < timeList.length; i++)
          {
            if(timeList[i].name == user.name)
            {
              userTime = timeList[i].timezone;
              break;
            }
          }

          if(userTime == null)
            timeList[0].timezone;

            var colonIndexes = [];
            var newText = text;
            var cIndex = 0;
            var hasColon = false;
            do {
              cIndex = newText.indexOf(":");
              hasColon = cIndex > -1;
              if(hasColon)
              {
                if(colonIndexes.length > 0) {
                  cIndex += colonIndexes[colonIndexes.length - 1] + 1;
                }
                colonIndexes.push(cIndex);
                if(cIndex + 1 < newText.length)
                  newText = newText.substring(cIndex + 1);
                 else
                  hasColon = false;
              }
            } while(hasColon)

            var time = null;
            for(var ci = 0; ci < colonIndexes.length; ci++) {
              time = getTime(text, colonIndexes[ci]);
              if(time != null)
                break;
            }
            if(time != null)
            {
              var hour = time.hour;
              var minutes = time.min;
              var isMorning = time.isMorning;
              console.log(isMorning);

              if(!isNaN(hour) && !isNaN(minutes)) {
                var messageString = "";
                for(var i = 0; i < timeList.length; i++) {
                  var t = timeList[i];
                  var newHour =  hour - (userTime.houroffset - t.timezone.houroffset);
                  var newMinutes = minutes - (userTime.minoffset - t.timezone.minoffset);
                  if(newMinutes >= 60) {
                    newHour += 1;
                    newMinutes -= 60;
                  }
                  if(newMinutes < 0) {
                    newMinutes += 60;
                    newHour -= 1;
                  }
                  var newIsMorning = isMorning;

                  if(hour < newHour) {
                    for(var s = newHour; s > hour; s--) {
                      if(s % 12 == 0)
                        newIsMorning = !newIsMorning;
                    }
                  }
                  else if(hour > newHour) {
                    for(var s = newHour; s <hour; s++) {
                      if(s % 12 == 0)
                        newIsMorning = !newIsMorning;
                    }
                  }
                  while(newHour > 12) {
                    newHour -= 12;
                  }
                  while(newHour < 1) {
                   newHour += 12;
                  }
                  var hourString = newHour.toString();
                  while(hourString.length < 2) hourString = "0" + hourString;
                  var minString = newMinutes.toString();
                  while(minString.length < 2) minString = "0" + minString;
                  messageString += '*' + t.display + '* : ' + hourString + ':' + minString + ' ' + (newIsMorning ? 'AM' : 'PM') + '\n';
                }
                channel.send(messageString);
              }
            }
            else {
                channel.send("Were you trying to ask me to help with timezones?  If so, *you didn't send me time!*  Feel free ask again.");
            }
        }
        else {
          getVerse(text, function (data) {
            try {
              var verse = JSON.parse(data);
              console.log(verse);
              if(verse.ok) {

                channel.send("*" + verse.reference + "*\n>" + verse.text.replace(/\r\n/g, '\n\n>'));
              }
            } catch(err) {
              console.log(err);
            }
          });
        }
      }
      else {
        typeError = messageType !== 'message' ? "unexpected type " + messageType + "." : null;
        textError = text == null ? 'text was undefined.' : null;
        channelError = channel == null ? 'channel was undefined.' : null;
        errors = [typeError, textError, channelError].filter(function (element) {
          return element !== null;
        }).join(' ');
        return console.log("@" + slack.self.name + " could not respond. " + errors);
      }
    } catch(err) {

    }
  });

  slack.on('error', function (error) {
    return console.error("Error: " + error);
  });

  slack.login();
  }
};
<commit_msg>Fixed Craig's time and added space<commit_after>this.Luther = function(conf) {
  this.config = conf;

  this.run = function() {
   var Slack, autoMark, autoReconnect, slack, token;
  var request = require('request');
  Slack = require('slack-client');

  token = this.config.lutherbotToken;

  autoReconnect = true;

  autoMark = true;

  slack = new Slack(token, autoReconnect, autoMark);

  slack.on('open', function () {
    var channel, channels, group, groups, id, messages, unreads;
    channels = [];
    groups = [];
    unreads = slack.getUnreadCount();
    channels = (function () {
      var _ref, _results;
      _ref = slack.channels;
      _results = [];
      for (id in _ref) {
        channel = _ref[id];
        if (channel.is_member) {
          _results.push("#" + channel.name);
        }
      }
      return _results;
    })();
    groups = (function () {
      var _ref, _results;
      _ref = slack.groups;
      _results = [];
      for (id in _ref) {
        group = _ref[id];
        if (group.is_open && !group.is_archived) {
          _results.push(group.name);
        }
      }
      return _results;
    })();
    console.log("Welcome to Slack. You are @" + slack.self.name + " of " + slack.team.name);
    console.log('You are in: ' + channels.join(', '));
    console.log('As well as: ' + groups.join(', '));
    messages = unreads === 1 ? 'message' : 'messages';
    return console.log("You have " + unreads + " unread " + messages);
  });

  function containsText(text, isThisInside) {
    return text.toUpperCase().indexOf(isThisInside.toUpperCase()) >= 0;
  }

  function getVerse(text, callback) {
    var options = {
      proxy: process.env.http_proxy,
      url: 'http://lutherbot.herokuapp.com/getVerse?text=' + text,
      method: 'GET',
    };

    request.get(options, function (err, res, body) {
      callback(body);
    });
  }

  function isMessageToLuther(messageType, channel, text) {
    return messageType === 'message' && channel != null && text != null && (containsText(text, "luther") || containsText(text, "<@U08ANELP7>"));
  }

  function isMessageTimeRequest(message) {
    return containsText(message, "time") && containsText(message, ":");
  }

  var timeZones = [{
    name: 'cdt',
    houroffset: -6,
    minoffset: 0
  },{
    name: 'pdt',
    houroffset: -5,
    minoffset: 0
  },{
    name: 'at',
    houroffset: 10,
    minoffset: 30
  }];

  var timeList = [{
    name: "rtankersley",
    display: "Ryan",
    timezone: timeZones[0]
  },{
    name: "benjaminjrobin",
    display: "Ben",
    timezone: timeZones[0]
  },{
    name: "themast",
    display: "Derek",
    timezone: timeZones[1]
  },{
    name: "craigelliss",
    display: "Craig",
    timezone: timeZones[2]
  }]

  function getIsMorning(charOne, charTwo, charThree) {
    if(charOne === ' ') {
     charOne = charTwo;
     charTwo = charThree;
    }

    if(charOne != null && (charTwo === 'M' || charTwo == 'm') &&  (charOne === 'P' || charOne === 'p'))
        return false;

    return true;
  }
  function getTime(text, colonIndex) {
    var one = 0;
    var two = 0;
    var three = 0;
    var four = 0;
    var five = null;
    var six = null;
    var seven = null;

    if(colonIndex - 1 > 0)
      two = text[colonIndex - 1];
    if(colonIndex - 2 > 0)
      one = text[colonIndex - 2];
    if(colonIndex + 1 < text.length)
      three = text[colonIndex + 1];
    if(colonIndex + 2 < text.length)
      four = text[colonIndex + 2];

    if(colonIndex + 5 < text.length) {
      five = text[colonIndex + 3];
      six = text[colonIndex + 4];
      seven = text[colonIndex + 5];
    }
    if(colonIndex + 4 < text.length) {
      five = text[colonIndex + 3];
      six = text[colonIndex + 4];
    }
    var hour = 0;
    var min = 0;
    if(one != ' ' && two != ' ' && !isNaN(Number(one)) && !isNaN(Number(two))) {
      hour = Number(one + two);
    }
    else if(two != ' ' && !isNaN(Number(two))) {
      hour = Number(two);
    }
    else
      return null;

    if(three != ' ' && four != ' ' && !isNaN(Number(three)) && !isNaN(Number(four)))
      min = Number(three + four);
    else
      return null;

    var isMorning = true;

    if(hour < 0 || hour > 24 || min < 0 || min > 59)
      return null;
    if(hour > 12) {
      hour -= 12;
      isMorning = false;
    }
    else if(getIsMorning(five, six, seven)) {
        isMorning = false;
    }

    return {hour: hour, min: min, isMorning: isMorning};
  }
  slack.on('team_join', function(user) {

  });

  slack.on('message', function (message) {
    try {
      var channel, channelError, channelName, errors, response, text, textError, ts, messageType, typeError, user, userName;

      channel = slack.getChannelGroupOrDMByID(message.channel);
      user = slack.getUserByID(message.user);
      response = '';
      messageType = message.type;
      ts = message.ts;
      text = message.text;
      channelName = (channel != null ? channel.is_channel : void 0) ? '#' : '';
      channelName = channelName + (channel ? channel.name : 'UNKNOWN_CHANNEL');
      userName = (user != null ? user.name : void 0) != null ? "@" + user.name : "UNKNOWN_USER";

      if (isMessageToLuther(messageType, channel, text)) {
        if(isMessageTimeRequest(text)) {
          var userTime = null;
          for(var i = 0; i < timeList.length; i++)
          {
            if(timeList[i].name == user.name)
            {
              userTime = timeList[i].timezone;
              break;
            }
          }

          if(userTime == null)
            timeList[0].timezone;

            var colonIndexes = [];
            var newText = text;
            var cIndex = 0;
            var hasColon = false;
            do {
              cIndex = newText.indexOf(":");
              hasColon = cIndex > -1;
              if(hasColon)
              {
                if(colonIndexes.length > 0) {
                  cIndex += colonIndexes[colonIndexes.length - 1] + 1;
                }
                colonIndexes.push(cIndex);
                if(cIndex + 1 < newText.length)
                  newText = newText.substring(cIndex + 1);
                 else
                  hasColon = false;
              }
            } while(hasColon)

            var time = null;
            for(var ci = 0; ci < colonIndexes.length; ci++) {
              time = getTime(text, colonIndexes[ci]);
              if(time != null)
                break;
            }
            if(time != null)
            {
              var hour = time.hour;
              var minutes = time.min;
              var isMorning = time.isMorning;
              console.log(isMorning);

              if(!isNaN(hour) && !isNaN(minutes)) {
                var messageString = "";
                for(var i = 0; i < timeList.length; i++) {
                  var t = timeList[i];
                  var newHour =  hour - (userTime.houroffset - t.timezone.houroffset);
                  var newMinutes = minutes - (userTime.minoffset - t.timezone.minoffset);
                  if(newMinutes >= 60) {
                    newHour += 1;
                    newMinutes -= 60;
                  }
                  if(newMinutes < 0) {
                    newMinutes += 60;
                    newHour -= 1;
                  }
                  var newIsMorning = isMorning;

                  if(hour < newHour) {
                    for(var s = newHour; s > hour; s--) {
                      if(s % 12 == 0)
                        newIsMorning = !newIsMorning;
                    }
                  }
                  else if(hour > newHour) {
                    for(var s = newHour; s <hour; s++) {
                      if(s % 12 == 0)
                        newIsMorning = !newIsMorning;
                    }
                  }
                  while(newHour > 12) {
                    newHour -= 12;
                  }
                  while(newHour < 1) {
                   newHour += 12;
                  }
                  var hourString = newHour.toString();
                  while(hourString.length < 2) hourString = "0" + hourString;
                  var minString = newMinutes.toString();
                  while(minString.length < 2) minString = "0" + minString;
                  messageString += '*' + t.display + '* : ' + hourString + ':' + minString + ' ' + (newIsMorning ? 'AM' : 'PM') + '\n';
                }
                channel.send(messageString);
              }
            }
            else {
                channel.send("Were you wanting help with timezones?  If so, *you didn't send me time!*  Feel free ask again.");
            }
        }
        else {
          getVerse(text, function (data) {
            try {
              var verse = JSON.parse(data);
              console.log(verse);
              if(verse.ok) {

                channel.send("*" + verse.reference + "*\n>" + verse.text.replace(/\r\n/g, '\n\n>'));
              }
            } catch(err) {
              console.log(err);
            }
          });
        }
      }
      else {
        typeError = messageType !== 'message' ? "unexpected type " + messageType + "." : null;
        textError = text == null ? 'text was undefined.' : null;
        channelError = channel == null ? 'channel was undefined.' : null;
        errors = [typeError, textError, channelError].filter(function (element) {
          return element !== null;
        }).join(' ');
        return console.log("@" + slack.self.name + " could not respond. " + errors);
      }
    } catch(err) {

    }
  });

  slack.on('error', function (error) {
    return console.error("Error: " + error);
  });

  slack.login();
  }
};
<|endoftext|>


<commit_before>var util = require('../lib/util')
  , assert = require('assert')
  ;

describe('Library', function() {
  it('parseUrl works', function() {
    ins = [
      '/',
      '/csv/cut 1/'
    ];
    exp = [
      [{
        operator: 'none'
      }],
      [
        {
          operator: 'incsv',
          options: ''
        },
        {
          operator: 'cut',
          options: '1'
        },
        {
          operator: 'outcsv',
          options: ''
        }
      ]
    ];
    ins.forEach(function(path, idx) {
      var out = util.parseUrl(path);
      assert.deepEqual(out, exp[idx]);
    });

    var query = { abc: '111' };
    var out = util.parseUrl('/csv $abc/', query);
    var exp = [
      {
        operator: 'incsv',
        options: '111'
      },
      {
        operator: 'outcsv',
        options: ''
      }
    ];
    assert.deepEqual(out, exp);
  });
});

<commit_msg>[test][xs]: remove accidentially added and broken test.<commit_after>var util = require('../lib/util')
  , assert = require('assert')
  ;

describe('Library', function() {
  it('parseUrl works', function() {
    ins = [
      '/'
      , '/csv/cut 1/'
    ];
    exp = [
      [{
        operator: 'none'
      }]
      , [
        {
          operator: 'incsv',
          options: ''
        },
        {
          operator: 'cut',
          options: '1'
        },
        {
          operator: 'outcsv',
          options: ''
        }
      ]
    ];
    ins.forEach(function(path, idx) {
      var out = util.parseUrl(path);
      assert.deepEqual(out, exp[idx]);
    });

    var query = { abc: '111' };
    var out = util.parseUrl('/csv $abc/', query);
    var exp = [
      {
        operator: 'incsv',
        options: '111'
      },
      {
        operator: 'outcsv',
        options: ''
      }
    ];
    assert.deepEqual(out, exp);
  });
});

<|endoftext|>


<commit_before>var webrtc = new SimpleWebRTC({
	// we don't do video
	localVideoEl: '',
	remoteVideosEl: '',
		// dont ask for camera access
	autoRequestMedia: false,
		// dont negotiate media
	receiveMedia: {
		mandatory: {
			OfferToReceiveAudio: false,
			OfferToReceiveVideo: false
		}
	}
});

var positions = [];
var players = [];
var rooms = [];

// join without waiting for media
webrtc.joinRoom('Lobby225346');

// called when a peer is created
webrtc.on('createdPeer', function (peer) {
	console.log('createdPeer', peer);
	var channel = peer.getDataChannel("message");
	peer.on('channelClose', function (channel, error) {
		console.log("Losed data channel", channel, error);
		console.log("Should remove player");
	});

	//handle incoming data
	peer.on('channelMessage', function (peer, channel, msg) {
		// check type, has to be json
		if(msg.type === "json"){
			doStuff(peer, msg.payload);
		}
	});

	peer.name = "Guest";
	updateUser();
	printPlayer();
});

webrtc.on('joinedRoom', function (room) {
	console.log("entered room " + room);
});

function printPlayer(){
	var div = document.getElementById("peers");
	var allPeers = webrtc.webrtc.peers;
	div.innerHTML = "";
	for (var i = 0; i < allPeers.length; i++){
		div.innerHTML += allPeers[i].name + "
";
	}
}
function printRoom(){
	var div = document.getElementById("roomList");
	div.innerHTML = "";
	for (var i = 0; i < rooms.length; i++){
		div.innerHTML += rooms[i] + "
";
	}
}

function updateUser(){
	var name = document.getElementById("username").value;
	if (name === "")
		name = "Guest";
	sendAll({msg: "Hi, I changed my name to" + name, job: "associate", name: name});
	document.getElementById("nickname").innerHTML = name;
}

function updateRoom(){
  var room = document.getElementById("room").value;
	if (room !== ""){
	  sendAll({msg: "I created the room " + room, job: "createRoom", room: room});
  }
}

//send a json to a peer
function sendPeer(peer, data){
	//create data channel
	var channel = peer.getDataChannel("message");

	var isOpen = peer.sendDirectly("message", "json", data);
	if(isOpen){}
		//console.log("Data send");
	else{
		//retry when channel is open
		var saveOldOnopen = channel.onopen;
		channel.onopen = function() {
			sendPeer(peer, data);
			channel.onopen = saveOldOnopen;
		}
		console.log("Problem sending data");
	}
}

//send a json to all peers
function sendAll(data){
	var peers = webrtc.webrtc.peers;
	for (var i = 0; i < peers.length; i++) {
		sendPeer(peers[i], data);
	}
}

function doStuff(peer, data){
	switch (data.job) {
		case "posInit":
			players.push({id: peer.id, rnd: data.rnd});
			if(players.length === 4)
				sortPlayer();
			break;
		case "move":
			//console.log(data);
			movePaddle(peer.id, data.direction);
			break;
    case "associate":
			peer.name = data.name;
			printPlayer();
    case "createRoom":
      rooms.push(data.room);
      printRoom();
		default:
			console.log(data);
	}
	//y = data.y;
	//console.log(y);
}
<commit_msg>[feat] add rooms<commit_after>var webrtc = new SimpleWebRTC({
	// we don't do video
	localVideoEl: '',
	remoteVideosEl: '',
		// dont ask for camera access
	autoRequestMedia: false,
		// dont negotiate media
	receiveMedia: {
		mandatory: {
			OfferToReceiveAudio: false,
			OfferToReceiveVideo: false
		}
	}
});

var positions = [];
var players = [];
var rooms = {};

// join without waiting for media
webrtc.joinRoom('Lobby225346');

// called when a peer is created
webrtc.on('createdPeer', function (peer) {
	console.log('createdPeer', peer);
	var channel = peer.getDataChannel("message");
	peer.on('channelClose', function (channel, error) {
		console.log("Losed data channel", channel, error);
		console.log("Should remove player");
	});

	//handle incoming data
	peer.on('channelMessage', function (peer, channel, msg) {
		// check type, has to be json
		if(msg.type === "json"){
			doStuff(peer, msg.payload);
		}
	});

	peer.name = "Guest";
	updateUser();
  //updateRoom();
	printPlayer();
});

webrtc.on('joinedRoom', function (room) {
	console.log("entered room " + room);
});

function printPlayer(){
	var div = document.getElementById("peers");
	var allPeers = webrtc.webrtc.peers;
	div.innerHTML = "";
	for (var i = 0; i < allPeers.length; i++){
		div.innerHTML += allPeers[i].name + "
";
	}
}
function printRoom(){
	var div = document.getElementById("roomList");
	div.innerHTML = "";
  console.log(rooms);
	for (el in rooms){
    console.log(el);
		div.innerHTML += el + "
";
	}
}

function updateUser(){
	var name = document.getElementById("username").value;
	if (name === "")
		name = "Guest";
	sendAll({msg: "Hi, I changed my name to" + name, job: "associate", name: name});
	document.getElementById("nickname").innerHTML = name;
}

function updateRoom(){
  var room = document.getElementById("room").value;
	if (room != "" && room != undefined){
	  sendAll({msg: "I created the room " + room, job: "createRoom", room: room});
  }
}

//send a json to a peer
function sendPeer(peer, data){
	//create data channel
	var channel = peer.getDataChannel("message");

	var isOpen = peer.sendDirectly("message", "json", data);
	if(isOpen){}
		//console.log("Data send");
	else{
		//retry when channel is open
		var saveOldOnopen = channel.onopen;
		channel.onopen = function() {
			sendPeer(peer, data);
			channel.onopen = saveOldOnopen;
		}
		console.log("Problem sending data");
	}
}

//send a json to all peers
function sendAll(data){
	var peers = webrtc.webrtc.peers;
	for (var i = 0; i < peers.length; i++) {
		sendPeer(peers[i], data);
	}
}

function doStuff(peer, data){
	switch (data.job) {
		case "posInit":
			players.push({id: peer.id, rnd: data.rnd});
			if(players.length === 4)
				sortPlayer();
			break;
		case "move":
			//console.log(data);
			movePaddle(peer.id, data.direction);
			break;
    case "associate":
			peer.name = data.name;
			printPlayer();
      break;
    case "createRoom":
      console.log("Rooms added", data.room);
      rooms[data.room] = true;
      printRoom();
      break;
		default:
			console.log(data);
	}
	//y = data.y;
	//console.log(y);
}
<|endoftext|>


<commit_before>var debug = require('debug')('vary');
var should = require('should');
var fs = require('fs');
var URL = require('url');
var express = require('express');

var runner = require('../lib/spawner');
var common = require('./common');

var tag = require('..').tag;

var ports = {
	app: 3000,
	ngx: 3001,
	memc: 3002
};

describe("Vary", function suite() {
	var servers, app;
	var testPath = '/vary-test';
	var testNegotiation = '/nego';
	var counters = {};

	function count(uri, inc) {
		if (typeof uri != "string") {
			if (uri.get) uri = uri.protocol + '://' + uri.get('Host') + uri.path;
			else uri = URL.format(Object.assign({
				protocol: 'http',
				hostname: 'localhost',
				pathname: uri.path
			}, uri));
		}
		var counter = counters[uri];
		if (counter == null) counter = counters[uri] = 0;
		if (inc) counters[uri] += inc;
		return counters[uri];
	}

	before(function(done) {
		servers = runner(ports, done);

		app = express();
		app.server = app.listen(ports.app);

		app.get(testPath, tag('app'), function(req, res, next) {
			res.vary('User-Agent');
			res.set('User-Agent', req.get('user-agent').includes('Firefox') ? 1 : 2);
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});

		app.get(testNegotiation, tag('app'), function(req, res, next) {
			res.vary('Accept');
			count(req, 1);
			if (req.accepts('xml')) {
				res.type('application/xml');
				res.send('<xml></xml>');
			} else if (req.accepts('json')) {
				res.json({xml: true});
			}
		});
	});

	after(function(done) {
		app.server.close();
		servers.close(done);
	});

	beforeEach(function() {
		counters = {};
	});

	it("should vary upon two groups of user-agent", function() {
		var agent1 = 'Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0';
		var agent2 = 'Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/42.0';
		var agent3 = 'Mozilla/5.0';
		var headers = {
			'User-Agent': agent1
		};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPath
		};
		return common.get(req).then(function() {
			headers['User-Agent'] = agent2;
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept-Encoding, User-Agent');
			res.headers.should.have.property('user-agent', '1');
			headers['User-Agent'] = agent1;
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept-Encoding, User-Agent');
			res.headers.should.have.property('user-agent', '1');
			headers['User-Agent'] = agent2;
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept-Encoding, User-Agent');
			res.headers.should.have.property('user-agent', '1');
			count(req).should.equal(2);
			headers['User-Agent'] = agent3;
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept-Encoding, User-Agent');
			res.headers.should.have.property('user-agent', '2');
			count(req).should.equal(3);
		});
	});

	it("should vary upon Accept, Content-Type", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testNegotiation
		};
		req.headers.Accept = "application/xml";
		return common.get(req).then(function() {
			req.headers.Accept = "application/json";
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept');
			res.headers.should.have.property('content-type', 'application/json; charset=utf-8');
			req.headers.Accept = "application/xml";
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept');
			res.headers.should.have.property('content-type', 'application/xml; charset=utf-8');
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept');
			res.headers.should.have.property('content-type', 'application/xml; charset=utf-8');
			count(req).should.equal(2);
			req.headers.Accept = "application/json";
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept');
			res.headers.should.have.property('content-type', 'application/json; charset=utf-8');
			count(req).should.equal(2);
		});
	});
});
<commit_msg>Test vary accept-name<commit_after>var debug = require('debug')('vary');
var should = require('should');
var fs = require('fs');
var URL = require('url');
var express = require('express');

var runner = require('../lib/spawner');
var common = require('./common');

var tag = require('..').tag;

var ports = {
	app: 3000,
	ngx: 3001,
	memc: 3002
};

describe("Vary", function suite() {
	var servers, app;
	var testPath = '/vary-test';
	var testNegotiation = '/nego';
	var testLanguage = "/lang";
	var counters = {};

	function count(uri, inc) {
		if (typeof uri != "string") {
			if (uri.get) uri = uri.protocol + '://' + uri.get('Host') + uri.path;
			else uri = URL.format(Object.assign({
				protocol: 'http',
				hostname: 'localhost',
				pathname: uri.path
			}, uri));
		}
		var counter = counters[uri];
		if (counter == null) counter = counters[uri] = 0;
		if (inc) counters[uri] += inc;
		return counters[uri];
	}

	before(function(done) {
		servers = runner(ports, done);

		app = express();
		app.server = app.listen(ports.app);

		app.get(testPath, tag('app'), function(req, res, next) {
			res.vary('User-Agent');
			res.set('User-Agent', req.get('user-agent').includes('Firefox') ? 1 : 2);
			count(req, 1);
			res.send({
				value: (req.path || '/').substring(1),
				date: new Date()
			});
		});

		app.get(testNegotiation, tag('app'), function(req, res, next) {
			res.vary('Accept');
			count(req, 1);
			if (req.accepts('xml')) {
				res.type('application/xml');
				res.send('<xml></xml>');
			} else if (req.accepts('json')) {
				res.json({xml: true});
			}
		});

		app.get(testLanguage, tag('app'), function(req, res, next) {
			res.vary('Accept-Language');
			count(req, 1);
			var langs = ['en', 'fr'];
			if (req.acceptsLanguages(langs) == 'en') {
				res.set('Content-Language', 'en');
				res.send('Good !');
			} else if (req.acceptsLanguages(langs) == 'fr') {
				res.set('Content-Language', 'fr');
				res.send('Bien !');
			} else {
				res.set('Content-Language', 'pt');
				res.send('Bem !');
			}
		});
	});

	after(function(done) {
		app.server.close();
		servers.close(done);
	});

	beforeEach(function() {
		counters = {};
	});

	it("should vary upon two groups of user-agent", function() {
		var agent1 = 'Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0';
		var agent2 = 'Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/42.0';
		var agent3 = 'Mozilla/5.0';
		var headers = {
			'User-Agent': agent1
		};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testPath
		};
		return common.get(req).then(function() {
			headers['User-Agent'] = agent2;
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept-Encoding, User-Agent');
			res.headers.should.have.property('user-agent', '1');
			headers['User-Agent'] = agent1;
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept-Encoding, User-Agent');
			res.headers.should.have.property('user-agent', '1');
			headers['User-Agent'] = agent2;
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept-Encoding, User-Agent');
			res.headers.should.have.property('user-agent', '1');
			count(req).should.equal(2);
			headers['User-Agent'] = agent3;
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept-Encoding, User-Agent');
			res.headers.should.have.property('user-agent', '2');
			count(req).should.equal(3);
		});
	});

	it("should vary upon Accept, Content-Type", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testNegotiation
		};
		req.headers.Accept = "application/xml";
		return common.get(req).then(function() {
			req.headers.Accept = "application/json";
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept');
			res.headers.should.have.property('content-type', 'application/json; charset=utf-8');
			req.headers.Accept = "application/xml";
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept');
			res.headers.should.have.property('content-type', 'application/xml; charset=utf-8');
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept');
			res.headers.should.have.property('content-type', 'application/xml; charset=utf-8');
			count(req).should.equal(2);
			req.headers.Accept = "application/json";
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept');
			res.headers.should.have.property('content-type', 'application/json; charset=utf-8');
			count(req).should.equal(2);
		});
	});

	it("should vary upon Accept-Language, Content-Language", function() {
		var headers = {};
		var req = {
			headers: headers,
			port: ports.ngx,
			path: testLanguage
		};
		var english = "fr;q=0.8, en, pt";
		var french = "fr;q=0.8, en;q=0.7, pt;q=0.5";
		req.headers['Accept-Language'] = english;
		return common.get(req).then(function(res) {
			res.headers.should.have.property('vary', 'Accept-Language');
			res.headers.should.have.property('content-language', 'en');
			req.headers['Accept-Language'] = french;
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept-Language');
			res.headers.should.have.property('content-language', 'fr');
			req.headers['Accept-Language'] = english;
			return common.get(req);
		}).then(function(res) {
			count(req).should.equal(2);
			res.headers.should.have.property('vary', 'Accept-Language');
			res.headers.should.have.property('content-language', 'en');
			req.headers['Accept-Language'] = french;
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept-Language');
			res.headers.should.have.property('content-language', 'fr');
			count(req).should.equal(2);
			req.headers['Accept-Language'] = "fr;q=0.8, en;q=0.9"; // another english
			return common.get(req);
		}).then(function(res) {
			res.headers.should.have.property('vary', 'Accept-Language');
			res.headers.should.have.property('content-language', 'en');
			count(req).should.equal(3);
		});
	});
});
<|endoftext|>


<commit_before>(function() {

  var view;

  module("Backbone.View", {

    setup: function() {
      view = new Backbone.View({
        id        : 'test-view',
        className : 'test-view',
        other     : 'non-special-option'
      });
    }

  });

  test("constructor", 3, function() {
    equal(view.el.id, 'test-view');
    equal(view.el.className, 'test-view');
    equal(view.el.other, void 0);
  });

  test("$", 2, function() {
    var view = new Backbone.View;
    view.setElement('
test
');
    var result = view.$('a b');

    strictEqual(result[0].innerHTML, 'test');
    ok(result.length === +result.length);
  });

  test("_setEl", 2, function() {
    view._setEl('
', {id: 'test-div'});
    strictEqual(view.el.tagName.toLowerCase(), 'div');
    strictEqual(view.el.id, 'test-div');
  });

  test("jQuery", function() {
    var view = new Backbone.View;
    view.setElement('
test
');

    if (Backbone.$) {
      ok(view.$el instanceof Backbone.$);
      equal(view.$el[0], view.el);
    } else {
      ok(view.el.nodeType === 1);
    }
  });

  test("initialize", 1, function() {
    var View = Backbone.View.extend({
      initialize: function() {
        this.one = 1;
      }
    });

    strictEqual(new View().one, 1);
  });

  test("delegateEvents", 6, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    var events = {'click h1': 'increment'};

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 1);

    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 2);

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 3);
    equal(counter2, 3);
  });

  test("delegate", 2, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    view.delegate('click', 'h1', view.increment);
    view.delegate('click', view.increment);

    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 1);
  });

  test("delegateEvents allows functions for callbacks", 3, function() {
    var view = new Backbone.View({el: '

'});
    view.counter = 0;

    var events = {
      click: function() {
        this.counter++;
      }
    };

    view.delegateEvents(events);
    view.$el.trigger('click');
    equal(view.counter, 1);

    view.$el.trigger('click');
    equal(view.counter, 2);

    view.delegateEvents(events);
    view.$el.trigger('click');
    equal(view.counter, 3);
  });

  test("delegateEvents ignore undefined methods", 0, function() {
    var view = new Backbone.View({el: '

'});
    view.delegateEvents({'click': 'undefinedMethod'});
    view.$el.trigger('click');
  });

  test("undelegateEvents", 6, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    var events = {'click h1': 'increment'};

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 1);

    view.undelegateEvents();
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 2);

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 3);
  });

  test("_ensureElement with DOM node el", 1, function() {
    var View = Backbone.View.extend({
      el: document.body
    });

    equal(new View().el, document.body);
  });

  test("_ensureElement with string el", 3, function() {
    var View = Backbone.View.extend({
      el: "body"
    });
    strictEqual(new View().el, document.body);

    View = Backbone.View.extend({
      el: "#testElement > h1"
    });
    strictEqual(new View().el, $("#testElement > h1").get(0));

    View = Backbone.View.extend({
      el: "#nonexistent"
    });
    ok(!new View().el);
  });

  test("with className and id functions", 2, function() {
    var View = Backbone.View.extend({
      className: function() {
        return 'className';
      },
      id: function() {
        return 'id';
      }
    });

    strictEqual(new View().el.className, 'className');
    strictEqual(new View().el.id, 'id');
  });

  test("with attributes", 2, function() {
    var View = Backbone.View.extend({
      attributes: {
        id: 'id',
        'class': 'class'
      }
    });

    strictEqual(new View().el.className, 'class');
    strictEqual(new View().el.id, 'id');
  });

  test("with attributes as a function", 1, function() {
    var View = Backbone.View.extend({
      attributes: function() {
        return {'class': 'dynamic'};
      }
    });

    strictEqual(new View().el.className, 'dynamic');
  });

  test("multiple views per element", 3, function() {
    var count = 0;
    var $el = $('

');

    var View = Backbone.View.extend({
      el: $el,
      events: {
        click: function() {
          count++;
        }
      }
    });

    var view1 = new View;
    $el.trigger("click");
    equal(1, count);

    var view2 = new View;
    $el.trigger("click");
    equal(3, count);

    view1.delegateEvents();
    $el.trigger("click");
    equal(5, count);
  });

  test("custom events, with namespaces", 2, function() {
    var count = 0;

    var View = Backbone.View.extend({
      el: $('body'),
      events: function() {
        return {"fake$event.namespaced": "run"};
      },
      run: function() {
        count++;
      }
    });

    var view = new View;
    $('body').trigger('fake$event').trigger('fake$event');
    equal(count, 2);

    $('body').off('.namespaced');
    $('body').trigger('fake$event');
    equal(count, 2);
  });

  test("#1048 - setElement uses provided object.", 2, function() {
    var $el = $('body');

    var view = new Backbone.View({el: $el});
    ok(view.$el === $el);

    view.setElement($el = $($el));
    ok(view.$el === $el);
  });

  test("#986 - Undelegate before changing element.", 1, function() {
    var button1 = $('<button></button>');
    var button2 = $('<button></button>');

    var View = Backbone.View.extend({
      events: {
        click: function(e) {
          ok(view.el === e.target);
        }
      }
    });

    var view = new View({el: button1});
    view.setElement(button2);

    button1.trigger('click');
    button2.trigger('click');
  });

  test("#1172 - Clone attributes object", 2, function() {
    var View = Backbone.View.extend({
      attributes: {foo: 'bar'}
    });

    var view1 = new View({id: 'foo'});
    strictEqual(view1.el.id, 'foo');

    var view2 = new View();
    ok(!view2.el.id);
  });

  test("#1228 - tagName can be provided as a function", 1, function() {
    var View = Backbone.View.extend({
      tagName: function() {
        return 'p';
      }
    });

    ok(new View().el.tagName.toLowerCase() == 'p');
  });

  test("views stopListening", 0, function() {
    var View = Backbone.View.extend({
      initialize: function() {
        this.listenTo(this.model, 'all x', function(){ ok(false); });
        this.listenTo(this.collection, 'all x', function(){ ok(false); });
      }
    });

    var view = new View({
      model: new Backbone.Model,
      collection: new Backbone.Collection
    });

    view.stopListening();
    view.model.trigger('x');
    view.collection.trigger('x');
  });

  test("Provide function for el.", 2, function() {
    var View = Backbone.View.extend({
      el: function() {
        return "

";
      }
    });

    var view = new View;
    ok(view.el.tagName.toLowerCase() == 'p');
    ok(view.$('a').length != 0);
  });

  test("events passed in options", 1, function() {
    var counter = 0;

    var View = Backbone.View.extend({
      el: '#testElement',
      increment: function() {
        counter++;
      }
    });

    var view = new View({
      events: {
        'click h1': 'increment'
      }
    });

    view.$('h1').trigger('click').trigger('click');
    equal(counter, 2);
  });

  test("remove", 0, function() {
    document.body.appendChild(view.el);

    view.delegate('click', function() { ok(false); });
    view.listenTo(view, 'all x', function() { ok(false); });

    view.remove();

    view.$el.trigger('x');
    view.trigger('x');
  });

  test('_removeElement', 2, function() {
    var el = view.el;
    document.body.appendChild(view.el);
    view._removeElement();
    strictEqual(view.el, el);
    strictEqual(view.el.parentNode, null);
  });

})();
<commit_msg>use notEqual body isntead of equal null<commit_after>(function() {

  var view;

  module("Backbone.View", {

    setup: function() {
      view = new Backbone.View({
        id        : 'test-view',
        className : 'test-view',
        other     : 'non-special-option'
      });
    }

  });

  test("constructor", 3, function() {
    equal(view.el.id, 'test-view');
    equal(view.el.className, 'test-view');
    equal(view.el.other, void 0);
  });

  test("$", 2, function() {
    var view = new Backbone.View;
    view.setElement('
test
');
    var result = view.$('a b');

    strictEqual(result[0].innerHTML, 'test');
    ok(result.length === +result.length);
  });

  test("_setEl", 2, function() {
    view._setEl('
', {id: 'test-div'});
    strictEqual(view.el.tagName.toLowerCase(), 'div');
    strictEqual(view.el.id, 'test-div');
  });

  test("jQuery", function() {
    var view = new Backbone.View;
    view.setElement('
test
');

    if (Backbone.$) {
      ok(view.$el instanceof Backbone.$);
      equal(view.$el[0], view.el);
    } else {
      ok(view.el.nodeType === 1);
    }
  });

  test("initialize", 1, function() {
    var View = Backbone.View.extend({
      initialize: function() {
        this.one = 1;
      }
    });

    strictEqual(new View().one, 1);
  });

  test("delegateEvents", 6, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    var events = {'click h1': 'increment'};

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 1);

    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 2);

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 3);
    equal(counter2, 3);
  });

  test("delegate", 2, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    view.delegate('click', 'h1', view.increment);
    view.delegate('click', view.increment);

    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 1);
  });

  test("delegateEvents allows functions for callbacks", 3, function() {
    var view = new Backbone.View({el: '

'});
    view.counter = 0;

    var events = {
      click: function() {
        this.counter++;
      }
    };

    view.delegateEvents(events);
    view.$el.trigger('click');
    equal(view.counter, 1);

    view.$el.trigger('click');
    equal(view.counter, 2);

    view.delegateEvents(events);
    view.$el.trigger('click');
    equal(view.counter, 3);
  });

  test("delegateEvents ignore undefined methods", 0, function() {
    var view = new Backbone.View({el: '

'});
    view.delegateEvents({'click': 'undefinedMethod'});
    view.$el.trigger('click');
  });

  test("undelegateEvents", 6, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    var events = {'click h1': 'increment'};

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 1);

    view.undelegateEvents();
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 2);

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 3);
  });

  test("_ensureElement with DOM node el", 1, function() {
    var View = Backbone.View.extend({
      el: document.body
    });

    equal(new View().el, document.body);
  });

  test("_ensureElement with string el", 3, function() {
    var View = Backbone.View.extend({
      el: "body"
    });
    strictEqual(new View().el, document.body);

    View = Backbone.View.extend({
      el: "#testElement > h1"
    });
    strictEqual(new View().el, $("#testElement > h1").get(0));

    View = Backbone.View.extend({
      el: "#nonexistent"
    });
    ok(!new View().el);
  });

  test("with className and id functions", 2, function() {
    var View = Backbone.View.extend({
      className: function() {
        return 'className';
      },
      id: function() {
        return 'id';
      }
    });

    strictEqual(new View().el.className, 'className');
    strictEqual(new View().el.id, 'id');
  });

  test("with attributes", 2, function() {
    var View = Backbone.View.extend({
      attributes: {
        id: 'id',
        'class': 'class'
      }
    });

    strictEqual(new View().el.className, 'class');
    strictEqual(new View().el.id, 'id');
  });

  test("with attributes as a function", 1, function() {
    var View = Backbone.View.extend({
      attributes: function() {
        return {'class': 'dynamic'};
      }
    });

    strictEqual(new View().el.className, 'dynamic');
  });

  test("multiple views per element", 3, function() {
    var count = 0;
    var $el = $('

');

    var View = Backbone.View.extend({
      el: $el,
      events: {
        click: function() {
          count++;
        }
      }
    });

    var view1 = new View;
    $el.trigger("click");
    equal(1, count);

    var view2 = new View;
    $el.trigger("click");
    equal(3, count);

    view1.delegateEvents();
    $el.trigger("click");
    equal(5, count);
  });

  test("custom events, with namespaces", 2, function() {
    var count = 0;

    var View = Backbone.View.extend({
      el: $('body'),
      events: function() {
        return {"fake$event.namespaced": "run"};
      },
      run: function() {
        count++;
      }
    });

    var view = new View;
    $('body').trigger('fake$event').trigger('fake$event');
    equal(count, 2);

    $('body').off('.namespaced');
    $('body').trigger('fake$event');
    equal(count, 2);
  });

  test("#1048 - setElement uses provided object.", 2, function() {
    var $el = $('body');

    var view = new Backbone.View({el: $el});
    ok(view.$el === $el);

    view.setElement($el = $($el));
    ok(view.$el === $el);
  });

  test("#986 - Undelegate before changing element.", 1, function() {
    var button1 = $('<button></button>');
    var button2 = $('<button></button>');

    var View = Backbone.View.extend({
      events: {
        click: function(e) {
          ok(view.el === e.target);
        }
      }
    });

    var view = new View({el: button1});
    view.setElement(button2);

    button1.trigger('click');
    button2.trigger('click');
  });

  test("#1172 - Clone attributes object", 2, function() {
    var View = Backbone.View.extend({
      attributes: {foo: 'bar'}
    });

    var view1 = new View({id: 'foo'});
    strictEqual(view1.el.id, 'foo');

    var view2 = new View();
    ok(!view2.el.id);
  });

  test("#1228 - tagName can be provided as a function", 1, function() {
    var View = Backbone.View.extend({
      tagName: function() {
        return 'p';
      }
    });

    ok(new View().el.tagName.toLowerCase() == 'p');
  });

  test("views stopListening", 0, function() {
    var View = Backbone.View.extend({
      initialize: function() {
        this.listenTo(this.model, 'all x', function(){ ok(false); });
        this.listenTo(this.collection, 'all x', function(){ ok(false); });
      }
    });

    var view = new View({
      model: new Backbone.Model,
      collection: new Backbone.Collection
    });

    view.stopListening();
    view.model.trigger('x');
    view.collection.trigger('x');
  });

  test("Provide function for el.", 2, function() {
    var View = Backbone.View.extend({
      el: function() {
        return "

";
      }
    });

    var view = new View;
    ok(view.el.tagName.toLowerCase() == 'p');
    ok(view.$('a').length != 0);
  });

  test("events passed in options", 1, function() {
    var counter = 0;

    var View = Backbone.View.extend({
      el: '#testElement',
      increment: function() {
        counter++;
      }
    });

    var view = new View({
      events: {
        'click h1': 'increment'
      }
    });

    view.$('h1').trigger('click').trigger('click');
    equal(counter, 2);
  });

  test("remove", 0, function() {
    document.body.appendChild(view.el);

    view.delegate('click', function() { ok(false); });
    view.listenTo(view, 'all x', function() { ok(false); });

    view.remove();

    view.$el.trigger('x');
    view.trigger('x');
  });

  test('_removeElement', 2, function() {
    var el = view.el;
    document.body.appendChild(view.el);
    view._removeElement();
    strictEqual(view.el, el);
    notEqual(view.el.parentNode, document.body);
  });

})();
<|endoftext|>


<commit_before>// node.js built-in modules
var assert   = require('assert');

// npm modules
var fixtures = require('haraka-test-fixtures');

//Default config
var default_config = {
    main: {},
    mta1: { ip: "1.1.1.1", host: "host1" },
    mta2: { ip: "2.2.2.2", host: "host2" }
};

beforeEach(function (done) {
    //this.outbound = new fixtures.plugin('outbound');
    this.plugin = new fixtures.plugin('index');
    this.plugin.cfg = default_config;

    this.connection = new fixtures.connection.createConnection();
    this.connection.transaction = fixtures.transaction.createTransaction();

    done();  // if a test hangs, assure you called done()
});

describe('VMTA plugin', function () {
    it('load', function (done) {
        assert.ok(this.plugin);
        done();
    });
});

var next = function () {
    test.equal(undefined, arguments[0]);
    test.done();
};

describe('VMTA config file', function () {
    it('loads "vmta.ini" from "config/vmta.ini"', function (done) {
        this.plugin.load_vmta_ini();

        assert.ok(this.plugin.cfg);

        done();
    });

    it('Check availability of "x-vmta" inside Header', function (done) {
        this.connection.transaction.header.add('x-vmta', "vmta_test");

        assert.ok( this.connection.transaction.header.headers['x-vmta'] );
        done();
    });

    it('Check availability of "mta1" inside Config file', function (done) {
        assert.ok(this.plugin.cfg.mta1);
        done();
    });
    //console.log(this.plugin.localAddresses());

});<commit_msg>Fixing the warning "'next' is assigned a value but never used"<commit_after>// node.js built-in modules
var assert   = require('assert');

// npm modules
var fixtures = require('haraka-test-fixtures');

//Default config
var default_config = {
    main: {},
    mta1: { ip: "1.1.1.1", host: "host1" },
    mta2: { ip: "2.2.2.2", host: "host2" }
};

beforeEach(function (done) {
    //this.outbound = new fixtures.plugin('outbound');
    this.plugin = new fixtures.plugin('index');
    this.plugin.cfg = default_config;

    this.connection = new fixtures.connection.createConnection();
    this.connection.transaction = fixtures.transaction.createTransaction();

    done();  // if a test hangs, assure you called done()
});

describe('VMTA plugin', function () {
    it('load', function (done) {
        assert.ok(this.plugin);
        done();
    });
});

/*var next = function () {
    test.equal(undefined, arguments[0]);
    test.done();
};/*

describe('VMTA config file', function () {
    it('loads "vmta.ini" from "config/vmta.ini"', function (done) {
        this.plugin.load_vmta_ini();

        assert.ok(this.plugin.cfg);

        done();
    });

    it('Check availability of "x-vmta" inside Header', function (done) {
        this.connection.transaction.header.add('x-vmta', "vmta_test");

        assert.ok( this.connection.transaction.header.headers['x-vmta'] );
        done();
    });

    it('Check availability of "mta1" inside Config file', function (done) {
        assert.ok(this.plugin.cfg.mta1);
        done();
    });
    //console.log(this.plugin.localAddresses());

});<|endoftext|>