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

var sinon = require('sinon');
var concat = require('..');
var fs = require('fs');
var path = require('path');
var broccoli = require('broccoli');
var merge = require('broccoli-merge-trees');

var chai = require('chai');
var chaiFiles = require('chai-files');

chai.use(chaiFiles);

var expect = chai.expect;
var file = chaiFiles.file;

var firstFixture = path.join(__dirname, 'fixtures', 'first');
var secondFixture = path.join(__dirname, 'fixtures', 'second');
var builder;

describe('sourcemap-concat', function() {
  it('concatenates files in one dir', function() {
    var node = concat(firstFixture, {
      outputFile: '/all-inner.js',
      inputFiles: ['inner/*.js']
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-inner.js').in(result);
      expectFile('all-inner.map').in(result);
    });
  });

  it('concatenates files across dirs', function() {
    var node = concat(firstFixture, {
      outputFile: '/all.js',
      inputFiles: ['**/*.js']
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all.js').in(result);
      expectFile('all.map').in(result);
    });
  });

  it('concatenates all files across dirs when inputFiles is not specified', function() {
    var node = concat(firstFixture, {
      outputFile: '/all.js'
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all.js').in(result);
      expectFile('all.map').in(result);
    });
  });

  it('inserts header', function() {
    var node = concat(firstFixture, {
      outputFile: '/all-with-header.js',
      inputFiles: ['**/*.js'],
      header: "/* This is my header. */"
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-with-header.js').in(result);
      expectFile('all-with-header.map').in(result);
    });
  });

  it('inserts header when sourcemaps are disabled', function() {
    var node = concat(firstFixture, {
      header: "/* This is my header. */",
      inputFiles: ['**/*.js'],
      outputFile: '/all-with-header.js',
      sourceMapConfig: { enabled: false }
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-with-header.js').withoutSrcURL().in(result);
      expectFile('all-with-header.map').notIn(result);
    });
  });

  it('inserts header, headerFiles, footer and footerFiles - and overlaps with inputFiles', function() {
    var node = concat(firstFixture, {
      header: '/* This is my header.s*/',
      headerFiles: ['inner/first.js', 'inner/second.js'],
      inputFiles: ['**/*.js'],
      footerFiles: ['other/third.js', 'other/fourth.js'],
      footer: '/* This is my footer. */',
      outputFile: '/all-the-things.js'
    });

    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-the-things.js').in(result);
      expectFile('all-the-things.map').in(result);
    });
  });

  it('headerFiles, but with a glob', function() {
    expect(function() {
      concat(firstFixture, {
        headerFiles: ['inner/*.js'],
        inputFiles: ['**/*.js'],
        outputFile: '/all-the-things.js'
      });
    }).to.throw('headerFiles cannot contain a glob,  `inner/*.js`');
  });

  it('footerFiles, but with a glob', function() {
    expect(function() {
      concat(firstFixture, {
        footerFiles: ['inner/*.js'],
        inputFiles: ['**/*.js'],
        outputFile: '/all-the-things.js'
      });
    }).to.throw('footerFiles cannot contain a glob,  `inner/*.js`');
  });

  it('inserts header, headerFiles, footer and footerFiles (reversed) - and overlaps with inputFiles', function() {
    var node = concat(firstFixture, {
      header: '/* This is my header.s*/',
      headerFiles: ['inner/second.js', 'inner/first.js'],
      inputFiles: ['**/*.js'],
      footerFiles: ['other/fourth.js', 'other/third.js'],
      footer: '/* This is my footer. */',
      outputFile: '/all-the-things-reversed.js'
    });

    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-the-things-reversed.js').in(result);
      expectFile('all-the-things-reversed.map').in(result);
    });
  });

  it('disables sourcemaps when requested', function() {
    var node = concat(firstFixture, {
      header: "/* This is my header. */",
      inputFiles: ['**/*.js'],
      outputFile: '/no-sourcemap.js',
      sourceMapConfig: { enabled: false },
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('no-sourcemap.js').in(result);
      expectFile('no-sourcemap.map').notIn(result);
    });
  });

  it('passes sourcemaps config to the sourcemaps engine', function() {
    var node = concat(firstFixture, {
      inputFiles: ['**/*.js'],
      outputFile: '/all-with-source-root.js',
      sourceMapConfig: { enabled: true, sourceRoot: "/foo" }
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      var expected = path.join(__dirname, 'expected', 'all-with-source-root.map');
      var actual = path.join(result.directory, 'all-with-source-root.map');

      expect(file(actual)).to.equal(file(expected));
    });
  });

  it('assimilates existing sourcemap', function() {
    var inner = concat(firstFixture, {
      outputFile: '/all-inner.js',
      inputFiles: ['inner/*.js'],
      header: "/* This is my header. */"
    });
    var other = concat(firstFixture, {
      outputFile: '/all-other.js',
      inputFiles: ['other/*.js'],
      header: "/* Other header. */"
    });

    var final = concat(merge([inner, other]), {
      outputFile: '/staged.js',
      inputFiles: ['all-inner.js', 'all-other.js'],
    });

    builder = new broccoli.Builder(final);
    return builder.build().then(function(result) {
      expectFile('staged.js').in(result);
      expectFile('staged.map').in(result);
    });
  });

  it('dedupe uniques in inputFiles (with simpleconcat)', function() {
    var final = concat(firstFixture, {
      outputFile: '/staged.js',
      inputFiles: ['inner/first.js', 'inner/second.js', 'inner/first.js'],
      sourceMapConfig: {
        enabled: false
      }
    });

    builder = new broccoli.Builder(final);
    return builder.build().then(function(result) {

      var firstFixture = path.join(__dirname, 'fixtures', 'first');
      var first = fs.readFileSync(path.join(firstFixture, 'inner/first.js'), 'UTF-8');
      var second = fs.readFileSync(path.join(firstFixture, 'inner/second.js'), 'UTF-8');

      var expected = first + '\n' +  second;
      expect(file(result.directory + '/staged.js')).to.equal(expected);
    });
  });

  it('dedupe uniques in inputFiles (with sourcemaps)', function() {
    var final = concat(firstFixture, {
      outputFile: '/staged.js',
      inputFiles: ['inner/first.js', 'inner/second.js', 'inner/first.js']
    });

    builder = new broccoli.Builder(final);
    return builder.build().then(function(result) {
      var firstFixture = path.join(__dirname, 'fixtures', 'first');
      var first = fs.readFileSync(path.join(firstFixture, 'inner/first.js'), 'UTF-8');
      var second = fs.readFileSync(path.join(firstFixture, 'inner/second.js'), 'UTF-8');

      var expected = first + '\n' +  second + '//# sourceMappingURL=staged.map';
      expect(file(result.directory + '/staged.js')).to.equal(expected, 'output is wrong');
    });
  });

  it('prepends headerFiles', function() {
    var node = concat(firstFixture, {
      outputFile: '/inner-with-headers.js',
      inputFiles: ['inner/*.js'],
      headerFiles: ['other/third.js', 'other/fourth.js']
    });

    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('inner-with-headers.js').in(result);
      expectFile('inner-with-headers.map').in(result);
    });
  });

  it('prepends headerFiles (order reversed)', function() {
    var node = concat(firstFixture, {
      outputFile: '/inner-with-headers-reversed.js',
      inputFiles: ['inner/*.js'],
      headerFiles: ['other/fourth.js', 'other/third.js']
    });

    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('inner-with-headers-reversed.js').in(result);
      expectFile('inner-with-headers-reversed.map').in(result);
    });
  });

  it('appends footer files', function() {
    var node = concat(firstFixture, {
      outputFile: '/inner-with-footers.js',
      inputFiles: ['inner/*.js'],
      footerFiles: ['other/third.js', 'other/fourth.js']
    });

    builder = new broccoli.Builder(node);

    return builder.build().then(function(result) {
      expectFile('inner-with-footers.js').in(result);
      expectFile('inner-with-footers.map').in(result);
    });
  });

  it('appends footer files when sourcemaps are disabled', function() {
    var node = concat(firstFixture, {
      outputFile: '/inner-with-footers.js',
      inputFiles: ['inner/*.js'],
      footerFiles: ['other/third.js', 'other/fourth.js'],
      sourceMapConfig: { enabled: false }
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('inner-with-footers.js').withoutSrcURL().in(result);
      expectFile('inner-with-footers.map').notIn(result);
    });
  });

  it('can ignore empty content', function() {
    var node = concat(firstFixture, {
      outputFile: '/nothing.js',
      inputFiles: ['nothing/*.js'],
      allowNone: true
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('nothing.js').in(result);
      expectFile('nothing.map').in(result);
    });
  });
  it('can ignore empty content when sourcemaps are disabled', function() {
    var node = concat(firstFixture, {
      outputFile: '/nothing.css',
      inputFiles: ['nothing/*.css'],
      sourceMapConfig: { enabled: false },
      allowNone: true
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('nothing.css').in(result);
    });
  });

  it('does not ignore empty content when allowNone is not explicitly set', function() {
    var node = concat(firstFixture, {
      outputFile: '/nothing.js',
      inputFiles: ['nothing/*.js']
    });
    builder = new broccoli.Builder(node);
    var reason;
    return builder.build().catch(function(rejectionReason) {
      reason = rejectionReason;
    }).then(function(){
      expect(reason).to.be;
      expect(reason.message).to.eql("ConcatWithMaps: nothing matched [nothing/*.js]");
    });
  });

  it('does not ignore empty content when allowNone is not explicitly set and sourcemaps are disabled', function() {
    var node = concat(firstFixture, {
      outputFile: '/nothing.css',
      inputFiles: ['nothing/*.css']
    });
    var failure = sinon.spy();
    builder = new broccoli.Builder(node);
    return builder.build().catch(failure).then(function(){
      expect(failure.called).to.be.true;
    });
  });

  it('is not fooled by directories named *.js', function() {
    var node = concat(secondFixture, {
      outputFile: '/sneaky.js',
      inputFiles: ['**/*.js']
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('sneaky.js').in(result);
      expectFile('sneaky.map').in(result);
    });
  });

  afterEach(function() {
    if (builder) {
      return builder.cleanup();
    }
  });
});

describe('concat-without-maps', function() {
  var Concat = require('../concat-without-source-maps');
  var quickTemp = require('quick-temp');
  var concat;
  var outputFile;

  beforeEach(function() {
    outputFile = quickTemp.makeOrRemake(this, 'tmpDestDir') + '/' + 'foo.js';

    concat = new Concat({
      outputFile: outputFile,
      baseDir: firstFixture
    });
  });

  afterEach(function() {
    quickTemp.remove(this, 'tmpDestDir');
  });

  it('addSpace', function() {
    concat.addSpace('a');
    concat.addSpace('b');
    concat.addSpace('c');
    concat.end();
    expect(file(outputFile)).to.equal('abc');
  });

  it('addFile', function() {
    concat.addFile('inner/first.js');
    concat.addFile('inner/second.js');
    concat.addFile('other/third.js');
    concat.end();
    expect(file(outputFile)).to.equal(file(__dirname + '/expected/concat-without-maps-1.js'));
  });

  it('addFile & addSpace', function() {
    concat.addFile('inner/first.js');
    concat.addSpace('"a";\n');
    concat.addSpace('"b";\n');
    concat.addSpace('"c";\n');
    concat.addFile('inner/second.js');
    concat.end();
    expect(file(outputFile)).to.equal(file(__dirname + '/expected/concat-without-maps-2.js'));
  });
});

function expectFile(filename) {
  var stripURL = false;

  return {
    in: function(result, subdir) {
      if (!subdir) {
        subdir = '.';
      }

      var actualContent = fs.readFileSync(path.join(result.directory, subdir, filename), 'utf-8');
      fs.writeFileSync(path.join(__dirname, 'actual', filename), actualContent);

      var expectedContent;

      try {
        expectedContent = fs.readFileSync(path.join(__dirname, 'expected', filename), '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;
    },

    withoutSrcURL: function() {
      stripURL = true;
      return this;
    }
  };
}

function expectSameFiles(actualContent, expectedContent, filename) {
  if (/\.map$/.test(filename)) {
    expect(JSON.parse(actualContent)).to.deep.equal(expectedContent ? JSON.parse(expectedContent) : undefined, 'discrepancy in ' + filename);
  } else {
    expect(actualContent).to.equal(expectedContent, 'discrepancy in ' + filename);
  }
}
<commit_msg>test: Move afterEach() block above tests<commit_after>/* global describe, afterEach, it, expect */

var sinon = require('sinon');
var concat = require('..');
var fs = require('fs');
var path = require('path');
var broccoli = require('broccoli');
var merge = require('broccoli-merge-trees');

var chai = require('chai');
var chaiFiles = require('chai-files');

chai.use(chaiFiles);

var expect = chai.expect;
var file = chaiFiles.file;

var firstFixture = path.join(__dirname, 'fixtures', 'first');
var secondFixture = path.join(__dirname, 'fixtures', 'second');

describe('sourcemap-concat', function() {
  var builder;

  afterEach(function() {
    if (builder) {
      return builder.cleanup();
    }
  });

  it('concatenates files in one dir', function() {
    var node = concat(firstFixture, {
      outputFile: '/all-inner.js',
      inputFiles: ['inner/*.js']
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-inner.js').in(result);
      expectFile('all-inner.map').in(result);
    });
  });

  it('concatenates files across dirs', function() {
    var node = concat(firstFixture, {
      outputFile: '/all.js',
      inputFiles: ['**/*.js']
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all.js').in(result);
      expectFile('all.map').in(result);
    });
  });

  it('concatenates all files across dirs when inputFiles is not specified', function() {
    var node = concat(firstFixture, {
      outputFile: '/all.js'
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all.js').in(result);
      expectFile('all.map').in(result);
    });
  });

  it('inserts header', function() {
    var node = concat(firstFixture, {
      outputFile: '/all-with-header.js',
      inputFiles: ['**/*.js'],
      header: "/* This is my header. */"
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-with-header.js').in(result);
      expectFile('all-with-header.map').in(result);
    });
  });

  it('inserts header when sourcemaps are disabled', function() {
    var node = concat(firstFixture, {
      header: "/* This is my header. */",
      inputFiles: ['**/*.js'],
      outputFile: '/all-with-header.js',
      sourceMapConfig: { enabled: false }
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-with-header.js').withoutSrcURL().in(result);
      expectFile('all-with-header.map').notIn(result);
    });
  });

  it('inserts header, headerFiles, footer and footerFiles - and overlaps with inputFiles', function() {
    var node = concat(firstFixture, {
      header: '/* This is my header.s*/',
      headerFiles: ['inner/first.js', 'inner/second.js'],
      inputFiles: ['**/*.js'],
      footerFiles: ['other/third.js', 'other/fourth.js'],
      footer: '/* This is my footer. */',
      outputFile: '/all-the-things.js'
    });

    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-the-things.js').in(result);
      expectFile('all-the-things.map').in(result);
    });
  });

  it('headerFiles, but with a glob', function() {
    expect(function() {
      concat(firstFixture, {
        headerFiles: ['inner/*.js'],
        inputFiles: ['**/*.js'],
        outputFile: '/all-the-things.js'
      });
    }).to.throw('headerFiles cannot contain a glob,  `inner/*.js`');
  });

  it('footerFiles, but with a glob', function() {
    expect(function() {
      concat(firstFixture, {
        footerFiles: ['inner/*.js'],
        inputFiles: ['**/*.js'],
        outputFile: '/all-the-things.js'
      });
    }).to.throw('footerFiles cannot contain a glob,  `inner/*.js`');
  });

  it('inserts header, headerFiles, footer and footerFiles (reversed) - and overlaps with inputFiles', function() {
    var node = concat(firstFixture, {
      header: '/* This is my header.s*/',
      headerFiles: ['inner/second.js', 'inner/first.js'],
      inputFiles: ['**/*.js'],
      footerFiles: ['other/fourth.js', 'other/third.js'],
      footer: '/* This is my footer. */',
      outputFile: '/all-the-things-reversed.js'
    });

    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('all-the-things-reversed.js').in(result);
      expectFile('all-the-things-reversed.map').in(result);
    });
  });

  it('disables sourcemaps when requested', function() {
    var node = concat(firstFixture, {
      header: "/* This is my header. */",
      inputFiles: ['**/*.js'],
      outputFile: '/no-sourcemap.js',
      sourceMapConfig: { enabled: false },
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('no-sourcemap.js').in(result);
      expectFile('no-sourcemap.map').notIn(result);
    });
  });

  it('passes sourcemaps config to the sourcemaps engine', function() {
    var node = concat(firstFixture, {
      inputFiles: ['**/*.js'],
      outputFile: '/all-with-source-root.js',
      sourceMapConfig: { enabled: true, sourceRoot: "/foo" }
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      var expected = path.join(__dirname, 'expected', 'all-with-source-root.map');
      var actual = path.join(result.directory, 'all-with-source-root.map');

      expect(file(actual)).to.equal(file(expected));
    });
  });

  it('assimilates existing sourcemap', function() {
    var inner = concat(firstFixture, {
      outputFile: '/all-inner.js',
      inputFiles: ['inner/*.js'],
      header: "/* This is my header. */"
    });
    var other = concat(firstFixture, {
      outputFile: '/all-other.js',
      inputFiles: ['other/*.js'],
      header: "/* Other header. */"
    });

    var final = concat(merge([inner, other]), {
      outputFile: '/staged.js',
      inputFiles: ['all-inner.js', 'all-other.js'],
    });

    builder = new broccoli.Builder(final);
    return builder.build().then(function(result) {
      expectFile('staged.js').in(result);
      expectFile('staged.map').in(result);
    });
  });

  it('dedupe uniques in inputFiles (with simpleconcat)', function() {
    var final = concat(firstFixture, {
      outputFile: '/staged.js',
      inputFiles: ['inner/first.js', 'inner/second.js', 'inner/first.js'],
      sourceMapConfig: {
        enabled: false
      }
    });

    builder = new broccoli.Builder(final);
    return builder.build().then(function(result) {

      var firstFixture = path.join(__dirname, 'fixtures', 'first');
      var first = fs.readFileSync(path.join(firstFixture, 'inner/first.js'), 'UTF-8');
      var second = fs.readFileSync(path.join(firstFixture, 'inner/second.js'), 'UTF-8');

      var expected = first + '\n' +  second;
      expect(file(result.directory + '/staged.js')).to.equal(expected);
    });
  });

  it('dedupe uniques in inputFiles (with sourcemaps)', function() {
    var final = concat(firstFixture, {
      outputFile: '/staged.js',
      inputFiles: ['inner/first.js', 'inner/second.js', 'inner/first.js']
    });

    builder = new broccoli.Builder(final);
    return builder.build().then(function(result) {
      var firstFixture = path.join(__dirname, 'fixtures', 'first');
      var first = fs.readFileSync(path.join(firstFixture, 'inner/first.js'), 'UTF-8');
      var second = fs.readFileSync(path.join(firstFixture, 'inner/second.js'), 'UTF-8');

      var expected = first + '\n' +  second + '//# sourceMappingURL=staged.map';
      expect(file(result.directory + '/staged.js')).to.equal(expected, 'output is wrong');
    });
  });

  it('prepends headerFiles', function() {
    var node = concat(firstFixture, {
      outputFile: '/inner-with-headers.js',
      inputFiles: ['inner/*.js'],
      headerFiles: ['other/third.js', 'other/fourth.js']
    });

    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('inner-with-headers.js').in(result);
      expectFile('inner-with-headers.map').in(result);
    });
  });

  it('prepends headerFiles (order reversed)', function() {
    var node = concat(firstFixture, {
      outputFile: '/inner-with-headers-reversed.js',
      inputFiles: ['inner/*.js'],
      headerFiles: ['other/fourth.js', 'other/third.js']
    });

    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('inner-with-headers-reversed.js').in(result);
      expectFile('inner-with-headers-reversed.map').in(result);
    });
  });

  it('appends footer files', function() {
    var node = concat(firstFixture, {
      outputFile: '/inner-with-footers.js',
      inputFiles: ['inner/*.js'],
      footerFiles: ['other/third.js', 'other/fourth.js']
    });

    builder = new broccoli.Builder(node);

    return builder.build().then(function(result) {
      expectFile('inner-with-footers.js').in(result);
      expectFile('inner-with-footers.map').in(result);
    });
  });

  it('appends footer files when sourcemaps are disabled', function() {
    var node = concat(firstFixture, {
      outputFile: '/inner-with-footers.js',
      inputFiles: ['inner/*.js'],
      footerFiles: ['other/third.js', 'other/fourth.js'],
      sourceMapConfig: { enabled: false }
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('inner-with-footers.js').withoutSrcURL().in(result);
      expectFile('inner-with-footers.map').notIn(result);
    });
  });

  it('can ignore empty content', function() {
    var node = concat(firstFixture, {
      outputFile: '/nothing.js',
      inputFiles: ['nothing/*.js'],
      allowNone: true
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('nothing.js').in(result);
      expectFile('nothing.map').in(result);
    });
  });
  it('can ignore empty content when sourcemaps are disabled', function() {
    var node = concat(firstFixture, {
      outputFile: '/nothing.css',
      inputFiles: ['nothing/*.css'],
      sourceMapConfig: { enabled: false },
      allowNone: true
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('nothing.css').in(result);
    });
  });

  it('does not ignore empty content when allowNone is not explicitly set', function() {
    var node = concat(firstFixture, {
      outputFile: '/nothing.js',
      inputFiles: ['nothing/*.js']
    });
    builder = new broccoli.Builder(node);
    var reason;
    return builder.build().catch(function(rejectionReason) {
      reason = rejectionReason;
    }).then(function(){
      expect(reason).to.be;
      expect(reason.message).to.eql("ConcatWithMaps: nothing matched [nothing/*.js]");
    });
  });

  it('does not ignore empty content when allowNone is not explicitly set and sourcemaps are disabled', function() {
    var node = concat(firstFixture, {
      outputFile: '/nothing.css',
      inputFiles: ['nothing/*.css']
    });
    var failure = sinon.spy();
    builder = new broccoli.Builder(node);
    return builder.build().catch(failure).then(function(){
      expect(failure.called).to.be.true;
    });
  });

  it('is not fooled by directories named *.js', function() {
    var node = concat(secondFixture, {
      outputFile: '/sneaky.js',
      inputFiles: ['**/*.js']
    });
    builder = new broccoli.Builder(node);
    return builder.build().then(function(result) {
      expectFile('sneaky.js').in(result);
      expectFile('sneaky.map').in(result);
    });
  });
});

describe('concat-without-maps', function() {
  var Concat = require('../concat-without-source-maps');
  var quickTemp = require('quick-temp');
  var concat;
  var outputFile;

  beforeEach(function() {
    outputFile = quickTemp.makeOrRemake(this, 'tmpDestDir') + '/' + 'foo.js';

    concat = new Concat({
      outputFile: outputFile,
      baseDir: firstFixture
    });
  });

  afterEach(function() {
    quickTemp.remove(this, 'tmpDestDir');
  });

  it('addSpace', function() {
    concat.addSpace('a');
    concat.addSpace('b');
    concat.addSpace('c');
    concat.end();
    expect(file(outputFile)).to.equal('abc');
  });

  it('addFile', function() {
    concat.addFile('inner/first.js');
    concat.addFile('inner/second.js');
    concat.addFile('other/third.js');
    concat.end();
    expect(file(outputFile)).to.equal(file(__dirname + '/expected/concat-without-maps-1.js'));
  });

  it('addFile & addSpace', function() {
    concat.addFile('inner/first.js');
    concat.addSpace('"a";\n');
    concat.addSpace('"b";\n');
    concat.addSpace('"c";\n');
    concat.addFile('inner/second.js');
    concat.end();
    expect(file(outputFile)).to.equal(file(__dirname + '/expected/concat-without-maps-2.js'));
  });
});

function expectFile(filename) {
  var stripURL = false;

  return {
    in: function(result, subdir) {
      if (!subdir) {
        subdir = '.';
      }

      var actualContent = fs.readFileSync(path.join(result.directory, subdir, filename), 'utf-8');
      fs.writeFileSync(path.join(__dirname, 'actual', filename), actualContent);

      var expectedContent;

      try {
        expectedContent = fs.readFileSync(path.join(__dirname, 'expected', filename), '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;
    },

    withoutSrcURL: function() {
      stripURL = true;
      return this;
    }
  };
}

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


<commit_before>import test from 'ava'
import * as http from 'http'
import axiosist from '.'

test('should request', t =>
  axiosist((req, res) => res.end())
    .get('/').then(() => t.pass()))

test('should request the right method', t =>
  axiosist((req, res) => {
    t.is(req.method, 'POST')
    res.end()
  }).post('/').then(() => t.pass()))

test('should request the right url', t =>
  axiosist((req, res) => {
    t.is(req.url, '/foo/bar?baz=qux')
    res.end()
  }).request({
    baseURL: '/foo',
    url: '/bar',
    params: { baz: 'qux' }
  }).then(() => t.pass()))

test('should request the right header', t =>
  axiosist((req, res) => {
    t.is(req.headers.foo, 'bar')
    res.end()
  }).request({
    url: '/',
    headers: { foo: 'bar' }
  }).then(() => t.pass()))

test('should request the right body', t =>
  axiosist((req, res) => {
    req.setEncoding('utf8')
    req
      .on('data', chunk => t.is(chunk, 'foo'))
      .on('end', () => res.end())
  }).request({
    method: 'post',
    url: '/',
    data: 'foo'
  }).then(() => t.pass()))

test('should request the right host', t =>
  axiosist((req, res) => {
    t.is(req.headers.host, 'example.com')
    res.end()
  }).get('http://example.com/foo')
    .then(() => t.pass()))

test('should response the right status', t =>
  axiosist((req, res) => {
    res.statusCode = 400
    res.statusMessage = 'FOO'
    res.end()
  }).get('/').then(response => {
    t.is(response.status, 400)
    t.is(response.statusText, 'FOO')
  }))

test('should response the right header', t =>
  axiosist((req, res) => {
    res.setHeader('foo', 'bar')
    res.end()
  }).get('/').then(response => {
    t.is(response.headers.foo, 'bar')
  }))

test('should response the right body', t =>
  axiosist((req, res) => {
    res.end('foo')
  }).get('/').then(response => {
    t.is(response.data, 'foo')
  }))

test('should fail correctly', t => t.throwsAsync(
  axiosist((req, res) => {
    res.end('foo')
  }).request({
    url: '/',
    maxContentLength: 1
  }), /maxContentLength/).then(() => t.pass()))

test('should response redirect', t =>
  axiosist((req, res) => {
    res.statusCode = 302
    res.setHeader('Location', 'http://example.com/')
    res.end()
  }).get('/').then(response => {
    t.is(response.status, 302)
    t.is(response.headers.location, 'http://example.com/')
  }))

test('should work with http server', t => {
  const app = http.createServer((req, res) => {
    res.end('foo')
  })

  return axiosist(app).get('/').then(() => t.pass())
})
<commit_msg>Refine test<commit_after>import test from 'ava'
import { createServer } from 'http'
import axiosist from '.'

test('should request', t =>
  axiosist((req, res) => res.end())
    .get('/').then(() => t.pass()))

test('should request the right method', t =>
  axiosist((req, res) => {
    t.is(req.method, 'POST')
    res.end()
  }).post('/').then(() => t.pass()))

test('should request the right url', t =>
  axiosist((req, res) => {
    t.is(req.url, '/foo/bar?baz=qux')
    res.end()
  }).request({
    baseURL: '/foo',
    url: '/bar',
    params: { baz: 'qux' }
  }).then(() => t.pass()))

test('should request the right header', t =>
  axiosist((req, res) => {
    t.is(req.headers.foo, 'bar')
    res.end()
  }).request({
    url: '/',
    headers: { foo: 'bar' }
  }).then(() => t.pass()))

test('should request the right body', t =>
  axiosist((req, res) => {
    req.setEncoding('utf8')
    req
      .on('data', chunk => t.is(chunk, 'foo'))
      .on('end', () => res.end())
  }).request({
    method: 'post',
    url: '/',
    data: 'foo'
  }).then(() => t.pass()))

test('should request the right host', t =>
  axiosist((req, res) => {
    t.is(req.headers.host, 'example.com')
    res.end()
  }).get('http://example.com/foo')
    .then(() => t.pass()))

test('should response the right status', t =>
  axiosist((req, res) => {
    res.statusCode = 400
    res.statusMessage = 'FOO'
    res.end()
  }).get('/').then(response => {
    t.is(response.status, 400)
    t.is(response.statusText, 'FOO')
  }))

test('should response the right header', t =>
  axiosist((req, res) => {
    res.setHeader('foo', 'bar')
    res.end()
  }).get('/').then(response => {
    t.is(response.headers.foo, 'bar')
  }))

test('should response the right body', t =>
  axiosist((req, res) => {
    res.end('foo')
  }).get('/').then(response => {
    t.is(response.data, 'foo')
  }))

test('should fail correctly', t => t.throwsAsync(
  axiosist((req, res) => {
    res.end('foo')
  }).request({
    url: '/',
    maxContentLength: 1
  }), /maxContentLength/).then(() => t.pass()))

test('should response redirect', t =>
  axiosist((req, res) => {
    res.statusCode = 302
    res.setHeader('Location', 'http://example.com/')
    res.end()
  }).get('/').then(response => {
    t.is(response.status, 302)
    t.is(response.headers.location, 'http://example.com/')
  }))

test('should work with http server', t =>
  axiosist(
    createServer((req, res) => res.end('foo'))
  ).get('/').then(response => {
    t.is(response.data, 'foo')
  }))
<|endoftext|>


<commit_before>module.exports = {
  dist: {
    files: {
      src: [
        '<%= app.dirs.dist %>/{,*/}*.js',
        '<%= app.dirs.dist %>/{,*/}*.css',
        '<%= app.dirs.dist %>/assets/fonts/*',
        '!<%= app.dirs.dist %>/server/*'
      ]
    }
  }
};
<commit_msg>Ignore chart.js on rev<commit_after>module.exports = {
  dist: {
    files: {
      src: [
        '<%= app.dirs.dist %>/{,*/}*.js',
        '<%= app.dirs.dist %>/{,*/}*.css',
        '<%= app.dirs.dist %>/assets/fonts/*',
        '!<%= app.dirs.dist %>/server/*',
        '!<%= app.dirs.dist %>/bower_components/Chart.js'
      ]
    }
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright 2017, Maha Farhat
 *
 * This file is part of the software gentb, consisting of custom
 * code for the GenTB's django-based website.
 *
 * gentb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * gentb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with gentb.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function() {
  $('div.maps').each(function(map) {
//this needs to get the data somehow so we can initialize the legend and scale it dynamically
    var map = L.map(this.id).setView([12, 25], 2);
    var color = d3.scale.threshold()
        .domain([250, 500, 750, 1000])
        .range(['#FFFFCC', '#C7E9B4', '#7FCDBB', '#41B6C4', '#1D91C0']);
    var newLegend = function(map, max, color) {

            legend = L.control({
              position: 'topright'
          });

            legend.onAdd = function(map) {
              var div = L.DomUtil.create('div', 'legend');
              return div
            };
            legend.addTo(map);

            var x = d3.scale.linear()
              .domain([0, max])
              .range([0, 400]);

            var xAxis = d3.svg.axis()
              .scale(x)
              .orient("top")
              .tickSize(1)
              .tickValues(color.domain())

            var svg = d3.select(".legend.leaflet-control").append("svg")
              .attr("id", 'legend')
              .attr("width", 450)
              .attr("height", 40);

            var g = svg.append("g")
              .attr("class", "key")
              .attr("transform", "translate(25,16)");

            g.selectAll("rect")
              .data(color.range().map(function(d, i) {
                return {
                  x0: i ? x(color.domain()[i - 1]) : x.range()[0],
                  x1: i < color.domain().length ? x(color.domain()[i]) : x.range()[1],
                  z: d
                };
              }))
              .enter().append("rect")
              .attr("height", 10)
              .attr("x", function(d) {
                return d.x0;
              })
              .attr("width", function(d) {
                return d.x1 - d.x0;
              })
              .style("fill", function(d) {
                return d.z;
              });

            g.call(xAxis).append("text")
              .attr("class", "caption")
              .attr("y", 21)
              .text('Number of isolates');

        }

    initialiseStrainMap(map, color, newLegend);
    $('#map-store').data('json-signal', function(data) {
      mapStrainData(map, color, data, newLegend);
      map.invalidateSize();
    });
  });
});

function matchKey(datapoint, key_variable) {
  if(key_variable[0]) {
      return (parseFloat(key_variable[0][datapoint]));
  }
  return "black";
}

var legend = null;
function initialiseStrainMap(map, color, newLegend) {

  L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: '' //Map tiles (c) OpenStreetMap, Map data (c) genTB'
  }).addTo(map);

 newLegend(map, 1000, color)

}
var map_layer = null;
function mapStrainData(map, color, data, newLegend) {
  var existing = getTabData('map');

  if(map_layer) {
    // Remove previous layer
    map.removeLayer(map_layer);
  }

  function get_style(feature) {

      var color_max;
      var color_by;
      if ($(".form-check-input:checked").val() == "feature.properties[1][0].gdp") {
          color_by = feature.properties[1][0].gdp;
          color_max = 6000000;
      }
      else {
          color_by = feature.properties[0][0].values.Total;
          color_max = 1000;
      }
  var best_color = d3.scale.threshold()
        .domain([color_max/4, color_max/2, color_max*3/4, color_max])
        .range(['#FFFFCC', '#C7E9B4', '#7FCDBB', '#41B6C4', '#1D91C0']);
    return {
     fillColor: best_color(color_by),
      weight: 1,
      opacity: 0.5,
      color: 'black',
      fillOpacity: 0.35
    };
  }

  //toggle mapping color
  $('.form-check-input').on('click',function(e){
      var max;
      if(map_layer) {
        // Remove previous layer
        map.removeLayer(map_layer);
      }
      map_layer = L.geoJson(data,  {
        style: get_style,
        onEachFeature: onEachFeature
      }
    ).addTo(map)

    if(legend) {
      // Remove previous layer
      map.removeControl(legend);
    }

    if ($(".form-check-input:checked").val() == "feature.properties[1][0].gdp") {
        var legend_label = "GDP"
        max = 400000;
    }
    else {
        var legend_label = "Number of isolates"
        max = 1000;
    }

    var color = d3.scale.threshold()
        .domain([max/4, max/2, max*.75, max])
        .range(['#FFFFCC', '#C7E9B4', '#7FCDBB', '#41B6C4', '#1D91C0']);

    newLegend(map, max, color);

    d3.select('.caption')
      .text(legend_label);

});

  function onEachFeature(feature, layer) {
    var country_code = feature.properties[0][0].value;
    ret = $('

');
    ret.append($('
' + feature.properties[0][0].name + '
'));
    $.each(['Sensitive', 'MDR', 'XDR', 'TDR'], function(key, value) {
      if (feature.properties[0][0].values[value]) {
        ret.append($('
Number of ' + value + ' isolates: ' + feature.properties[0][0].values[value] + "
"));
      }
    });
    if(Object.keys(feature.properties[0][0].values).length > 2) {
      ret.append($("

Total isolates: " + feature.properties[0][0].values.Total + "
"));
    }
    ret.append($('
' + 'Social Determinants of Health:' + '
'));
    ret.append($("

 GDP: " + (feature.properties[1][0].gdp) + "
"));
    var button1 = $("<button class='btn btn-primary btn-xs'>Select Country</button>").click(function() {
        // WARNING: jquery class selectors and addClass/removeClass DO NOT work here

        var next = $('.country-'+country_code);
        // Set element id just in case it's useful later
        next[0].id = country_code;

        // Add the countrySelect class to highlight it
        next.attr('class', next.attr('class') + ' countrySelect');
        next.data('deselect', function() { button2.click(); });

        // Set the usable data for other charts
        addTabData('map', country_code, feature.properties[0][0].name, 'flag');

        button1.hide();
        button2.show();
        map.closePopup();
    });
    button1.attr('id', 'select-'+country_code);
    var button2 = $("<button class='btn btn-danger btn-xs'>Deselect</button>").click(function() {
        // WARNING: jquery class selectors and addClass/removeClass DO NOT work here
        var previous = $('.country-'+country_code);
        previous.attr('class', previous.attr('class').replace(' countrySelect', ''));
        removeTabData('map', country_code);
        button1.show();
        button2.hide();
        map.closePopup();
    });
    ret.append($("
"));
    ret.append(button1);
    ret.append(button2);
    layer.bindPopup(ret[0]);

    var id_cls = 'country-' + country_code;
    if(existing.includes(country_code)) {
        id_cls += ' countrySelect';
        button1.hide();
    } else {
        button2.hide();
    }
    layer.setStyle({className: id_cls});

  }

  map_layer = L.geoJson(data,  {
    style: get_style,
    onEachFeature: onEachFeature
  }
).addTo(map)

}
<commit_msg>find max dynamically and cleaned up color and legend code to be less redundant<commit_after>/*
 * Copyright 2017, Maha Farhat
 *
 * This file is part of the software gentb, consisting of custom
 * code for the GenTB's django-based website.
 *
 * gentb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * gentb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with gentb.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function() {
  $('div.maps').each(function(map) {
//this needs to get the data somehow so we can initialize the legend and scale it dynamically
    var map = L.map(this.id).setView([12, 25], 2);
    var newLegend = function(map, max, color) {

            legend = L.control({
              position: 'topright'
          });

            legend.onAdd = function(map) {
              var div = L.DomUtil.create('div', 'legend');
              return div
            };
            legend.addTo(map);

            var x = d3.scale.linear()
              .domain([0, max])
              .range([0, 400]);

            var xAxis = d3.svg.axis()
              .scale(x)
              .orient("top")
              .tickSize(1)
              .tickValues(color.domain())

            var svg = d3.select(".legend.leaflet-control").append("svg")
              .attr("id", 'legend')
              .attr("width", 450)
              .attr("height", 40);

            var g = svg.append("g")
              .attr("class", "key")
              .attr("transform", "translate(25,16)");

            g.selectAll("rect")
              .data(color.range().map(function(d, i) {
                return {
                  x0: i ? x(color.domain()[i - 1]) : x.range()[0],
                  x1: i < color.domain().length ? x(color.domain()[i]) : x.range()[1],
                  z: d
                };
              }))
              .enter().append("rect")
              .attr("height", 10)
              .attr("x", function(d) {
                return d.x0;
              })
              .attr("width", function(d) {
                return d.x1 - d.x0;
              })
              .style("fill", function(d) {
                return d.z;
              });

            g.call(xAxis).append("text")
              .attr("class", "caption")
              .attr("y", 21)
              .text('Number of isolates');

        }
    let maxTotal;
    initialiseStrainMap(map);
    $('#map-store').data('json-signal', function(data) {
      var getMaxAttribute = function (data, attribute) {
          var max = -10000000;
          for (var i=0 ; i<data.length ; i++) {
              if (attribute === "total_strains"){
                  max = Math.max(data[i]["properties"][0][0].values.Total, max);
              }
              else{
                  max = Math.max(data[i]["properties"][0][0][attribute], max);
              }
          }
          return max;
      }
      var maxGDP = getMaxAttribute(data.features, "gdp");
      maxTotal = getMaxAttribute(data.features, "total_strains");
      mapStrainData(map, data, newLegend, maxGDP, maxTotal);
      map.invalidateSize();
    });
  });
});

function matchKey(datapoint, key_variable) {
  if(key_variable[0]) {
      return (parseFloat(key_variable[0][datapoint]));
  }
  return "black";
}

var legend = null;
function initialiseStrainMap(map) {

  L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: '' //Map tiles (c) OpenStreetMap, Map data (c) genTB'
  }).addTo(map);

}
var map_layer = null;
function mapStrainData(map, data, newLegend, maxGDP, maxTotal) {
  let color_max;
  let best_color;

  var existing = getTabData('map');

  if(map_layer) {
    // Remove previous layer
    map.removeLayer(map_layer);
  }

  function get_style(feature) {

      var color_by;
      if ($(".form-check-input:checked").val() == "feature.properties[0][0].gdp") {
          color_by = feature.properties[0][0].gdp;
          color_max = maxGDP;
      }
      else {
          color_by = feature.properties[0][0].values.Total;
          color_max = maxTotal;
      }
    best_color = d3.scale.threshold()
        .domain([color_max/4, color_max/2, color_max*3/4, color_max])
        .range(['#FFFFCC', '#C7E9B4', '#7FCDBB', '#41B6C4', '#1D91C0']);
    if (!legend) {
        newLegend(map, maxTotal, best_color)
    }

    return {
     fillColor: best_color(color_by),
      weight: 1,
      opacity: 0.5,
      color: 'black',
      fillOpacity: 0.35
    };
  }

  //toggle mapping color
  $('.form-check-input').on('click',function(e){
      var max;
      if(map_layer) {
        // Remove previous layer
        map.removeLayer(map_layer);
      }
      map_layer = L.geoJson(data,  {
        style: get_style,
        onEachFeature: onEachFeature
      }
    ).addTo(map)

    if(legend) {
      // Remove previous layer
      map.removeControl(legend);
    }

    if ($(".form-check-input:checked").val() == "feature.properties[0][0].gdp") {
        var legend_label = "GDP"
        color_max = maxGDP;
    }
    else {
        var legend_label = "Number of isolates"
        color_max = maxTotal;
    }

    newLegend(map, color_max, best_color);

    d3.select('.caption')
      .text(legend_label);

});

  function onEachFeature(feature, layer) {
    let gdp;
    var country_code = feature.properties[0][0].value;
    ret = $('

');
    ret.append($('
' + feature.properties[0][0].name + '
'));
    $.each(['Sensitive', 'MDR', 'XDR', 'TDR'], function(key, value) {
      if (feature.properties[0][0].values[value]) {
        ret.append($('
Number of ' + value + ' isolates: ' + feature.properties[0][0].values[value] + "
"));
      }
    });
    if(Object.keys(feature.properties[0][0].values).length > 2) {
      ret.append($("

Total isolates: " + feature.properties[0][0].values.Total + "
"));
    }
    ret.append($('
' + 'Social Determinants of Health:' + '
'));
    // if (feature.properties[1].length == 0) {
    //     gdp == null;
    // }
    // else{
    //     gdp = feature.properties[0][0].gdp
    // }
    ret.append($("

 GDP: " + (feature.properties[0][0].gdp) + "
"));
    var button1 = $("<button class='btn btn-primary btn-xs'>Select Country</button>").click(function() {
        // WARNING: jquery class selectors and addClass/removeClass DO NOT work here

        var next = $('.country-'+country_code);
        // Set element id just in case it's useful later
        next[0].id = country_code;

        // Add the countrySelect class to highlight it
        next.attr('class', next.attr('class') + ' countrySelect');
        next.data('deselect', function() { button2.click(); });

        // Set the usable data for other charts
        addTabData('map', country_code, feature.properties[0][0].name, 'flag');

        button1.hide();
        button2.show();
        map.closePopup();
    });
    button1.attr('id', 'select-'+country_code);
    var button2 = $("<button class='btn btn-danger btn-xs'>Deselect</button>").click(function() {
        // WARNING: jquery class selectors and addClass/removeClass DO NOT work here
        var previous = $('.country-'+country_code);
        previous.attr('class', previous.attr('class').replace(' countrySelect', ''));
        removeTabData('map', country_code);
        button1.show();
        button2.hide();
        map.closePopup();
    });
    ret.append($("
"));
    ret.append(button1);
    ret.append(button2);
    layer.bindPopup(ret[0]);

    var id_cls = 'country-' + country_code;
    if(existing.includes(country_code)) {
        id_cls += ' countrySelect';
        button1.hide();
    } else {
        button2.hide();
    }
    layer.setStyle({className: id_cls});

  }

  map_layer = L.geoJson(data,  {
    style: get_style,
    onEachFeature: onEachFeature
  }
).addTo(map)

}
<|endoftext|>


<commit_before>/* informix cli using nodejs-db-informix */

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

/*
 * Connection configurations
 */
// var settings = JSON.parse(require('fs').readFileSync('./tests/db_conf.json','utf8'));
var settings = {
      "host": ""
    , "user": ""
    , "password": ""
    , "database": "sysmaster"
    , "charset": ""
    // , "port": ""
    // , "compress": ""
    // , "initCommand": ""
    // , "readTimeout": ""
    // , "reconnect": ""
    // , "socket": ""
    // , "sslVerifyServer": ""
    // , "timeout": ""
    // , "writeTimeout": ""
};

/*
 * Create a new Informix database bindings. Setup event callbacks. Connect to
 * the database.
 * c - connection
 */
function connect(settings) {
    if (!settings || typeof(settings) !== 'object') {
        throw new Error("No settings provided");
    }

    /*
     * Create an Informix database nodejs object
     */
    var bindings = require("../nodejs-db-informix");
    console.log(bindings);

    var c = new bindings.Informix(settings);

    c.on('error', function(error) {
        console.log("Error: ");
        console.log(error);
    }).on('ready', function(server) {
        console.log("Connection ready to ");
        console.log(server);
    }).connect(function(err) {
        if (err) {
            throw new Error('Could not connect to DB');
        }
        console.log('Connected to db with ');
        console.log(settings);
        console.log("isConnected() == " + c.isConnected());

        this
        .on('each', function(e, idx, more) {
            console.log('each');
            console.log(arguments);
        })
        .on('success', function() {
            console.log('success');
            console.log(arguments);
        });

        /*
        var rs = this.query("select first 10 * from systables", function(s,r) {
            console.log(s);
            console.log(r);
        }).execute();
        */

        /*
        var rs = this
                .query(
                      "SELECT FIRST 10 * FROM systables"
                    , []
                    , function (status, results) {
                        console.log('CALLBACK:');
                        // console.log(arguments);
                        console.log("status:" + status);
                        console.log(results);
                    }
                    , {
                        start: function(q) {
                            console.log('Query:');
                            console.log(q);
                        }
                        , finish: function(f) {
                            console.log('Finish:');
                            console.log(f);
                        }
                        , async: true
                        , cast: true
                    }
                )
                .execute();
        */

        /*
        var rs = this
                .query(
                      ""
                    , []
                    , function (status, results) {
                        console.log('CALLBACK:');
                        // console.log(arguments);
                        console.log("status:" + status);
                        console.log(results);
                    }
                    , {
                        start: function(q) {
                            console.log('Query:');
                            console.log(q);
                        }
                        , finish: function(f) {
                            console.log('Finish:');
                            console.log(f);
                        }
                        , async: true
                        , cast: true
                    }
                )
                .select("*")
                .first(10)
                .from("systables", false)
                .execute();
        */

    });

    return c;
}

function execQuery(conn,qry) {
    if (!conn || conn == undefined || conn == null) {
        throw Error("_main: connection is not valid");
    }
    var rs = conn
        .query(
              qry
            , []
            , function (status, results) {
                console.log('CALLBACK:');
                // console.log(arguments);
                console.log("status:" + status);
                console.log(results);
            }
            , {
                start: function(q) {
                    console.log('Query:');
                    console.log(q);
                }
                , finish: function(f) {
                    console.log('Finish:');
                    console.log(f);
                }
                , async: true
                , cast: true
            }
        )
        .execute();

    return rs;
}

function _main () {
    var conn = connect(settings);

    if (!conn || conn == undefined || conn == null) {
        throw Error("_main: connection is not valid");
    }

    console.log('connection:');
    console.log(conn);

    rl.setPrompt('inf> ');
    rl.prompt();

    rl.on('line', function(line) {
        var cmd = line.trim();

        if (cmd == '' || cmd == undefined || cmd == null) {
            rl.prompt();
            return;
        }

        var c_reg = /^\s*connect\s+(\w+)/;

        if (c_reg.test(cmd)) {
            var m = cmd.match(c_reg);
            var db = m[1];
            if (db == null || db == undefined || db.trim() == '') {
                console.log("Invalid command: " + cmd);
                rl.prompt();
                return;
            }

            conn.disconnect();
            settings.database = db;
            conn = connect(settings);

        } else {
            execQuery(conn, cmd);
        }

        rl.prompt();

    }).on('close', function() {
        console.log('Exit.');
    });
}

_main();
<commit_msg>remove stale<commit_after><|endoftext|>


<commit_before>import moment from 'moment';
import gravity from '../../lib/loaders/gravity';
import cached from '../fields/cached';
import date from '../fields/date';
import SaleArtwork from '../sale_artwork';
import Profile from '../profile';
import Image from '../image/index';
import {
  GraphQLString,
  GraphQLObjectType,
  GraphQLNonNull,
  GraphQLList,
  GraphQLBoolean,
} from 'graphql';

export function auctionState({ start_at, end_at }) {
  const start = moment(start_at);
  const end = moment(end_at);
  if (moment().isAfter(end) || moment().isSame(end)) {
    return 'closed';
  } else if (moment().isBetween(start, end)) {
    return 'open';
  } else if (moment().isBefore(start) || moment().isSame(start)) {
    return 'preview';
  }
}

const SaleType = new GraphQLObjectType({
  name: 'Sale',
  fields: () => {
    return {
      cached,
      id: {
        type: GraphQLString,
      },
      name: {
        type: GraphQLString,
      },
      href: {
        type: GraphQLString,
        resolve: ({ id }) => `/auction/${id}`,
      },
      description: {
        type: GraphQLString,
      },
      sale_type: {
        type: GraphQLString,
      },
      is_auction: {
        type: GraphQLBoolean,
      },
      is_auction_promo: {
        type: GraphQLBoolean,
        resolve: ({ sale_type }) => sale_type === 'auction promo',
      },
      is_preview: {
        type: GraphQLBoolean,
        resolve: (sale) =>
          auctionState(sale) === 'preview',
      },
      is_open: {
        type: GraphQLBoolean,
        resolve: (sale) =>
          auctionState(sale) === 'open',
      },
      is_closed: {
        type: GraphQLBoolean,
        resolve: (sale) =>
          auctionState(sale) === 'closed',
      },
      is_with_buyers_premium: {
        type: GraphQLBoolean,
        resolve: ({ buyers_premium }) => buyers_premium,
      },
      auction_state: {
        type: GraphQLString,
        resolve: auctionState,
      },
      start_at: date,
      end_at: date,
      currency: {
        type: GraphQLString,
      },
      sale_artworks: {
        type: new GraphQLList(SaleArtwork.type),
        resolve: ({ id }, options) => gravity(`sale/${id}/sale_artworks`, options),
      },
      cover_image: {
        type: Image.type,
        resolve: ({ image_versions, image_url }) => Image.resolve({ image_versions, image_url }),
      },
      sale_artwork: {
        type: SaleArtwork.type,
        args: {
          id: {
            type: new GraphQLNonNull(GraphQLString),
          },
        },
        resolve: (sale, { id }) => {
          return gravity(`sale/${sale.id}/sale_artwork/${id}`);
        },
      },
      profile: {
        type: Profile.type,
        resolve: ({ profile }) => profile,
      },
    };
  },
});

const Sale = {
  type: SaleType,
  description: 'A Sale',
  args: {
    id: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The slug or ID of the Sale',
    },
  },
  resolve: (root, { id }) => gravity(`sale/${id}`),
};

export default Sale;
<commit_msg>add _id to schema<commit_after>import moment from 'moment';
import gravity from '../../lib/loaders/gravity';
import cached from '../fields/cached';
import date from '../fields/date';
import SaleArtwork from '../sale_artwork';
import Profile from '../profile';
import Image from '../image/index';
import {
  GraphQLString,
  GraphQLObjectType,
  GraphQLNonNull,
  GraphQLList,
  GraphQLBoolean,
} from 'graphql';

export function auctionState({ start_at, end_at }) {
  const start = moment(start_at);
  const end = moment(end_at);
  if (moment().isAfter(end) || moment().isSame(end)) {
    return 'closed';
  } else if (moment().isBetween(start, end)) {
    return 'open';
  } else if (moment().isBefore(start) || moment().isSame(start)) {
    return 'preview';
  }
}

const SaleType = new GraphQLObjectType({
  name: 'Sale',
  fields: () => {
    return {
      cached,
      id: {
        type: GraphQLString,
      },
      _id: {
        type: GraphQLString,
      },
      name: {
        type: GraphQLString,
      },
      href: {
        type: GraphQLString,
        resolve: ({ id }) => `/auction/${id}`,
      },
      description: {
        type: GraphQLString,
      },
      sale_type: {
        type: GraphQLString,
      },
      is_auction: {
        type: GraphQLBoolean,
      },
      is_auction_promo: {
        type: GraphQLBoolean,
        resolve: ({ sale_type }) => sale_type === 'auction promo',
      },
      is_preview: {
        type: GraphQLBoolean,
        resolve: (sale) =>
          auctionState(sale) === 'preview',
      },
      is_open: {
        type: GraphQLBoolean,
        resolve: (sale) =>
          auctionState(sale) === 'open',
      },
      is_closed: {
        type: GraphQLBoolean,
        resolve: (sale) =>
          auctionState(sale) === 'closed',
      },
      is_with_buyers_premium: {
        type: GraphQLBoolean,
        resolve: ({ buyers_premium }) => buyers_premium,
      },
      auction_state: {
        type: GraphQLString,
        resolve: auctionState,
      },
      start_at: date,
      end_at: date,
      currency: {
        type: GraphQLString,
      },
      sale_artworks: {
        type: new GraphQLList(SaleArtwork.type),
        resolve: ({ id }, options) => gravity(`sale/${id}/sale_artworks`, options),
      },
      cover_image: {
        type: Image.type,
        resolve: ({ image_versions, image_url }) => Image.resolve({ image_versions, image_url }),
      },
      sale_artwork: {
        type: SaleArtwork.type,
        args: {
          id: {
            type: new GraphQLNonNull(GraphQLString),
          },
        },
        resolve: (sale, { id }) => {
          return gravity(`sale/${sale.id}/sale_artwork/${id}`);
        },
      },
      profile: {
        type: Profile.type,
        resolve: ({ profile }) => profile,
      },
    };
  },
});

const Sale = {
  type: SaleType,
  description: 'A Sale',
  args: {
    id: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The slug or ID of the Sale',
    },
  },
  resolve: (root, { id }) => gravity(`sale/${id}`),
};

export default Sale;
<|endoftext|>


<commit_before>
process.env.NODE_ENV = 'test';

var assert = require('assert');
var connect = require('connect');
var request = require('supertest');
var session = require('..');

describe('Cookie Session', function(){
  var cookie;

  describe('when options.signed = true', function(){
    describe('when app.keys are set', function(){
      it('should work', function(done){
        var app = connect();
        app.use(session({
          keys: ['a', 'b']
        }));
        app.use(function (req, res, next) {
          req.session.message = 'hi';
          res.end();
        })

        request(app.listen())
        .get('/')
        .expect(200, '', done)
      })
    })

    describe('when app.keys are not set', function(){
      it('should throw', function(){
        assert.throws(function () {
          session();
        });
      })
    })
  })

  describe('when options.signed = false', function(){
    describe('when app.keys are not set', function(){
      it('should work', function(done){
        var app = connect();
        app.use(session({
          signed: false
        }));
        app.use(function (req, res, next) {
          req.session.message = 'hi';
          res.end();
        })

        request(app.listen())
        .get('/')
        .expect(200, done);
      })
    })
  })

  describe('when options.secure = true', function(){
    describe('when connection not secured', function(){
      it('should not Set-Cookie', function(done) {
        var app = App({ secure: true });
        app.use(function (req, res, next) {
          process.nextTick(function(){
            req.session.message = 'hello!';
            res.end('greetings');
          })
        })

        request(app)
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })
  })

  describe('when the session contains a ;', function(){
    it('should still work', function(done){
      var app = App();
      app.use(function (req, res, next) {
        if (req.method === 'POST') {
          req.session.string = ';';
          res.statusCode = 204;
          res.end();
        } else {
          res.end(req.session.string);
        }
      })

      var server = app.listen();
      request(server)
      .post('/')
      .expect(shouldHaveCookie('express.sess'))
      .expect(204, function(err, res){
        if (err) return done(err);
        var cookie = res.headers['set-cookie'];
        request(server)
        .get('/')
        .set('Cookie', cookie.join(';'))
        .expect(';', done);
      })
    })
  })

  describe('when the session is invalid', function(){
    it('should create new session', function(done){
      var app = App({ name: 'session', signed: false });
      app.use(function (req, res, next) {
        res.end(String(req.session.isNew))
      })

      request(app)
      .get('/')
      .set('Cookie', 'session=bogus')
      .expect(200, 'true', done)
    })
  })

  describe('new session', function(){
    describe('when not accessed', function(){
      it('should not Set-Cookie', function(done) {
        var app = App();
        app.use(function (req, res, next) {
          res.end('greetings');
        })

        request(app.listen())
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })

    describe('when accessed and not populated', function(done){
      it('should not Set-Cookie', function(done) {
        var app = App();
        app.use(function (req, res, next) {
          req.session;
          res.end('greetings');
        })

        request(app.listen())
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })

    describe('when populated', function(done){
      it('should Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session.message = 'hello';
          res.end();
        })

        request(app.listen())
        .get('/')
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, function(err, res){
          if (err) return done(err);
          cookie = res.header['set-cookie'].join(';');
          done();
        })
      })

      it('should not Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          res.end(JSON.stringify(this.session));
        })

        request(app.listen())
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })
  })

  describe('saved session', function(){
    describe('when not accessed', function(){
      it('should not Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          res.end('aklsjdfklasjdf');
        })

        request(app.listen())
        .get('/')
        .set('Cookie', cookie)
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })

    describe('when accessed but not changed', function(){
      it('should be the same session', function(done){
        var app = App();
        app.use(function (req, res, next) {
          assert.equal(req.session.message, 'hello');
          res.end('aklsjdfkljasdf');
        })

        request(app.listen())
        .get('/')
        .set('Cookie', cookie)
        .expect(200, done);
      })

      it('should not Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          assert.equal(req.session.message, 'hello');
          res.end('aklsjdfkljasdf');
        })

        request(app.listen())
        .get('/')
        .set('Cookie', cookie)
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })

    describe('when accessed and changed', function(){
      it('should Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session.money = '$$$';
          res.end('klajsdlkfjadsf');
        })

        request(app.listen())
        .get('/')
        .set('Cookie', cookie)
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, done);
      })
    })
  })

  describe('when session = ', function(){
    describe('null', function(){
      it('should expire the session', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session = null;
          res.end('lkajsdf');
        })

        request(app.listen())
        .get('/')
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, done);
      })

      it('should no longer return a session', function (done) {
        var app = App()
        app.use(function (req, res, next) {
          req.session = null
          res.end(JSON.stringify(req.session))
        })

        request(app.listen())
        .get('/')
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, 'null', done)
      })
    })

    describe('{}', function(){
      it('should not Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session = {};
          res.end('hello, world');
        })

        request(app.listen())
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, 'hello, world', done)
      })
    })

    describe('{a: b}', function(){
      it('should create a session', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session = { message: 'hello' };
          res.end('klajsdfasdf');
        })

        request(app.listen())
        .get('/')
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, done);
      })
    })

    describe('anything else', function(){
      it('should throw', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session = 'aklsdjfasdf';
        })

        request(app.listen())
        .get('/')
        .expect(500, done);
      })
    })
  })

  describe('req.session', function () {
    describe('.isPopulated', function () {
      it('should be false on new session', function (done) {
        var app = App();
        app.use(function (req, res, next) {
          res.end(String(req.session.isPopulated))
        })

        request(app.listen())
        .get('/')
        .expect(200, 'false', done)
      })

      it('should be true after adding property', function (done) {
        var app = App();
        app.use(function (req, res, next) {
          req.session.message = 'hello!'
          res.end(String(req.session.isPopulated))
        })

        request(app.listen())
        .get('/')
        .expect(200, 'true', done)
      })
    })
  })

  describe('req.sessionOptions', function () {
    it('should be the session options', function (done) {
      var app = App({ name: 'session' })
      app.use(function (req, res, next) {
        res.end(String(req.sessionOptions.name))
      })

      request(app)
      .get('/')
      .expect(200, 'session', done)
    })

    it('should alter the cookie setting', function (done) {
      var app = App({ maxAge: 3600000, name: 'session' })
      app.use(function (req, res, next) {
        if (req.url === '/max') {
          req.sessionOptions.maxAge = 6500000
        }

        req.session.message = 'hello!'
        res.end()
      })

      request(app)
      .get('/')
      .expect(function (res) {
        var date = new Date(res.headers.date)
        var expires = new Date(res.headers['set-cookie'][0].match(/expires=([^;]+)/)[1])
        assert.ok(expires - date <= 3600000)
      })
      .expect(200, function (err) {
        if (err) return done(err)
        request(app)
        .get('/max')
        .expect(function (res) {
          var date = new Date(res.headers.date)
          var expires = new Date(res.headers['set-cookie'][0].match(/expires=([^;]+)/)[1])
          assert.ok(expires - date > 5000000)
        })
        .expect(200, done)
      })
    })
  })
})

function App(options) {
  options = options || {};
  options.keys = ['a', 'b'];
  var app = connect();
  app.use(session(options));
  return app;
}

function shouldHaveCookie(name) {
  return function (res) {
    assert.ok(res.headers['set-cookie'].some(function (cookie) {
      return cookie.split('=')[0] === name
    }), 'should have cookie "' + name + '"')
  }
}

function shouldNotSetCookies() {
  return function (res) {
    assert.strictEqual(res.headers['set-cookie'], undefined, 'should not set cookies')
  }
}
<commit_msg>tests: remove unnecessary listen() in tests for supertest<commit_after>
process.env.NODE_ENV = 'test';

var assert = require('assert');
var connect = require('connect');
var request = require('supertest');
var session = require('..');

describe('Cookie Session', function(){
  var cookie;

  describe('when options.signed = true', function(){
    describe('when app.keys are set', function(){
      it('should work', function(done){
        var app = connect();
        app.use(session({
          keys: ['a', 'b']
        }));
        app.use(function (req, res, next) {
          req.session.message = 'hi';
          res.end();
        })

        request(app)
        .get('/')
        .expect(200, '', done)
      })
    })

    describe('when app.keys are not set', function(){
      it('should throw', function(){
        assert.throws(function () {
          session();
        });
      })
    })
  })

  describe('when options.signed = false', function(){
    describe('when app.keys are not set', function(){
      it('should work', function(done){
        var app = connect();
        app.use(session({
          signed: false
        }));
        app.use(function (req, res, next) {
          req.session.message = 'hi';
          res.end();
        })

        request(app)
        .get('/')
        .expect(200, done);
      })
    })
  })

  describe('when options.secure = true', function(){
    describe('when connection not secured', function(){
      it('should not Set-Cookie', function(done) {
        var app = App({ secure: true });
        app.use(function (req, res, next) {
          process.nextTick(function(){
            req.session.message = 'hello!';
            res.end('greetings');
          })
        })

        request(app)
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })
  })

  describe('when the session contains a ;', function(){
    it('should still work', function(done){
      var app = App();
      app.use(function (req, res, next) {
        if (req.method === 'POST') {
          req.session.string = ';';
          res.statusCode = 204;
          res.end();
        } else {
          res.end(req.session.string);
        }
      })

      request(app)
      .post('/')
      .expect(shouldHaveCookie('express.sess'))
      .expect(204, function(err, res){
        if (err) return done(err);
        var cookie = res.headers['set-cookie'];
        request(app)
        .get('/')
        .set('Cookie', cookie.join(';'))
        .expect(';', done);
      })
    })
  })

  describe('when the session is invalid', function(){
    it('should create new session', function(done){
      var app = App({ name: 'session', signed: false });
      app.use(function (req, res, next) {
        res.end(String(req.session.isNew))
      })

      request(app)
      .get('/')
      .set('Cookie', 'session=bogus')
      .expect(200, 'true', done)
    })
  })

  describe('new session', function(){
    describe('when not accessed', function(){
      it('should not Set-Cookie', function(done) {
        var app = App();
        app.use(function (req, res, next) {
          res.end('greetings');
        })

        request(app)
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })

    describe('when accessed and not populated', function(done){
      it('should not Set-Cookie', function(done) {
        var app = App();
        app.use(function (req, res, next) {
          req.session;
          res.end('greetings');
        })

        request(app)
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })

    describe('when populated', function(done){
      it('should Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session.message = 'hello';
          res.end();
        })

        request(app)
        .get('/')
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, function(err, res){
          if (err) return done(err);
          cookie = res.header['set-cookie'].join(';');
          done();
        })
      })

      it('should not Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          res.end(JSON.stringify(this.session));
        })

        request(app)
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })
  })

  describe('saved session', function(){
    describe('when not accessed', function(){
      it('should not Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          res.end('aklsjdfklasjdf');
        })

        request(app)
        .get('/')
        .set('Cookie', cookie)
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })

    describe('when accessed but not changed', function(){
      it('should be the same session', function(done){
        var app = App();
        app.use(function (req, res, next) {
          assert.equal(req.session.message, 'hello');
          res.end('aklsjdfkljasdf');
        })

        request(app)
        .get('/')
        .set('Cookie', cookie)
        .expect(200, done);
      })

      it('should not Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          assert.equal(req.session.message, 'hello');
          res.end('aklsjdfkljasdf');
        })

        request(app)
        .get('/')
        .set('Cookie', cookie)
        .expect(shouldNotSetCookies())
        .expect(200, done)
      })
    })

    describe('when accessed and changed', function(){
      it('should Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session.money = '$$$';
          res.end('klajsdlkfjadsf');
        })

        request(app)
        .get('/')
        .set('Cookie', cookie)
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, done);
      })
    })
  })

  describe('when session = ', function(){
    describe('null', function(){
      it('should expire the session', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session = null;
          res.end('lkajsdf');
        })

        request(app)
        .get('/')
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, done);
      })

      it('should no longer return a session', function (done) {
        var app = App()
        app.use(function (req, res, next) {
          req.session = null
          res.end(JSON.stringify(req.session))
        })

        request(app)
        .get('/')
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, 'null', done)
      })
    })

    describe('{}', function(){
      it('should not Set-Cookie', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session = {};
          res.end('hello, world');
        })

        request(app)
        .get('/')
        .expect(shouldNotSetCookies())
        .expect(200, 'hello, world', done)
      })
    })

    describe('{a: b}', function(){
      it('should create a session', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session = { message: 'hello' };
          res.end('klajsdfasdf');
        })

        request(app)
        .get('/')
        .expect(shouldHaveCookie('express.sess'))
        .expect(200, done);
      })
    })

    describe('anything else', function(){
      it('should throw', function(done){
        var app = App();
        app.use(function (req, res, next) {
          req.session = 'aklsdjfasdf';
        })

        request(app)
        .get('/')
        .expect(500, done);
      })
    })
  })

  describe('req.session', function () {
    describe('.isPopulated', function () {
      it('should be false on new session', function (done) {
        var app = App();
        app.use(function (req, res, next) {
          res.end(String(req.session.isPopulated))
        })

        request(app)
        .get('/')
        .expect(200, 'false', done)
      })

      it('should be true after adding property', function (done) {
        var app = App();
        app.use(function (req, res, next) {
          req.session.message = 'hello!'
          res.end(String(req.session.isPopulated))
        })

        request(app)
        .get('/')
        .expect(200, 'true', done)
      })
    })
  })

  describe('req.sessionOptions', function () {
    it('should be the session options', function (done) {
      var app = App({ name: 'session' })
      app.use(function (req, res, next) {
        res.end(String(req.sessionOptions.name))
      })

      request(app)
      .get('/')
      .expect(200, 'session', done)
    })

    it('should alter the cookie setting', function (done) {
      var app = App({ maxAge: 3600000, name: 'session' })
      app.use(function (req, res, next) {
        if (req.url === '/max') {
          req.sessionOptions.maxAge = 6500000
        }

        req.session.message = 'hello!'
        res.end()
      })

      request(app)
      .get('/')
      .expect(function (res) {
        var date = new Date(res.headers.date)
        var expires = new Date(res.headers['set-cookie'][0].match(/expires=([^;]+)/)[1])
        assert.ok(expires - date <= 3600000)
      })
      .expect(200, function (err) {
        if (err) return done(err)
        request(app)
        .get('/max')
        .expect(function (res) {
          var date = new Date(res.headers.date)
          var expires = new Date(res.headers['set-cookie'][0].match(/expires=([^;]+)/)[1])
          assert.ok(expires - date > 5000000)
        })
        .expect(200, done)
      })
    })
  })
})

function App(options) {
  options = options || {};
  options.keys = ['a', 'b'];
  var app = connect();
  app.use(session(options));
  return app;
}

function shouldHaveCookie(name) {
  return function (res) {
    assert.ok(res.headers['set-cookie'].some(function (cookie) {
      return cookie.split('=')[0] === name
    }), 'should have cookie "' + name + '"')
  }
}

function shouldNotSetCookies() {
  return function (res) {
    assert.strictEqual(res.headers['set-cookie'], undefined, 'should not set cookies')
  }
}
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-17 09:38:31<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>// Check SCSS for code quality
module.exports = function(grunt) {
    grunt.config('scsslint', {
        options: {
            bundleExec: false,
            colorizeOutput: true,
            compact: true,
            config: '.scss-lint.yml',
            exclude: [
                'scss/base/_normalize.scss',
                'scss/lib/mixins/_typography.scss',
                'scss/lib/mixins/_units.scss',
                'scss/lib/parts/_forms.scss',
                'scss/lib/parts/_images.scss'
            ],
            reporterOutput: null
        },
        all: [
            'scss/**/*.scss'
        ]
    });

    grunt.loadNpmTasks('grunt-scss-lint');
};
<commit_msg>Fix path in scss-lint config<commit_after>// Check SCSS for code quality
module.exports = function(grunt) {
    grunt.config('scsslint', {
        options: {
            bundleExec: false,
            colorizeOutput: true,
            compact: true,
            config: '.scss-lint.yml',
            exclude: [
                'scss/ext/_normalize.scss',
                'scss/lib/mixins/_typography.scss',
                'scss/lib/mixins/_units.scss',
                'scss/lib/parts/_forms.scss',
                'scss/lib/parts/_images.scss'
            ],
            reporterOutput: null
        },
        all: [
            'scss/**/*.scss'
        ]
    });

    grunt.loadNpmTasks('grunt-scss-lint');
};
<|endoftext|>