<commit_before>'use strict';
const proxyquire = require('proxyquire').noPreserveCache();;
const fs = require('fs');
const path = require('path');
const EventEmitter = require('events').EventEmitter;
const util = require('util');

function StubEmitter() {
  EventEmitter.call(this);
}
util.inherits(StubEmitter, EventEmitter);
StubEmitter.prototype.pipe = function () {
  // noop.
};

const should = require('should');

let stub;
let requestStub = {
  get: () => {
    return stub
  }
}

describe('downloadArchive module', function() {
  it('Should export a function', () => {
    require('../src/downloadArchive').should.be.instanceOf(Function);
  });
  it('Should do as expected', (done) => {
    let port = 8866;
    let server = require('http').createServer((req, res) => {
      res.end('testResponse')
    }).listen(port);
    require('../src/downloadArchive')(`http://localhost:${port}/1234.tar.gz`, (err, d) => {
      // See that the contents of the file is as expected.
      fs.readFileSync(path.join(process.cwd(), d)).toString().should.equal('testResponse');
      fs.unlinkSync(path.join(process.cwd(), d));
      server.close();
      done(err);
    });
  });
  it('Should call the callback only once, even if we force it to do something stupid', (done) => {
    stub = new StubEmitter();
    proxyquire('./../src/downloadArchive', {
      'request': requestStub
    })('http://localhost:8866/1234.tar.gz', (err, d) => {
      fs.unlinkSync(path.join(process.cwd(), d));
      done(err);
    });
    setTimeout(_ => {
      stub.emit('end');
      stub.emit('error', new Error('problem'));
    }, 100);
  });
});

describe('extractArchive module', function() {
  it('Should export a function', () => {
    require('../src/extractArchive').should.be.instanceOf(Function);
  });
  it('Should return the filename when the file exists', (done) => {
    let fileName = 'TAR1337.tgz';
    fs.writeFileSync(fileName, '');
    require('../src/extractArchive')(fileName, (err, d) => {
      fs.unlinkSync(fileName);
      d.should.equal('1337');
      done(err);
    })
  })
  it('Should do as expected when encountering unknown file', (done) => {
    require('../src/extractArchive')('willneverxist.tar.gz', (err, d) => {
      err.code.should.equal('ENOENT');
      done()
    });
  });
});

describe('findArchive module', function() {
  // jsdom takes some time to start, some times.
  this.timeout(5000);
  it('Should export a function', () => {
    require('../src/findArchive').should.be.instanceOf(Function);
  });
  it('Should do as expected', (done) => {
    let port = 8877;
    let server = require('http').createServer((req, res) => {
      res.end('testtest2');
    }).listen(port);
    require('../src/findArchive')(`http://localhost:${port}`, (err, d) => {
      d.should.equal(`http://localhost:${port}/2.tgz`)
      done(err);
      server.close()
    });
  });
  it('Should do as expected when no archive is found', (done) => {
    let port = 8888;
    let server = require('http').createServer((req, res) => {
      res.end('testtest2');
    }).listen(port);
    require('../src/findArchive')(`http://localhost:${port}`, (err, d) => {
      should(d).equal(undefined);
      err.message.should.equal('No archive found.')
      server.close()
      done();
    });
  });
  it('Should do as expected when having jsdom error', (done) => {
    proxyquire('../src/findArchive', {
      'jsdom': {
        env: function(url, inject, callback) {
          callback(new Error(`No way will I inject ${inject} to ${url}`));
        }
      }
    })('http://example.com', (err, d) => {
      err.message.should.equal('No way will I inject http://code.jquery.com/jquery.js to http://example.com');
      done();
    });
  })
});

describe('uploadText module', function() {
  it('Should export a function', () => {
    require('../src/uploadText').should.be.instanceOf(Function);
  });
});
<commit_msg>Add tests for uploadText module.<commit_after>'use strict';
const proxyquire = require('proxyquire').noPreserveCache();;
const fs = require('fs');
const path = require('path');
const EventEmitter = require('events').EventEmitter;
const util = require('util');

function StubEmitter() {
  EventEmitter.call(this);
}
util.inherits(StubEmitter, EventEmitter);
StubEmitter.prototype.pipe = function () {
  // noop.
};

const should = require('should');

let stub;
let requestStub = {
  get: () => {
    return stub
  }
}

describe('downloadArchive module', function() {
  it('Should export a function', () => {
    require('../src/downloadArchive').should.be.instanceOf(Function);
  });
  it('Should do as expected', (done) => {
    let port = 8866;
    let server = require('http').createServer((req, res) => {
      res.end('testResponse')
    }).listen(port);
    require('../src/downloadArchive')(`http://localhost:${port}/1234.tar.gz`, (err, d) => {
      // See that the contents of the file is as expected.
      fs.readFileSync(path.join(process.cwd(), d)).toString().should.equal('testResponse');
      fs.unlinkSync(path.join(process.cwd(), d));
      server.close();
      done(err);
    });
  });
  it('Should call the callback only once, even if we force it to do something stupid', (done) => {
    stub = new StubEmitter();
    proxyquire('./../src/downloadArchive', {
      'request': requestStub
    })('http://localhost:8866/1234.tar.gz', (err, d) => {
      fs.unlinkSync(path.join(process.cwd(), d));
      done(err);
    });
    setTimeout(_ => {
      stub.emit('end');
      stub.emit('error', new Error('problem'));
    }, 100);
  });
});

describe('extractArchive module', function() {
  it('Should export a function', () => {
    require('../src/extractArchive').should.be.instanceOf(Function);
  });
  it('Should return the filename when the file exists', (done) => {
    let fileName = 'TAR1337.tgz';
    fs.writeFileSync(fileName, '');
    require('../src/extractArchive')(fileName, (err, d) => {
      fs.unlinkSync(fileName);
      d.should.equal('1337');
      done(err);
    })
  })
  it('Should do as expected when encountering unknown file', (done) => {
    require('../src/extractArchive')('willneverxist.tar.gz', (err, d) => {
      err.code.should.equal('ENOENT');
      done()
    });
  });
});

describe('findArchive module', function() {
  // jsdom takes some time to start, some times.
  this.timeout(5000);
  it('Should export a function', () => {
    require('../src/findArchive').should.be.instanceOf(Function);
  });
  it('Should do as expected', (done) => {
    let port = 8877;
    let server = require('http').createServer((req, res) => {
      res.end('testtest2');
    }).listen(port);
    require('../src/findArchive')(`http://localhost:${port}`, (err, d) => {
      d.should.equal(`http://localhost:${port}/2.tgz`)
      done(err);
      server.close()
    });
  });
  it('Should do as expected when no archive is found', (done) => {
    let port = 8888;
    let server = require('http').createServer((req, res) => {
      res.end('testtest2');
    }).listen(port);
    require('../src/findArchive')(`http://localhost:${port}`, (err, d) => {
      should(d).equal(undefined);
      err.message.should.equal('No archive found.')
      server.close()
      done();
    });
  });
  it('Should do as expected when having jsdom error', (done) => {
    proxyquire('../src/findArchive', {
      'jsdom': {
        env: function(url, inject, callback) {
          callback(new Error(`No way will I inject ${inject} to ${url}`));
        }
      }
    })('http://example.com', (err, d) => {
      err.message.should.equal('No way will I inject http://code.jquery.com/jquery.js to http://example.com');
      done();
    });
  })
});

describe('uploadText module', function() {
  it('Should export a function', () => {
    require('../src/uploadText').should.be.instanceOf(Function);
  });
  it('Should do as expected when response is as expected', (done) => {
    let port = 8899;
    let server = require('http').createServer((req, res) => {
      res.writeHead(302, {Location: 'http://example.com'});
      res.end();
    }).listen(port);
    require('../src/uploadText')(`http://localhost:${port}`, ['a', 'b'], (err, d) => {
      d.should.equal('http://example.com');
      done(err);
      server.close();
    });
  });
  it('Should do as expected when response is wrong', (done) => {
    let port = 9911;
    let server = require('http').createServer((req, res) => {
      res.end('hello');
    }).listen(port);
    require('../src/uploadText')(`http://localhost:${port}`, ['a', 'b'], (err, d) => {
      err.message.should.equal('No location header found');
      server.close();
      done();
    });
  });
  it('Should do as expected if request returns an error', (done) => {
    require('../src/uploadText')('noprotocol://horrible&domain:thisisnotaport', ['a', 'b'], (err, d) => {
      err.message.should.equal('Invalid protocol: noprotocol:');
      done();
    });
  })
});
<|endoftext|>


<commit_before>/*
 * node-libnmap
 *
 * Copyright 2014 Jason Gerfen
 * All rights reserved.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

var libnmap = require('../')

libnmap.nmap('scan', {
  flags: '-T4 -oG -',
  range: ['localhost', '10.0.2.0/25', '192.168.0.0/25', '192.168.0.128-253'],
  callback: function(err, report){
    if (err) throw err
    console.log(report)
  }
})
<commit_msg>test: Updated test case for scan method<commit_after>/*
 * node-libnmap
 *
 * Copyright 2014 Jason Gerfen
 * All rights reserved.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

var libnmap = require('../')

libnmap.nmap('scan', {
  flags: '-T4 -oG -',
  range: ['localhost', '10.0.2.0/25', '192.168.2.0/25', '192.168.0.128-253'],
  callback: function(err, report){
    if (err) throw err
    console.log(report)
  }
})
<|endoftext|>


<commit_before>var sys = require("sys"),
    assert = require("assert"),
    jsonCommand = require("../lib/jsonCommand");

var testObj = {
  id : 19375093,
  text : "who knows",
  user : {
    id : 1310571,
    name : "foo"
  },
  arr1 : [
    'a', 'b', 'c'
  ],
  obj1 : {
    arr2 : [
      'd', 'e', 'f'
    ]
  },
  created_at : 127817599,
  zero : 0
};

function printTestName(testName) {
  sys.puts("\nRunning " + testName + ":");
  sys.puts("-----------------------------------------");
}

(function testSimpleSetup() {

  (function testProcessArgs() {
    printTestName("testProcessArgs");

    var jsonC = new JSON.Command();
    var conditions = [ "(name == 'foo')", "(text == 'boo')" ];
    jsonC.processArgs([ "-c", conditions[0], "-c", conditions[1] ]);
    assert.equal(jsonC.conditionals[0], conditions[0],
      "conditionals contains specified conditional [0]");
    assert.equal(jsonC.conditionals[1], conditions[1],
      "conditionals contains specified conditional [1]");

  })();

  (function testCreateRequestedKeys() {
    printTestName("testCreateRequestedKeys");

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "newKey" ]);
    jsonC.createRequestedKeys(testObj);

    assert.equal(testObj.newKey, null,
      "createRequestedKeys adds requested key to object");

    jsonC = new JSON.Command();
    jsonC.processArgs([ "zero" ]);
    jsonC.createRequestedKeys(testObj);

    assert.equal(testObj.zero, 0,
      "createRequestedKeys does not add null for 0 to object");
  })();

  (function testCheckConditionals() {
    printTestName("testCheckConditionals");

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "-c", "(name == 'foo')"]);

    assert.equal(jsonC.checkConditionals(testObj), false,
      "checkConditionals (name=='foo') is false");

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "-c", "(user.name == 'foo')"]);

    assert.equal(jsonC.checkConditionals(testObj), true,
      "checkConditionals (user.name=='foo') is true");
  })();

  (function testProcessKeyTransforms() {
    printTestName("testProcessKeyTransforms");

    var tmpTestObj = {
      id : 19375093, text : "who knows", created_at : 127817599,
      user : {
        id : 1310571, name : "foo"
      }
    };

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "user.new_name=user.name", "-d"]);
    jsonC.createRequestedKeys(tmpTestObj);
    jsonC.processKeyTransforms(tmpTestObj);

    assert.equal(tmpTestObj.user.new_name, testObj.user.name,
      "processKeyTransforms user.new_name = user.name is true");

  })();

  (function testProcessExecutables() {
    printTestName("testProcessExecutables");

    var tmpTestObj = {
      id : 19375093, text : "who knows", created_at : 127817599,
      user : {
        id : 1310571, name : "foo"
      }
    };

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "-e", "user.name = 'boo';"]);
    jsonC.processExecutables(tmpTestObj);

    assert.equal(tmpTestObj.user.name, "boo",
      "processExecutables user.name = 'boo' is true");
  })();

  (function testProcessKeys() {
    printTestName("testProcessKeys");

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "user.name", "text", "arr1[1]", "obj1.arr2[2]" ]);
    assert.equal(jsonC.keys.length, 4,
      "processedKeys keys length == 4");

    var resObj = jsonC.processKeys(testObj);

    assert.equal(resObj.user.name, testObj.user.name,
      "processKeys result object user.name = testObj.user.name is true");
    assert.equal(resObj.text, testObj.text,
      "processKeys result object user.name = testObj.text is true");
    assert.equal(resObj.id, undefined,
      "processKeys result object id is undefined is true");
    assert.equal(resObj.created_at, undefined,
      "processKeys result object created_at is undefined is true");
    assert.equal(resObj.user.id, undefined,
      "processKeys result object user.id is undefined is true");
    assert.equal(resObj.arr1[0], testObj.arr1[1],
      "processKeys result object arr1[0] = testObj.arr1[0] is true");
    assert.equal(resObj.obj1.arr2[0], testObj.obj1.arr2[2],
      "processKeys result object obj1.arr2[0] = testObj.obj1.arr2[2] is true");

  })();

})();

sys.puts("\nAll tests passed!\n");
<commit_msg>remove sys module<commit_after>var assert = require("assert"),
    jsonCommand = require("../lib/jsonCommand");

var testObj = {
  id : 19375093,
  text : "who knows",
  user : {
    id : 1310571,
    name : "foo"
  },
  arr1 : [
    'a', 'b', 'c'
  ],
  obj1 : {
    arr2 : [
      'd', 'e', 'f'
    ]
  },
  created_at : 127817599,
  zero : 0
};

function printTestName(testName) {
  console.log("\nRunning " + testName + ":");
  console.log("-----------------------------------------");
}

(function testSimpleSetup() {

  (function testProcessArgs() {
    printTestName("testProcessArgs");

    var jsonC = new JSON.Command();
    var conditions = [ "(name == 'foo')", "(text == 'boo')" ];
    jsonC.processArgs([ "-c", conditions[0], "-c", conditions[1] ]);
    assert.equal(jsonC.conditionals[0], conditions[0],
      "conditionals contains specified conditional [0]");
    assert.equal(jsonC.conditionals[1], conditions[1],
      "conditionals contains specified conditional [1]");

  })();

  (function testCreateRequestedKeys() {
    printTestName("testCreateRequestedKeys");

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "newKey" ]);
    jsonC.createRequestedKeys(testObj);

    assert.equal(testObj.newKey, null,
      "createRequestedKeys adds requested key to object");

    jsonC = new JSON.Command();
    jsonC.processArgs([ "zero" ]);
    jsonC.createRequestedKeys(testObj);

    assert.equal(testObj.zero, 0,
      "createRequestedKeys does not add null for 0 to object");
  })();

  (function testCheckConditionals() {
    printTestName("testCheckConditionals");

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "-c", "(name == 'foo')"]);

    assert.equal(jsonC.checkConditionals(testObj), false,
      "checkConditionals (name=='foo') is false");

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "-c", "(user.name == 'foo')"]);

    assert.equal(jsonC.checkConditionals(testObj), true,
      "checkConditionals (user.name=='foo') is true");
  })();

  (function testProcessKeyTransforms() {
    printTestName("testProcessKeyTransforms");

    var tmpTestObj = {
      id : 19375093, text : "who knows", created_at : 127817599,
      user : {
        id : 1310571, name : "foo"
      }
    };

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "user.new_name=user.name", "-d"]);
    jsonC.createRequestedKeys(tmpTestObj);
    jsonC.processKeyTransforms(tmpTestObj);

    assert.equal(tmpTestObj.user.new_name, testObj.user.name,
      "processKeyTransforms user.new_name = user.name is true");

  })();

  (function testProcessExecutables() {
    printTestName("testProcessExecutables");

    var tmpTestObj = {
      id : 19375093, text : "who knows", created_at : 127817599,
      user : {
        id : 1310571, name : "foo"
      }
    };

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "-e", "user.name = 'boo';"]);
    jsonC.processExecutables(tmpTestObj);

    assert.equal(tmpTestObj.user.name, "boo",
      "processExecutables user.name = 'boo' is true");
  })();

  (function testProcessKeys() {
    printTestName("testProcessKeys");

    var jsonC = new JSON.Command();
    jsonC.processArgs([ "user.name", "text", "arr1[1]", "obj1.arr2[2]" ]);
    assert.equal(jsonC.keys.length, 4,
      "processedKeys keys length == 4");

    var resObj = jsonC.processKeys(testObj);

    assert.equal(resObj.user.name, testObj.user.name,
      "processKeys result object user.name = testObj.user.name is true");
    assert.equal(resObj.text, testObj.text,
      "processKeys result object user.name = testObj.text is true");
    assert.equal(resObj.id, undefined,
      "processKeys result object id is undefined is true");
    assert.equal(resObj.created_at, undefined,
      "processKeys result object created_at is undefined is true");
    assert.equal(resObj.user.id, undefined,
      "processKeys result object user.id is undefined is true");
    assert.equal(resObj.arr1[0], testObj.arr1[1],
      "processKeys result object arr1[0] = testObj.arr1[0] is true");
    assert.equal(resObj.obj1.arr2[0], testObj.obj1.arr2[2],
      "processKeys result object obj1.arr2[0] = testObj.obj1.arr2[2] is true");

  })();

})();

console.log("\nAll tests passed!\n");
<|endoftext|>


<commit_before>/*
 * Copyright (c) Sematext Group, Inc.
 * All Rights Reserved
 *
 * SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'
var config = require('../lib/util/spmconfig.js')
config.logger.console = false
config.logger.level = 'debug'
if (!config.tokens.spm) {
  config.tokens.spm = process.env.SPM_TOKEN || 'TEST_TEST_TEST_SPM_AGENT_TRAVIS'
}

describe('SPM for NodeJS tests', function () {
  it('SPM Agent Stats', function (done) {
    try {
      this.timeout(30000)
      config.collectionInterval = 1200
      config.retransmitInterval = 1000
      config.recoverInterval = 1000
      config.maxDataPoints = 1
      config.logger.console = true
      config.logger.level = 'debug'
      var SpmAgent = require('../lib/index.js')
      var client = new SpmAgent()
      var testAgent = client.createAgent(new SpmAgent.Agent({
        start: function (agent) {
          setTimeout(function () {
            agent.addMetrics({name: 'collectd5-disk-space-used\tdf-xvda1/df_complex-used', value: 3380457472.0, sct: 'OS'})
            agent.addMetrics({name: 'collectd-io-octets  disk-sda2/disk_octets', value: '0.000000,0.000000', sct: 'OS'})
            agent.addMetrics({name: 'test', sct: 'OS', value: [1, 2, 3]})
            agent.addMetrics({name: 'test', value: [1, 2, 3]})
          }, 900)
        },
        stop: console.log
      }))

      client.once('stats', function (stats) {
        done()
      })
    } catch (err) {
      console.log(err.stack)
      done(err)
    }
  })
  it('Logger should log', function (done) {
    try {
      var logger = require('../lib/util/logger.js')
      logger.log('Logger test %d', 1)
      done()
    } catch (err) {
      done(err)
    }
  })
  it('SPM Config has defaults', function (done) {
    try {
      var cfgValue = ['tokens.spm', 'recoverInterval', 'maxRetransmitBatchSize', 'spmSenderBulkInsertUrl', 'logger.dir', 'logger.filename', 'logger.level', 'maxDataPoints', 'collectionInterval']
      var checked = cfgValue.filter(function (key) {
        return (config.get(key) === null)
      })
      if (checked.length === 0) {
        done()
      } else {
        done('missing config values: ' + checked)
      }
    } catch (err) {
      done(err)
    }
  })
})
<commit_msg>add dynamic url parameters, via global setting<commit_after>/*
 * Copyright (c) Sematext Group, Inc.
 * All Rights Reserved
 *
 * SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'
var config = require('../lib/util/spmconfig.js')
config.logger.console = false
config.logger.level = 'debug'
if (!config.tokens.spm) {
  config.tokens.spm = process.env.SPM_TOKEN || 'TEST_TEST_TEST_SPM_AGENT_TRAVIS'
}
global.spmSenderUrlParameters = '&countainerCount=1'

describe('SPM for NodeJS tests', function () {
  it('SPM Agent Stats', function (done) {
    try {
      this.timeout(30000)
      config.collectionInterval = 1200
      config.retransmitInterval = 1000
      config.recoverInterval = 1000
      config.maxDataPoints = 1
      config.logger.console = true
      config.logger.level = 'debug'
      var SpmAgent = require('../lib/index.js')
      var client = new SpmAgent()
      var testAgent = client.createAgent(new SpmAgent.Agent({
        start: function (agent) {
          setTimeout(function () {
            agent.addMetrics({name: 'collectd5-disk-space-used\tdf-xvda1/df_complex-used', value: 3380457472.0, sct: 'OS'})
            agent.addMetrics({name: 'collectd-io-octets  disk-sda2/disk_octets', value: '0.000000,0.000000', sct: 'OS'})
            agent.addMetrics({name: 'test', sct: 'OS', value: [1, 2, 3]})
            agent.addMetrics({name: 'test', value: [1, 2, 3]})
          }, 900)
        },
        stop: console.log
      }))

      client.once('stats', function (stats) {
        done()
      })
    } catch (err) {
      console.log(err.stack)
      done(err)
    }
  })
  it('Logger should log', function (done) {
    try {
      var logger = require('../lib/util/logger.js')
      logger.log('Logger test %d', 1)
      done()
    } catch (err) {
      done(err)
    }
  })
  it('SPM Config has defaults', function (done) {
    try {
      var cfgValue = ['tokens.spm', 'recoverInterval', 'maxRetransmitBatchSize', 'spmSenderBulkInsertUrl', 'logger.dir', 'logger.filename', 'logger.level', 'maxDataPoints', 'collectionInterval']
      var checked = cfgValue.filter(function (key) {
        return (config.get(key) === null)
      })
      if (checked.length === 0) {
        done()
      } else {
        done('missing config values: ' + checked)
      }
    } catch (err) {
      done(err)
    }
  })
})
<|endoftext|>


<commit_before>/* jshint expr: true */
var expect = require('chai').expect;
var Ractive = require('ractive');

var child, parent, adapt, subchild;

describe('ractive-ractive', function () {
  before(function () {
    require('../index');
    adapt = Ractive.adaptors.Ractive;
    Ractive.defaults.adapt = ['Ractive'];
  });

  /*
   * simple cases
   */

  describe('simple', function () {
    beforeEach(function () {
      child  = new Ractive();
      parent = new Ractive();
    });

    it(".get picks up the child's value", function () {
      child.set('enabled', 1);
      parent.set('child', child);

      expect(parent.get('child.enabled')).eql(1);
    });

    it('propagates changes from child to parent', function () {
      child.set('enabled', 1);
      parent.set('child', child);
      child.set('enabled', 2);

      expect(parent.get('child.enabled')).eql(2);
    });

    /*
     * ensure that you can observe changes in the child via the parent.
     */

    it('can observe changes of the child', function (next) {
      var runs = 0;
      parent.set('child', child);

      parent.observe('child.enabled', function (val) {
        runs++;
        if (runs === 1) {
          expect(val).be.undefined;
        }
        else if (runs === 2) {
          expect(val).eql(2);
          next();
        }
      });

      child.set('enabled', 2);
    });

    it('updates the parent HTML when the child updates', function () {
      parent = new Ractive({
        template: "{{#child}}value={{enabled}}{{/child}}"
      });

      parent.set('child', child);

      child.set('enabled', 1);
      expect(parent.toHTML()).eql('value=1');

      child.set('enabled', 2);
      expect(parent.toHTML()).eql('value=2');
    });

    it('works bidirectionally by propagating parent changes to child', function () {
      parent.set('child', child);
      parent.set('child.enabled', 2);

      expect(child.get('enabled')).eql(2);
    });

    it('works bidirectionally with html', function () {
      child = new Ractive({
        template: "value={{enabled}}"
      });

      expect(child.toHTML()).eql('value=');

      parent.set('child', child);
      expect(child.toHTML()).eql('value=');

      parent.set('child.enabled', 2);
      expect(child.toHTML()).eql('value=2');
    });

    it('handles reset', function () {
      parent.set('child', child);
      parent.set('child', { enabled: 300 });

      expect(child.get('enabled')).eql(300);
    });
  });

  /*
   * deep nesting
   */

  describe('deeply-nested cases', function () {
    beforeEach(function () {
      subchild = new Ractive();
      child    = new Ractive();
      parent   = new Ractive();

      parent.set('child', child);
      child.set('subchild', subchild);
    });

    it('works upwards', function () {
      subchild.set('enabled', 20);
      expect(parent.get('child.subchild.enabled')).eql(20);

      subchild.set('enabled', 200);
      expect(parent.get('child.subchild.enabled')).eql(200);
    });

    it('works downwards', function () {
      parent.set('child.subchild.enabled', 20);

      expect(subchild.get('enabled')).eql(20);
      expect(child.get('subchild.enabled')).eql(20);
      expect(parent.get('child.subchild.enabled')).eql(20);
    });
  });

  /*
   * filter function
   */

  describe('filter', function () {
    it('works', function () {
      var obj = new Ractive();
      expect(adapt.filter(obj)).eql(true);
    });

    it('works for negatives: object', function () {
      var obj = {};
      expect(adapt.filter(obj)).eql(false);
    });

    it('works for negatives: array', function () {
      var obj = [];
      expect(adapt.filter(obj)).eql(false);
    });
  });
});
<commit_msg>Add more tests.<commit_after>/* jshint expr: true */
var expect = require('chai').expect;
var Ractive = require('ractive');

var child, parent, adapt, subchild;

describe('ractive-ractive', function () {
  before(function () {
    require('../index');
    adapt = Ractive.adaptors.Ractive;
    Ractive.defaults.adapt = ['Ractive'];
  });

  /*
   * simple cases
   */

  describe('simple', function () {
    beforeEach(function () {
      child  = new Ractive();
      parent = new Ractive();
    });

    it(".get picks up the child's value", function () {
      child.set('enabled', 1);
      parent.set('child', child);

      expect(parent.get('child.enabled')).eql(1);
    });

    it('propagates changes from child to parent', function () {
      child.set('enabled', 1);
      parent.set('child', child);
      child.set('enabled', 2);

      expect(parent.get('child.enabled')).eql(2);
    });

    /*
     * ensure that you can observe changes in the child via the parent.
     */

    it('can observe changes of the child', function (next) {
      var runs = 0;
      parent.set('child', child);

      parent.observe('child.enabled', function (val) {
        runs++;
        if (runs === 1) {
          expect(val).be.undefined;
        }
        else if (runs === 2) {
          expect(val).eql(2);
          next();
        }
      });

      child.set('enabled', 2);
    });

    it('updates the parent HTML when the child updates', function () {
      parent = new Ractive({
        template: "{{#child}}value={{enabled}}{{/child}}"
      });

      parent.set('child', child);

      child.set('enabled', 1);
      expect(parent.toHTML()).eql('value=1');

      child.set('enabled', 2);
      expect(parent.toHTML()).eql('value=2');
    });

    it('works bidirectionally by propagating parent changes to child', function () {
      parent.set('child', child);
      parent.set('child.enabled', 2);

      expect(child.get('enabled')).eql(2);
    });

    it('works bidirectionally with html', function () {
      child = new Ractive({
        template: "value={{enabled}}"
      });

      expect(child.toHTML()).eql('value=');

      parent.set('child', child);
      expect(child.toHTML()).eql('value=');

      parent.set('child.enabled', 2);
      expect(child.toHTML()).eql('value=2');
    });

    it('handles being reset to an object', function () {
      parent.set('child', child);
      parent.set('child', { enabled: 300 });

      expect(child.get('enabled')).eql(300);
    });

    it('handles being reset to undefined', function () {
      parent.set('child', child);
      parent.set('child', undefined);
    });
  });

  /*
   * deep nesting
   */

  describe('deeply-nested cases', function () {
    beforeEach(function () {
      subchild = new Ractive();
      child    = new Ractive();
      parent   = new Ractive();

      parent.set('child', child);
      child.set('subchild', subchild);
    });

    it('works upwards', function () {
      subchild.set('enabled', 20);
      expect(parent.get('child.subchild.enabled')).eql(20);

      subchild.set('enabled', 200);
      expect(parent.get('child.subchild.enabled')).eql(200);
    });

    it('works downwards', function () {
      parent.set('child.subchild.enabled', 20);

      expect(subchild.get('enabled')).eql(20);
      expect(child.get('subchild.enabled')).eql(20);
      expect(parent.get('child.subchild.enabled')).eql(20);
    });

    it('handles teardown properly', function () {
      parent.set('child.subchild.enabled', 20);
      child.set('subchild', undefined);

      expect(parent.get('child.subchild.enabled')).be.undefined;
      expect(child.get('subchild.enabled')).be.undefined;
    });
  });

  /*
   * filter function
   */

  describe('filter', function () {
    it('works', function () {
      var obj = new Ractive();
      expect(adapt.filter(obj)).eql(true);
    });

    it('works for negatives: object', function () {
      var obj = {};
      expect(adapt.filter(obj)).eql(false);
    });

    it('works for negatives: array', function () {
      var obj = [];
      expect(adapt.filter(obj)).eql(false);
    });
  });
});
<|endoftext|>


<commit_before>/* eslint filenames/match-regex: 0 */
'use strict'

const Promise = require('bluebird')
const path = require('path')
const chai = require('chai')

require('sinon-as-promised')(Promise)

const expect = chai.expect

const TEST_APP = path.join(__dirname, 'fullcube-templates')
const app = require(path.join(TEST_APP, 'server/server.js'))

const Template = app.models.Template

describe('Component', function() {
  describe('Initialization', function() {
    it('should add a getStateMachine method to the app', function() {
      expect(Template).to.itself.respondTo('_templates')
    })
  })
})

describe('Create dummy data from templates', function() {
  before(function() {
    this.templates = Template._templates()
  })

  it('should have templates defined', function() {
    expect(this.templates).to.be.an('object')
    expect(this.templates.Application).to.be.an('object')
    expect(this.templates.Card).to.be.an('object')
    expect(this.templates.Person).to.be.an('object')
    expect(this.templates.Product).to.be.an('object')
    expect(this.templates.ProductBasic).to.be.an('object')
    expect(this.templates.ProductShirt).to.be.an('object')
    expect(this.templates.Program).to.be.an('object')
    expect(this.templates.User).to.be.an('object')
  })

  it('should have methods defined', function() {
    this.templateNames = Object.keys(this.templates)
    this.templateNames.forEach(templateName => {
      const methodName = `_template_${templateName}`

      it(`should had a method for template ${templateName}`, function() {
        expect(Template).to.itself.respondTo(methodName)
      })
    })
  })

})
<commit_msg>Enhance tests to get a 100% coverage<commit_after>/* eslint filenames/match-regex: 0 */
'use strict'

const Promise = require('bluebird')
const path = require('path')
const chai = require('chai')

require('sinon-as-promised')(Promise)

const expect = chai.expect

const TEST_APP = path.join(__dirname, 'fullcube-templates')
const app = require(path.join(TEST_APP, 'server/server.js'))

const Template = app.models.Template

describe('Component', function() {
  describe('Initialization', function() {
    it('should add a getStateMachine method to the app', function() {
      expect(Template).to.itself.respondTo('_templates')
    })
  })
})

describe('Create dummy data from templates', function() {
  before(function() {
    this.templates = Template._templates()
  })

  it('should have templates defined', function() {
    expect(this.templates).to.be.an('object')
    expect(this.templates.Application).to.be.an('object')
    expect(this.templates.Card).to.be.an('object')
    expect(this.templates.Person).to.be.an('object')
    expect(this.templates.Product).to.be.an('object')
    expect(this.templates.ProductBasic).to.be.an('object')
    expect(this.templates.ProductShirt).to.be.an('object')
    expect(this.templates.Program).to.be.an('object')
    expect(this.templates.User).to.be.an('object')
  })

  it('should have methods defined', function() {
    this.templateNames = Object.keys(this.templates)
    this.templateNames.forEach(templateName => {
      const methodName = `_template_${templateName}`

      describe(`Template ${templateName}`, function() {
        it(`should have a method for template ${templateName}`, function() {
          expect(Template).to.itself.respondTo(methodName)
        })

        it(`should respond to the method for template ${templateName}`, function() {
          return Template[methodName]
            .call()
            .then(result => {
              expect(result).to.be.an('object')
            })
        })

        it(`should override options in the template ${templateName}`, function() {
          return Template[methodName]
            .call(this, { programId: '123' })
            .then(result => {
              expect(result.programId).to.equal('123')
            })
        })

      })
    })
  })

})
<|endoftext|>


<commit_before>var expect = require('chai').expect
var path = require('path')
var gulp = require('gulp')
var addGrunt = require('../')

var ranbef = {
    x: false
}
var ran = {
    x: false
}

describe('gulp-grunt', function() {

    beforeEach(function() {
        gulp = require('gulp')
        gulp.env.silent = true
        ran = ranbef
        addGrunt(gulp, { base: path.join(__dirname, 'fixtures') })
    })

    it('should load grunt tasks', function() {
        expect(gulp.tasks).to.have.keys(['grunt-test', 'grunt-error'])
    })

    it('should still run gulp tasks', function() {
        gulp.task('x', function() {
            ran.x = true
        })
        gulp.run('x')
        expect(ran.x).to.be.true
    })

    var localGulp

    beforeEach(function() {
        localGulp = new gulp.Gulp
    })

    it('should work with another prefix', function() {
        addGrunt(localGulp, { base: path.join(__dirname, 'fixtures'), prefix: 'gr-' })
        expect(localGulp.tasks).to.have.keys(['gr-test', 'gr-error'])
    })

    it('should work with no prefix', function() {
        addGrunt(localGulp, { base: path.join(__dirname, 'fixtures'), prefix: '' })
        expect(localGulp.tasks).to.have.keys(['test', 'error'])
    })

    describe('should run grunt tasks', function() {

        var out
        var write = process.stdout.write

        beforeEach(function() {
            out = []
            process.stdout.write = function(data) {
                out.push(data)
            }
        })

        var finish = function() {
            process.stdout.write = write
        }

        it('should run grunt tasks', function() {
            gulp.run('grunt-test')
            finish()
            expect(out[1]).to.equal('test has been run\n')
        })

        it('should handle errors gracefully', function() {
            gulp.env.silent = false
            gulp.run('grunt-error')
            finish()
            expect(out[1]).to.have.string('Errored')
        })

    })

})
<commit_msg>make travis happy<commit_after>var expect = require('chai').expect
var path = require('path')
var gulp = require('gulp')
var addGrunt = require('../')

var ranbef = {
    x: false
}
var ran = {
    x: false
}

describe('gulp-grunt', function() {

    beforeEach(function() {
        gulp = require('gulp')
        gulp.env.silent = true
        ran = ranbef
        addGrunt(gulp, { base: path.join(__dirname, 'fixtures') })
    })

    it('should load grunt tasks', function() {
        expect(gulp.tasks).to.have.keys(['grunt-test', 'grunt-error'])
    })

    it('should still run gulp tasks', function() {
        gulp.task('x', function() {
            ran.x = true
        })
        gulp.run('x')
        expect(ran.x).to.be.true
    })

    var localGulp

    beforeEach(function() {
        localGulp = new gulp.Gulp
    })

    it('should work with another prefix', function() {
        addGrunt(localGulp, { base: path.join(__dirname, 'fixtures'), prefix: 'gr-' })
        expect(localGulp.tasks).to.have.keys(['gr-test', 'gr-error'])
    })

    it('should work with no prefix', function() {
        addGrunt(localGulp, { base: path.join(__dirname, 'fixtures'), prefix: '' })
        expect(localGulp.tasks).to.have.keys(['test', 'error'])
    })

    describe('should run grunt tasks', function() {

        var out
        var write = process.stdout.write

        beforeEach(function() {
            out = []
            process.stdout.write = function(data) {
                out.push(data)
            }
        })

        var finish = function() {
            process.stdout.write = write
        }

        it('should run grunt tasks', function() {
            gulp.run('grunt-test')
            finish()
            expect(out).to.include('test has been run\n')
        })

        it('should handle errors gracefully', function() {
            gulp.env.silent = false
            gulp.run('grunt-error')
            finish()
            expect(out[1]).to.have.string('Errored')
        })

    })

})
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var expect = require('chai').expect;
var assert = require('chai').assert;
var ssdm = require('../lib/ssdm.js');
require('shelljs/global');

describe ('#ssdm-basic', function () {

  it ('should display usage on no command', function () {
    var result = ssdm ();
    var help = fs
                .readFileSync(__dirname+'/../res/help.txt', 'utf-8')
                .replace(/\$0/g, 'ssdm')
                .trim();
    expect(result).to.equal(help);
  });

});

describe('#ssdm-util', function () {

  beforeEach(_setUpTestDir);

  it ('should list whitelisted files for list', function () {
    var cmdResponse = ssdm(['list']);
    var expected = '*\n!.gitignore';
    expect(cmdResponse).to.equal(expected);
  });

  it ('should pass through git commands within the context', function () {
    var cmdResponse = ssdm(['git', 'status']);
    var responsePattern = /^On branch master[\s\S]*$/;
    assert.match(cmdResponse, responsePattern);
  });

  afterEach(_tearDownTestDir);

});

describe('#ssdm-adding', function () {

  beforeEach(_setUpTestDir);

  it ('should add file pattern to whitelist', function () {
    var cmdResponse = ssdm (['addfile', '.bashrc']);
    var result = fs.readFileSync('.ssdmignore').toString();
    var expected = '*\n!.gitignore\n!.bashrc';
    expect(result).to.equal(expected);
  });

  it ('should add multiple file patterns to whitelist', function () {
    var cmdResponse = ssdm (['addfile', '.bashrc', '.vimrc', '.gitconfig']);
    var result = fs.readFileSync('.ssdmignore').toString();
    var expected = '*\n!.gitignore\n!.bashrc\n!.vimrc\n!.gitconfig';
    expect(result).to.equal(expected);
  });

  afterEach(_tearDownTestDir);

});

function _setUpTestDir() {
    mkdir('test-dir');
    cd('test-dir');
    if (exec('git init', {silent: true}).code !== 0) {
      echo('Error: \'git init\' failed');
      return 1;
    } else {
      mv('.git', '.ssdm');
    }
    '*\n!.gitignore'.to('.ssdmignore');
}

function _tearDownTestDir() {
    // make sure we are in test-dir before we start changing dirs
    var testDirPattern = /.*\/test-dir\/?$/;
    if (testDirPattern.test(process.cwd())) {
      cd('..');
    }
    rm('-rf', 'test-dir');
}
<commit_msg>account for prepended chars in Travis<commit_after>'use strict';

var fs = require('fs');
var expect = require('chai').expect;
var assert = require('chai').assert;
var ssdm = require('../lib/ssdm.js');
require('shelljs/global');

describe ('#ssdm-basic', function () {

  it ('should display usage on no command', function () {
    var result = ssdm ();
    var help = fs
                .readFileSync(__dirname+'/../res/help.txt', 'utf-8')
                .replace(/\$0/g, 'ssdm')
                .trim();
    expect(result).to.equal(help);
  });

});

describe('#ssdm-util', function () {

  beforeEach(_setUpTestDir);

  it ('should list whitelisted files for list', function () {
    var cmdResponse = ssdm(['list']);
    var expected = '*\n!.gitignore';
    expect(cmdResponse).to.equal(expected);
  });

  it ('should pass through git commands within the context', function () {
    var cmdResponse = ssdm(['git', 'status']);

    // need to start with wildcard to account for
    // some testrunners (e.g. the one used by Travis)
    // automatically prepending each line with format chars
    var responsePattern = /^.*On branch master[\s\S]*$/;

    assert.match(cmdResponse, responsePattern);
  });

  afterEach(_tearDownTestDir);

});

describe('#ssdm-adding', function () {

  beforeEach(_setUpTestDir);

  it ('should add file pattern to whitelist', function () {
    var cmdResponse = ssdm (['addfile', '.bashrc']);
    var result = fs.readFileSync('.ssdmignore').toString();
    var expected = '*\n!.gitignore\n!.bashrc';
    expect(result).to.equal(expected);
  });

  it ('should add multiple file patterns to whitelist', function () {
    var cmdResponse = ssdm (['addfile', '.bashrc', '.vimrc', '.gitconfig']);
    var result = fs.readFileSync('.ssdmignore').toString();
    var expected = '*\n!.gitignore\n!.bashrc\n!.vimrc\n!.gitconfig';
    expect(result).to.equal(expected);
  });

  afterEach(_tearDownTestDir);

});

function _setUpTestDir() {
    mkdir('test-dir');
    cd('test-dir');
    if (exec('git init', {silent: true}).code !== 0) {
      echo('Error: \'git init\' failed');
      return 1;
    } else {
      mv('.git', '.ssdm');
    }
    '*\n!.gitignore'.to('.ssdmignore');
}

function _tearDownTestDir() {
    // make sure we are in test-dir before we start changing dirs
    var testDirPattern = /.*\/test-dir\/?$/;
    if (testDirPattern.test(process.cwd())) {
      cd('..');
    }
    rm('-rf', 'test-dir');
}
<|endoftext|>


<commit_before>
'use strict'

require('leaked-handles')

const P = require('bluebird')
const test = require('ava')
const appStore = require('../index')
const DB = require('../lib/db')
const check = require('check-types')
const env = require('./helpers/env')

const opts = {
  appName: env.appName,
  dbUrl: env.dbUrl
}

const tearDown = (store, t) => {
  return store.destroy()
}

/**
 * Empty the database table of any lingering data
 * from previous tests
 *
 */
test.before(async t => {
  const db = await DB(opts)
  const knex = db[1].knex
  const table = db[2]
  await knex(table).del()
})

test('batch setting/getting', async t => {
  let store
  let itemMap

  const data = {
    foo: 'bar',
    bar: 'baz',
    bam: 12,
    arr: [ 1, 2, 3 ]
  }

  store = await appStore(opts)
  await store.setAll(data)
  itemMap = await store.getAll(Object.keys(data))

  t.truthy(itemMap.foo, 'foo prop is good.')
  t.is(itemMap.foo, data.foo, 'itemMap.foo matches data.foo.')

  t.truthy(itemMap.bar, 'bar prop is good')
  t.is(itemMap.bar, data.bar, 'itemMap.bar matches data.bar')

  t.truthy(itemMap.bam, 'bam prop is good')
  t.is(itemMap.bam, data.bam, 'itemMap.bar matches data.bar')

  itemMap.arr.forEach((el, index) => {
    t.truthy(
      el,
      data.arr[ index ],
      `itemMap.arr[${index}] matches data.arr[${index}]`
    )
  })
  // ensure data types are preserved
  t.is(typeof itemMap.bam, 'number', 'itemMap.bam is still a number')

  t.is(
    true, check.array(itemMap.arr), 'itemMap.arr is still an array'
  )
  await tearDown(store, t)
})

test('delete key', async (t) => {
  let item
  const store = await appStore(opts)

  await store.set('delMe', 'foo')
  item = await store.get('delMe')
  t.is(typeof item, 'string', 'string saved correctly')
  t.is(item, 'foo', 'Object key is as it should be')
  await store.del('delMe')
  item = await store.get('delMe')
  t.falsy(item, 'Deleted item has been deleted')
  await tearDown(store, t)
})

test('ttl functionality', async (t) => {
  let item
  const store = await appStore(opts)

  await store.set('beep', 'boop', 500)
  item = await store.get('beep')
  t.truthy(item, 'The item was successfully set')
  t.is(item, 'boop', `The item's value is as expected`)

  await (() => {
    return new P((resolve, reject) => {
      setTimeout(() => {
        store.get('beep')
          .then((fetched) => {
            t.falsy(fetched, 'The fetched item should be undefined by now')
            resolve()
          })
          .catch((err) => reject(err))
      }, 1000)
    })
  })()
  await tearDown(store, t)
})
<commit_msg>simple test case and test debug<commit_after>
'use strict'

require('leaked-handles')

const P = require('bluebird')
const test = require('ava')
const appStore = require('../index')
const DB = require('../lib/db')
const check = require('check-types')
const env = require('./helpers/env')

const opts = {
  appName: env.appName,
  dbUrl: env.dbUrl
}

const tearDown = (store, t) => {
  return store.destroy()
}

/**
 * Empty the database table of any lingering data
 * from previous tests
 *
 */
test.before(async t => {
  const db = await DB(opts)
  const knex = db[1].knex
  const table = db[2]
  console.log(`Cleaning '${table}' table...`)
  await knex(table).del()
})

test('simple set/get', async t => {
  let store
  let item
  store = await appStore(opts)
  item = await store.get('fooz')
  t.is(undefined, item)
  await store.set('fooz', 'booz')
  item = await store.get('fooz')
  t.is(item, 'booz')
})

test('batch setting/getting', async t => {
  let store
  let itemMap

  const data = {
    foo: 'bar',
    bar: 'baz',
    bam: 12,
    arr: [ 1, 2, 3 ]
  }

  store = await appStore(opts)
  await store.setAll(data)
  itemMap = await store.getAll(Object.keys(data))

  t.truthy(itemMap.foo, 'foo prop is good.')
  t.is(itemMap.foo, data.foo, 'itemMap.foo matches data.foo.')

  t.truthy(itemMap.bar, 'bar prop is good')
  t.is(itemMap.bar, data.bar, 'itemMap.bar matches data.bar')

  t.truthy(itemMap.bam, 'bam prop is good')
  t.is(itemMap.bam, data.bam, 'itemMap.bar matches data.bar')

  itemMap.arr.forEach((el, index) => {
    t.truthy(
      el,
      data.arr[ index ],
      `itemMap.arr[${index}] matches data.arr[${index}]`
    )
  })
  // ensure data types are preserved
  t.is(typeof itemMap.bam, 'number', 'itemMap.bam is still a number')

  t.is(
    true, check.array(itemMap.arr), 'itemMap.arr is still an array'
  )
  await tearDown(store, t)
})

test('delete key', async (t) => {
  let item
  const store = await appStore(opts)

  await store.set('delMe', 'foo')
  item = await store.get('delMe')
  t.is(typeof item, 'string', 'string saved correctly')
  t.is(item, 'foo', 'Object key is as it should be')
  await store.del('delMe')
  item = await store.get('delMe')
  t.falsy(item, 'Deleted item has been deleted')
  await tearDown(store, t)
})

test('ttl functionality', async (t) => {
  let item
  const store = await appStore(opts)

  await store.set('beep', 'boop', 500)
  item = await store.get('beep')
  t.truthy(item, 'The item was successfully set')
  t.is(item, 'boop', `The item's value is as expected`)

  await (() => {
    return new P((resolve, reject) => {
      setTimeout(() => {
        store.get('beep')
          .then((fetched) => {
            t.falsy(fetched, 'The fetched item should be undefined by now')
            resolve()
          })
          .catch((err) => reject(err))
      }, 1000)
    })
  })()
  await tearDown(store, t)
})
<|endoftext|>


<commit_before>'use strict'
const assert = require('assert')
const path = require('path')
const expect = require('chai').expect
const crypto = require('../src/crypto.js')
const util = require('../src/util')
const Db = require('../src/Db')
const MasterPassKey = require('../src/_MasterPassKey')
const MasterPass = require('../src/MasterPass')
// const logger = require('../script/logger')
const scrypto = require('crypto')
const _ = require('lodash')
const fs = require('fs-extra')
const exec = require('child_process').exec

console.log(`cwd: ${process.cwd()}`)
console.log(`__dirname: ${__dirname}`)

describe("Crypter Core Modules' tests", function () {
  global.paths = {
    mdb: path.join(__dirname, '/tmp/mdb'),
    tmp: path.join(__dirname, '/tmp')
  }
  console.log(require('util').inspect(global.paths, {
    depth: null
  }))

  global.defaults = {
    iterations: 4096, // file encryption key iterations
    keyLength: 32, // in bytes
    ivLength: 12,
    algorithm: 'aes-256-gcm',
    salgorithm: 'aes-256-ctr',
    digest: 'sha256',
    hash_alg: 'sha256',
    check_hash_alg: 'md5',
    padLength: 1024,
    mpk_iterations: 100000, // masterpass key iterations
    shares: 3,
    threshold: 2
  }

  global.vault = {
    'RAND0M-ID3': {
      name: 'crypto',
      id: 22,
      secure: true
    },
    'R3C0M-I4D': {
      name: 'cry9to',
      id: 2090,
      secure: false
    }
  }

  global.creds = {}

  // Declare globals
  fs.ensureDirSync(global.paths.tmp)
  global.MasterPassKey = new MasterPassKey(scrypto.randomBytes(global.defaults.keyLength))
  global.mdb = new Db(global.paths.mdb)

  const t1path = `${global.paths.tmp}/test.txt`

  // After all tests have run
  after(function () {
    fs.removeSync(global.paths.tmp)
  })

  /** Crypto module.js
   ******************************/

  describe('Crypto module', function () {
    before(function () {
      fs.writeFileSync(t1path, '#Crypter', 'utf8')
    })

    describe('deriveKey & genPassHash', function () {
      const masterpass = 'crypto#101'
      it('should deriveKey using a MasterPass correctly when salt is buffer', function () {
        let mpkey
        return crypto.deriveKey(masterpass, null)
          .then((dmp) => {
            mpkey = dmp.key
            return crypto.deriveKey(masterpass, dmp.salt)
          })
          .then((dmp) => {
            expect(dmp.key.toString('hex')).to.equal(mpkey.toString('hex'))
          })
      })

      it('should deriveKey using a MasterPass correctly with persistent salt', function () {
        let mpkey
        return crypto.deriveKey(masterpass, null)
          .then((dmp) => {
            const pdmpsalt = JSON.parse(JSON.stringify(dmp.salt))
            mpkey = dmp.key
            return crypto.deriveKey(masterpass, pdmpsalt)
          })
          .then((dmp) => {
            expect(dmp.key.toString('hex')).to.equal(mpkey.toString('hex'))
          })
      })
    })

    describe('Encryption', function () {
      before(function () {
        fs.writeFileSync(t1path, '#Crypter', 'utf8')
      })
      describe('crypt promise', function () {
        it('should encrypt file with pass without errors & have all expected creds', function () {
          return crypto.crypt(t1path, global.MasterPassKey.get())
            .then((file) => {
              expect(file).not.be.empty
              expect(file.path).to.equal(t1path)
              expect(file.cryptPath).to.equal(`${t1path}.crypto`)
              expect(file.iv).not.be.empty
              expect(file.salt).not.be.empty
              expect(file.key).not.be.empty
              expect(file.iv).not.be.empty
              expect(file.authTag).not.be.empty
            })
        })
        it('throw error when pass not supplied', function () {
          return crypto.crypt(t1path)
            .catch((err) => {
              expect(err).to.be.an('error')
              expect(err.message).to.equal('Pass to derive key from not provided')
            })
        })
        it('throw error when empty destination path to encrypt is passed', function () {
          return crypto.crypt('', global.MasterPassKey.get())
            .catch((err) => {
              expect(err).to.be.an('error')
              expect(err.message).to.equal("ENOENT: no such file or directory, open ''")
            })
        })
      })
      describe('encrypt promise', function () {
        it('throw origin error when empty filepath to encrypt is passed', function () {
          return crypto.encrypt('', '', global.MasterPassKey.get())
            .catch((err) => {
              expect(err).to.be.an('error')
              expect(err.message).to.equal("ENOENT: no such file or directory, open ''")
            })
        })
        it('throw dest error when empty destination path to encrypt is passed', function () {
          return crypto.encrypt(t1path, '', global.MasterPassKey.get())
            .catch((err) => {
              expect(err).to.be.an('error')
              expect(err.message).to.equal("ENOENT: no such file or directory, open ''")
            })
        })
      })
    })
  })
  /**
   * Util module.js
   ******************************/
  describe('Util module', function () {
    const t1path = `${global.paths.tmp}/atest.txt`
    const t1data = '#Crypter'
    before(function () {
      fs.writeFileSync(t1path, t1data, 'utf8')
    })

    describe('checkFileSync and checkDirectorySync', function () {
      it('should check if file exists', function (done) {
        expect(util.checkDirectorySync('./'))
          .to.be.true
        expect(util.checkFileSync('any.file'))
          .to.be.false
        expect(util.checkFileSync('anydir/file'))
          .to.be.false
        expect(util.checkFileSync('anydir'))
          .to.be.false
        done()
      })
    })
  })

  /**
   * MasterPass & MasterPassKey module.js
   ******************************/
  describe('MasterPass module', function () {
    it('should set and check masterpass', function () {
      const pass = 'V1R3$1NNUM3RI$'
      var mpkey
      return MasterPass.set(pass)
        .then((mpk) => {
          mpkey = mpk
          return MasterPass.check(pass)
        })
        .then((result) => {
          expect(result.match)
            .to.be.true
          expect(result.key.toString('hex'))
            .to.equal(mpkey.toString('hex'))
        })
    })

    it('should throw error if not provided when checking', function () {
      const pass = ''
      return MasterPass.check(pass)
        .catch((err) => {
          expect(err).to.be.an('error')
          expect(err.message).to.equal('Pass to derive key from not provided')
        })
    })

    it('should throw error if not provided when setting', function () {
      const pass = ''
      return MasterPass.set(pass)
        .catch((err) => {
          expect(err).to.be.an('error')
          expect(err.message).to.equal('Pass to derive key from not provided')
        })
    })
  })

  describe('MasterPassKey module', function () {
    it('should set and get same masterpasskey', function () {
      const mpkey = scrypto.randomBytes(global.defaults.keyLength)
      const newMPK = scrypto.randomBytes(global.defaults.keyLength)
      const MPK = new MasterPassKey(mpkey)
      expect(MPK.get()).to.deep.equal(mpkey)
      expect(MPK.get() instanceof Buffer).to.be.true
      MPK.set(newMPK)
      expect(MPK.get()).to.deep.equal(newMPK)
    })
    it('should throw error when deleted and get called', function () {
      const mpkey = scrypto.randomBytes(global.defaults.keyLength)
      const MPK = new MasterPassKey(mpkey)
      MPK.delete()
      expect(MPK.get()).to.be.an('error')
      expect(MPK.get().message).to.equal('MasterPassKey is not set')
    })
    it('should throw error when not instantiated with key', function () {
      const MPK = new MasterPassKey()
      expect(MPK.get()).to.be.an('error')
      expect(MPK.get().message).to.equal('MasterPassKey is not set')
    })
    it('should throw error when instantiated with data type other than a Buffer', function () {
      const MPK = new MasterPassKey()
      expect(MPK.set('pass')).to.be.an('error')
      expect(MPK.set().message).to.equal('MasterPassKey not a Buffer')
    })
  })

  /**
   * Db module.js
   ******************************/
  describe('Db module', function () {
    let db
    let putValue = function (key, value) {
      return new Promise(function (resolve, reject) {
        db.put(key, value, function (err) {
          if (err) reject(err) // db save error
          resolve()
        })
      })
    }
    let close = function (key, value) {
      return new Promise(function (resolve, reject) {
        db.put(key, value, function (err) {
          if (err) reject(err) // db save error
          resolve()
        })
      })
    }
    beforeEach(function () {
      return new Promise(function(resolve, reject) {
        db = new Db(`${global.paths.tmp}/db`)
        global.testo = {
          'RAND0M-ID3': {
            name: 'crypto',
            id: 22,
            secure: true
          }
        }
        resolve()
      })
    })
    afterEach(function () {
      return new Promise(function(resolve, reject) {
        db.close()
        resolve()
      })
    })
    it('should save and restore obj', function () {
      const beforeSaveObj = _.cloneDeep(global.testo)
      return db.saveGlobalObj('testo')
        .then(() => {
          global.testo = null
          return db.restoreGlobalObj('testo')
        })
        .then(() => {
          expect(global.testo).to.deep.equal(beforeSaveObj)
          return
        })
        .catch((err) => {
          throw (err)
        })
    })

    it('should save and restore obj persistently', function () {
      const beforeSaveObj = _.cloneDeep(global.testo)
      return db.saveGlobalObj('testo')
        .then(() => {
          global.testo = null
          db.close()
          db = new Db(`${global.paths.tmp}/db`)
          return db.restoreGlobalObj('testo')
        })
        .then(() => {
          expect(global.testo)
            .to.deep.equal(beforeSaveObj)
          return
        })
        .catch((err) => {
          throw (err)
        })
    })

    describe('onlyGetValue', () => {
      it('should resolve value if key exists', function () {
        return putValue('key', 'value')
          .then(() => {
            return db.onlyGetValue('key')
          }).then((value) => {
          expect(value).to.equal('value')
        })
          .catch((err) => {
            throw err
          })
      })
      it('should resolve null if key not found', function () {
        return db.onlyGetValue('notExist')
          .then((value) => {
            expect(value).to.equal(false)
          })
      })
      it('should resolve null if key not found', function () {
        return db.onlyGetValue('')
          .catch((err) => {
            // expect(err instanceof ReadError).to.be.true
            expect(err.message).to.equal('key cannot be an empty String')
          })
      })
    })

    describe('restoreGlobalObj', () => {
      it('should not save global object if empty', function () {
        global.b = {}
        return db.saveGlobalObj('b')
          .then(() => {
          })
          .catch((err) => {
            throw err
          })
      })
      it('should throw error when global obj to save is undefined', function () {
        global.g = {}
        global.g.a = {
          b: global.g
        }
        return db.saveGlobalObj('g')
          .then(() => {
            db.close()
          })
          .catch((err) => {
            db.close()
            expect(err).to.be.an('error')
            expect(err.message).to.equal('Converting circular structure to JSON')
          })
      })
    })

    describe('saveGlobalObj', () => {
      it('should throw error when global object not exist', function () {
        return db.restoreGlobalObj('fake')
          .catch((err) => {
            expect(err.notFound).to.be.true
            expect(err.status).to.equal(404)
          })
      })

      it('should throw error when JSON fails to parse', function () {
        return putValue('s', 'i')
          .then(() => {
            return db.restoreGlobalObj('s')
          })
          .catch((err) => {
            expect(err).to.be.an('error')
            expect(err.message).to.equal('Unexpected token i')
          })
      })
    })
  })
})
<commit_msg>try another fix<commit_after>'use strict'
const assert = require('assert')
const path = require('path')
const expect = require('chai').expect
const crypto = require('../src/crypto.js')
const util = require('../src/util')
const Db = require('../src/Db')
const MasterPassKey = require('../src/_MasterPassKey')
const MasterPass = require('../src/MasterPass')
// const logger = require('../script/logger')
const scrypto = require('crypto')
const _ = require('lodash')
const fs = require('fs-extra')
const exec = require('child_process').exec

console.log(`cwd: ${process.cwd()}`)
console.log(`__dirname: ${__dirname}`)

describe("Crypter Core Modules' tests", function () {
  global.paths = {
    mdb: path.join(__dirname, '/tmp/mdb'),
    tmp: path.join(__dirname, '/tmp')
  }
  console.log(require('util').inspect(global.paths, {
    depth: null
  }))

  global.defaults = {
    iterations: 4096, // file encryption key iterations
    keyLength: 32, // in bytes
    ivLength: 12,
    algorithm: 'aes-256-gcm',
    salgorithm: 'aes-256-ctr',
    digest: 'sha256',
    hash_alg: 'sha256',
    check_hash_alg: 'md5',
    padLength: 1024,
    mpk_iterations: 100000, // masterpass key iterations
    shares: 3,
    threshold: 2
  }

  global.vault = {
    'RAND0M-ID3': {
      name: 'crypto',
      id: 22,
      secure: true
    },
    'R3C0M-I4D': {
      name: 'cry9to',
      id: 2090,
      secure: false
    }
  }

  global.creds = {}

  // Declare globals
  fs.ensureDirSync(global.paths.tmp)
  global.MasterPassKey = new MasterPassKey(scrypto.randomBytes(global.defaults.keyLength))
  global.mdb = new Db(global.paths.mdb)

  const t1path = `${global.paths.tmp}/test.txt`

  // After all tests have run
  after(function () {
    fs.removeSync(global.paths.tmp)
  })

  /** Crypto module.js
   ******************************/

  describe('Crypto module', function () {
    before(function () {
      fs.writeFileSync(t1path, '#Crypter', 'utf8')
    })

    describe('deriveKey & genPassHash', function () {
      const masterpass = 'crypto#101'
      it('should deriveKey using a MasterPass correctly when salt is buffer', function () {
        let mpkey
        return crypto.deriveKey(masterpass, null)
          .then((dmp) => {
            mpkey = dmp.key
            return crypto.deriveKey(masterpass, dmp.salt)
          })
          .then((dmp) => {
            expect(dmp.key.toString('hex')).to.equal(mpkey.toString('hex'))
          })
      })

      it('should deriveKey using a MasterPass correctly with persistent salt', function () {
        let mpkey
        return crypto.deriveKey(masterpass, null)
          .then((dmp) => {
            const pdmpsalt = JSON.parse(JSON.stringify(dmp.salt))
            mpkey = dmp.key
            return crypto.deriveKey(masterpass, pdmpsalt)
          })
          .then((dmp) => {
            expect(dmp.key.toString('hex')).to.equal(mpkey.toString('hex'))
          })
      })
    })

    describe('Encryption', function () {
      before(function () {
        fs.writeFileSync(t1path, '#Crypter', 'utf8')
      })
      describe('crypt promise', function () {
        it('should encrypt file with pass without errors & have all expected creds', function () {
          return crypto.crypt(t1path, global.MasterPassKey.get())
            .then((file) => {
              expect(file).not.be.empty
              expect(file.path).to.equal(t1path)
              expect(file.cryptPath).to.equal(`${t1path}.crypto`)
              expect(file.iv).not.be.empty
              expect(file.salt).not.be.empty
              expect(file.key).not.be.empty
              expect(file.iv).not.be.empty
              expect(file.authTag).not.be.empty
            })
        })
        it('throw error when pass not supplied', function () {
          return crypto.crypt(t1path)
            .catch((err) => {
              expect(err).to.be.an('error')
              expect(err.message).to.equal('Pass to derive key from not provided')
            })
        })
        it('throw error when empty destination path to encrypt is passed', function () {
          return crypto.crypt('', global.MasterPassKey.get())
            .catch((err) => {
              expect(err).to.be.an('error')
              expect(err.message).to.equal("ENOENT: no such file or directory, open ''")
            })
        })
      })
      describe('encrypt promise', function () {
        it('throw origin error when empty filepath to encrypt is passed', function () {
          return crypto.encrypt('', '', global.MasterPassKey.get())
            .catch((err) => {
              expect(err).to.be.an('error')
              expect(err.message).to.equal("ENOENT: no such file or directory, open ''")
            })
        })
        it('throw dest error when empty destination path to encrypt is passed', function () {
          return crypto.encrypt(t1path, '', global.MasterPassKey.get())
            .catch((err) => {
              expect(err).to.be.an('error')
              expect(err.message).to.equal("ENOENT: no such file or directory, open ''")
            })
        })
      })
    })
  })
  /**
   * Util module.js
   ******************************/
  describe('Util module', function () {
    const t1path = `${global.paths.tmp}/atest.txt`
    const t1data = '#Crypter'
    before(function () {
      fs.writeFileSync(t1path, t1data, 'utf8')
    })

    describe('checkFileSync and checkDirectorySync', function () {
      it('should check if file exists', function (done) {
        expect(util.checkDirectorySync('./'))
          .to.be.true
        expect(util.checkFileSync('any.file'))
          .to.be.false
        expect(util.checkFileSync('anydir/file'))
          .to.be.false
        expect(util.checkFileSync('anydir'))
          .to.be.false
        done()
      })
    })
  })

  /**
   * MasterPass & MasterPassKey module.js
   ******************************/
  describe('MasterPass module', function () {
    after(function () {
      global.mdb.close()
    })
    it('should set and check masterpass', function () {
      const pass = 'V1R3$1NNUM3RI$'
      var mpkey
      return MasterPass.set(pass)
        .then((mpk) => {
          mpkey = mpk
          return MasterPass.check(pass)
        })
        .then((result) => {
          expect(result.match)
            .to.be.true
          expect(result.key.toString('hex'))
            .to.equal(mpkey.toString('hex'))
        })
    })

    it('should throw error if not provided when checking', function () {
      const pass = ''
      return MasterPass.check(pass)
        .catch((err) => {
          expect(err).to.be.an('error')
          expect(err.message).to.equal('Pass to derive key from not provided')
        })
    })

    it('should throw error if not provided when setting', function () {
      const pass = ''
      return MasterPass.set(pass)
        .catch((err) => {
          expect(err).to.be.an('error')
          expect(err.message).to.equal('Pass to derive key from not provided')
        })
    })
  })

  describe('MasterPassKey module', function () {
    it('should set and get same masterpasskey', function () {
      const mpkey = scrypto.randomBytes(global.defaults.keyLength)
      const newMPK = scrypto.randomBytes(global.defaults.keyLength)
      const MPK = new MasterPassKey(mpkey)
      expect(MPK.get()).to.deep.equal(mpkey)
      expect(MPK.get() instanceof Buffer).to.be.true
      MPK.set(newMPK)
      expect(MPK.get()).to.deep.equal(newMPK)
    })
    it('should throw error when deleted and get called', function () {
      const mpkey = scrypto.randomBytes(global.defaults.keyLength)
      const MPK = new MasterPassKey(mpkey)
      MPK.delete()
      expect(MPK.get()).to.be.an('error')
      expect(MPK.get().message).to.equal('MasterPassKey is not set')
    })
    it('should throw error when not instantiated with key', function () {
      const MPK = new MasterPassKey()
      expect(MPK.get()).to.be.an('error')
      expect(MPK.get().message).to.equal('MasterPassKey is not set')
    })
    it('should throw error when instantiated with data type other than a Buffer', function () {
      const MPK = new MasterPassKey()
      expect(MPK.set('pass')).to.be.an('error')
      expect(MPK.set().message).to.equal('MasterPassKey not a Buffer')
    })
  })

  /**
   * Db module.js
   ******************************/
  describe('Db module', function () {
    let db
    let putValue = function (key, value) {
      return new Promise(function (resolve, reject) {
        db.put(key, value, function (err) {
          if (err) reject(err) // db save error
          resolve()
        })
      })
    }
    let close = function (key, value) {
      return new Promise(function (resolve, reject) {
        db.put(key, value, function (err) {
          if (err) reject(err) // db save error
          resolve()
        })
      })
    }
    before(() => {
      global.testo = {
        'RAND0M-ID3': {
          name: 'crypto',
          id: 22,
          secure: true
        }
      }
      db = new Db(`${global.paths.tmp}/db`)
    })

    after(function () {
      db.close()
    })
    it('should save and restore obj', function () {
      const beforeSaveObj = _.cloneDeep(global.testo)
      return db.saveGlobalObj('testo')
        .then(() => {
          global.testo = null
          return db.restoreGlobalObj('testo')
        })
        .then(() => {
          expect(global.testo).to.deep.equal(beforeSaveObj)
          return
        })
        .catch((err) => {
          throw (err)
        })
    })

    it('should save and restore obj persistently', function () {
      const beforeSaveObj = _.cloneDeep(global.testo)
      return db.saveGlobalObj('testo')
        .then(() => {
          global.testo = null
          db.close()
          db = new Db(`${global.paths.tmp}/db`)
          return db.restoreGlobalObj('testo')
        })
        .then(() => {
          expect(global.testo)
            .to.deep.equal(beforeSaveObj)
          return
        })
        .catch((err) => {
          throw (err)
        })
    })

    describe('onlyGetValue', () => {
      it('should resolve value if key exists', function () {
        return putValue('key', 'value')
          .then(() => {
            return db.onlyGetValue('key')
          }).then((value) => {
          expect(value).to.equal('value')
        })
          .catch((err) => {
            throw err
          })
      })
      it('should resolve null if key not found', function () {
        return db.onlyGetValue('notExist')
          .then((value) => {
            expect(value).to.equal(false)
          })
      })
      it('should resolve null if key not found', function () {
        return db.onlyGetValue('')
          .catch((err) => {
            // expect(err instanceof ReadError).to.be.true
            expect(err.message).to.equal('key cannot be an empty String')
          })
      })
    })

    describe('restoreGlobalObj', () => {
      it('should not save global object if empty', function () {
        global.b = {}
        return db.saveGlobalObj('b')
          .then(() => {
          })
          .catch((err) => {
            throw err
          })
      })
      it('should throw error when global obj to save is undefined', function () {
        global.g = {}
        global.g.a = {
          b: global.g
        }
        return db.saveGlobalObj('g')
          .catch((err) => {
            expect(err).to.be.an('error')
            expect(err.message).to.equal('Converting circular structure to JSON')
          })
      })
    })

    describe('saveGlobalObj', () => {
      it('should throw error when global object not exist', function () {
        return db.restoreGlobalObj('fake')
          .catch((err) => {
            expect(err.notFound).to.be.true
            expect(err.status).to.equal(404)
          })
      })

      it('should throw error when JSON fails to parse', function () {
        return putValue('s', 'i')
          .then(() => {
            return db.restoreGlobalObj('s')
          })
          .catch((err) => {
            expect(err).to.be.an('error')
            expect(err.message).to.equal('Unexpected token i')
          })
      })
    })
  })
})
<|endoftext|>


<commit_before>var Pheasant = require( __dirname + '/../src/pheasant' ).Pheasant,
    chai     = require( 'chai' ),

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

describe( 'Settings', function() {

    describe( 'Pheasant.setDefaultStringFormat', function() {

        it( 'should change the default formatting', function() {

            expect( Pheasant.parse( '#000' ).toString( 'hex3' ) ).to.equal( '#000' );
            Pheasant.setDefaultStringFormat( 'hex6' );
            expect( Pheasant.parse( '#000' ).toString() ).to.equal( '#000000' );
            expect( Pheasant.parse( '#000' ).toString( 'hex3' ) ).to.equal( '#000' );

        });

    });

});

describe( 'Parsing', function() {

    beforeEach(function() {

        Pheasant.setDefaultStringFormat( 'hex3' );

    });

    describe( 'of CSS/SVG color names', function() {

        it( 'should normalize strings with spaces before', function() {

            expect( Pheasant.parse( '  black' ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( '   lime' ).toString() ).to.equal( '#0f0' );

        });

        it( 'should normalize strings with spaces after', function() {

            expect( Pheasant.parse( 'black   ' ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( 'lime    ' ).toString() ).to.equal( '#0f0' );

        });

        it( 'should normalize strings with spaces both before and after', function() {

            expect( Pheasant.parse( ' black   ' ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( '  lime   ' ).toString() ).to.equal( '#0f0' );

        });

        it( 'should normalize mixed-case strings', function() {

            expect( Pheasant.parse( 'bLaCk' ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( 'liME' ).toString() ).to.equal( '#0f0' );

        });

        it( 'should handle CSS color names', function() {

            expect( Pheasant.parse( 'black'   ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( 'lime'    ).toString() ).to.equal( '#0f0' );
            expect( Pheasant.parse( 'red'     ).toString() ).to.equal( '#f00' );
            expect( Pheasant.parse( 'blue'    ).toString() ).to.equal( '#00f' );
            expect( Pheasant.parse( 'white'   ).toString() ).to.equal( '#fff' );
            expect( Pheasant.parse( 'fuchsia' ).toString() ).to.equal( '#f0f' );

        });

    });

    describe( 'of hexadecimal strings of length 3', function() {

        it( 'should normalize strings with spaces before', function() {

            expect( Pheasant.parse( '  #abc' ).toString() ).to.equal( '#abc' );

        });

        it( 'should normalize strings with spaces after', function() {

            expect( Pheasant.parse( '#acc   ' ).toString() ).to.equal( '#acc' );

        });

        it( 'should normalize strings with spaces both before and after', function() {

            expect( Pheasant.parse( '  #0ce   ' ).toString() ).to.equal( '#0ce' );
            expect( Pheasant.parse( ' #110    ' ).toString() ).to.equal( '#110' );

        });

        it( 'should normalize mixed-case strings', function() {

            expect( Pheasant.parse( '#AAA' ).toString() ).to.equal( '#aaa' );
            expect( Pheasant.parse( '#0Ed' ).toString() ).to.equal( '#0ed' );

        });

        it( 'should handle hex3 values', function() {

            expect( Pheasant.parse( '#aaa' ).toString() ).to.equal( '#aaa' );
            expect( Pheasant.parse( '#fff' ).toString() ).to.equal( '#fff' );
            expect( Pheasant.parse( '#012' ).toString() ).to.equal( '#012' );

        });

    });

    describe( 'of hexadecimal strings of length 6', function() {

        it( 'should normalize strings with spaces before', function() {

            expect( Pheasant.parse( '  #abcdef' ).toString() ).to.equal( '#ace' );

        });

        it( 'should normalize strings with spaces after', function() {

            expect( Pheasant.parse( '#ab0def   ' ).toString() ).to.equal( '#a0e' );

        });

        it( 'should normalize strings with spaces both before and after', function() {

            expect( Pheasant.parse( '  #a0a0fe   ' ).toString() ).to.equal( '#aaf' );
            expect( Pheasant.parse( ' #110ccc    ' ).toString() ).to.equal( '#10c' );

        });

        it( 'should normalize mixed-case strings', function() {

            expect( Pheasant.parse( '#BAAb23' ).toString() ).to.equal( '#ba2' );
            expect( Pheasant.parse( '#0EdCdD' ).toString() ).to.equal( '#0dd' );

        });

        it( 'should handle hex6 values', function() {

            expect( Pheasant.parse( '#abcdef' ).toString() ).to.equal( '#ace' );
            expect( Pheasant.parse( '#123456' ).toString() ).to.equal( '#135' );
            expect( Pheasant.parse( '#424242' ).toString() ).to.equal( '#444' );

        });

    });

});

describe( 'Stringifying', function() {

    describe( 'to Hex3 format (#xyz)', function() {

        beforeEach(function() {

            Pheasant.setDefaultStringFormat( 'hex3' );

        });

        it( 'should normalize colors with values higher than 255', function() {

            expect( new Pheasant.Color( 256, 2, 1 ).toString() ).to.equal( '#f00' );
            expect( new Pheasant.Color( Infinity, 2, 4242 ).toString() ).to.equal( '#f0f' );

        });

        it( 'should normalize colors with negative values', function() {

            expect( new Pheasant.Color( -1, 42, 1 ).toString() ).to.equal( '#020' );
            expect( new Pheasant.Color( -Infinity, 2, -4242 ).toString() ).to.equal( '#000' );

        });

        it( 'should normalize colors with float values', function() {

            expect( new Pheasant.Color( 0, 15.99, 1.42 ).toString() ).to.equal( '#010' );

        });

        it( 'should normalize colors with negative float values', function() {

            expect( new Pheasant.Color( 0, -15.99, -1.42 ).toString() ).to.equal( '#000' );

        });

        it( 'should not handle colors with NaN values', function() {

            expect( new Pheasant.Color( 0, NaN, 0 ).toString() ).to.be.null;

        });

    });

    describe( 'to Hex6 format (#abcdef)', function() {

        beforeEach(function() {

            Pheasant.setDefaultStringFormat( 'hex6' );

        });

        it( 'should normalize colors with values higher than 255', function() {

            expect( new Pheasant.Color( 256, 2, 1 ).toString() ).to.equal( '#ff0201' );
            expect( new Pheasant.Color( Infinity, 2, 4242 ).toString() ).to.equal( '#ff02ff' );

        });

        it( 'should normalize colors with negative values', function() {

            expect( new Pheasant.Color( -1, 42, 1 ).toString() ).to.equal( '#002a01' );
            expect( new Pheasant.Color( -Infinity, 2, -4242 ).toString() ).to.equal( '#000200' );

        });

        it( 'should normalize colors with float values', function() {

            expect( new Pheasant.Color( 0, 15.99, 1.42 ).toString() ).to.equal( '#001001' );

        });

        it( 'should normalize colors with negative float values', function() {

            expect( new Pheasant.Color( 0, -15.99, -1.42 ).toString() ).to.equal( '#000000' );

        });

        it( 'should not handle colors with NaN values', function() {

            expect( new Pheasant.Color( 0, NaN, 0 ).toString() ).to.be.null;

        });

    });

});
<commit_msg>stringifying to color names tests.<commit_after>var Pheasant = require( __dirname + '/../src/pheasant' ).Pheasant,
    chai     = require( 'chai' ),

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

describe( 'Settings', function() {

    describe( 'Pheasant.setDefaultStringFormat', function() {

        it( 'should change the default formatting', function() {

            expect( Pheasant.parse( '#000' ).toString( 'hex3' ) ).to.equal( '#000' );
            Pheasant.setDefaultStringFormat( 'hex6' );
            expect( Pheasant.parse( '#000' ).toString() ).to.equal( '#000000' );
            expect( Pheasant.parse( '#000' ).toString( 'hex3' ) ).to.equal( '#000' );

        });

    });

});

describe( 'Parsing', function() {

    beforeEach(function() {

        Pheasant.setDefaultStringFormat( 'hex3' );

    });

    describe( 'of CSS/SVG color names', function() {

        it( 'should normalize strings with spaces before', function() {

            expect( Pheasant.parse( '  black' ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( '   lime' ).toString() ).to.equal( '#0f0' );

        });

        it( 'should normalize strings with spaces after', function() {

            expect( Pheasant.parse( 'black   ' ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( 'lime    ' ).toString() ).to.equal( '#0f0' );

        });

        it( 'should normalize strings with spaces both before and after', function() {

            expect( Pheasant.parse( ' black   ' ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( '  lime   ' ).toString() ).to.equal( '#0f0' );

        });

        it( 'should normalize mixed-case strings', function() {

            expect( Pheasant.parse( 'bLaCk' ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( 'liME' ).toString() ).to.equal( '#0f0' );

        });

        it( 'should handle CSS color names', function() {

            expect( Pheasant.parse( 'black'   ).toString() ).to.equal( '#000' );
            expect( Pheasant.parse( 'lime'    ).toString() ).to.equal( '#0f0' );
            expect( Pheasant.parse( 'red'     ).toString() ).to.equal( '#f00' );
            expect( Pheasant.parse( 'blue'    ).toString() ).to.equal( '#00f' );
            expect( Pheasant.parse( 'white'   ).toString() ).to.equal( '#fff' );
            expect( Pheasant.parse( 'fuchsia' ).toString() ).to.equal( '#f0f' );

        });

    });

    describe( 'of hexadecimal strings of length 3', function() {

        it( 'should normalize strings with spaces before', function() {

            expect( Pheasant.parse( '  #abc' ).toString() ).to.equal( '#abc' );

        });

        it( 'should normalize strings with spaces after', function() {

            expect( Pheasant.parse( '#acc   ' ).toString() ).to.equal( '#acc' );

        });

        it( 'should normalize strings with spaces both before and after', function() {

            expect( Pheasant.parse( '  #0ce   ' ).toString() ).to.equal( '#0ce' );
            expect( Pheasant.parse( ' #110    ' ).toString() ).to.equal( '#110' );

        });

        it( 'should normalize mixed-case strings', function() {

            expect( Pheasant.parse( '#AAA' ).toString() ).to.equal( '#aaa' );
            expect( Pheasant.parse( '#0Ed' ).toString() ).to.equal( '#0ed' );

        });

        it( 'should handle hex3 values', function() {

            expect( Pheasant.parse( '#aaa' ).toString() ).to.equal( '#aaa' );
            expect( Pheasant.parse( '#fff' ).toString() ).to.equal( '#fff' );
            expect( Pheasant.parse( '#012' ).toString() ).to.equal( '#012' );

        });

    });

    describe( 'of hexadecimal strings of length 6', function() {

        it( 'should normalize strings with spaces before', function() {

            expect( Pheasant.parse( '  #abcdef' ).toString() ).to.equal( '#ace' );

        });

        it( 'should normalize strings with spaces after', function() {

            expect( Pheasant.parse( '#ab0def   ' ).toString() ).to.equal( '#a0e' );

        });

        it( 'should normalize strings with spaces both before and after', function() {

            expect( Pheasant.parse( '  #a0a0fe   ' ).toString() ).to.equal( '#aaf' );
            expect( Pheasant.parse( ' #110ccc    ' ).toString() ).to.equal( '#10c' );

        });

        it( 'should normalize mixed-case strings', function() {

            expect( Pheasant.parse( '#BAAb23' ).toString() ).to.equal( '#ba2' );
            expect( Pheasant.parse( '#0EdCdD' ).toString() ).to.equal( '#0dd' );

        });

        it( 'should handle hex6 values', function() {

            expect( Pheasant.parse( '#abcdef' ).toString() ).to.equal( '#ace' );
            expect( Pheasant.parse( '#123456' ).toString() ).to.equal( '#135' );
            expect( Pheasant.parse( '#424242' ).toString() ).to.equal( '#444' );

        });

    });

});

describe( 'Stringifying', function() {

    describe( 'to Hex3 format (#xyz)', function() {

        beforeEach(function() {

            Pheasant.setDefaultStringFormat( 'hex3' );

        });

        it( 'should normalize colors with values higher than 255', function() {

            expect( new Pheasant.Color( 256, 2, 1 ).toString() ).to.equal( '#f00' );
            expect( new Pheasant.Color( Infinity, 2, 4242 ).toString() ).to.equal( '#f0f' );

        });

        it( 'should normalize colors with negative values', function() {

            expect( new Pheasant.Color( -1, 42, 1 ).toString() ).to.equal( '#020' );
            expect( new Pheasant.Color( -Infinity, 2, -4242 ).toString() ).to.equal( '#000' );

        });

        it( 'should normalize colors with float values', function() {

            expect( new Pheasant.Color( 0, 15.99, 1.42 ).toString() ).to.equal( '#010' );

        });

        it( 'should normalize colors with negative float values', function() {

            expect( new Pheasant.Color( 0, -15.99, -1.42 ).toString() ).to.equal( '#000' );

        });

        it( 'should not handle colors with NaN values', function() {

            expect( new Pheasant.Color( 0, NaN, 0 ).toString() ).to.be.null;

        });

    });

    describe( 'to Hex6 format (#abcdef)', function() {

        beforeEach(function() {

            Pheasant.setDefaultStringFormat( 'hex6' );

        });

        it( 'should normalize colors with values higher than 255', function() {

            expect( new Pheasant.Color( 256, 2, 1 ).toString() ).to.equal( '#ff0201' );
            expect( new Pheasant.Color( Infinity, 2, 4242 ).toString() ).to.equal( '#ff02ff' );

        });

        it( 'should normalize colors with negative values', function() {

            expect( new Pheasant.Color( -1, 42, 1 ).toString() ).to.equal( '#002a01' );
            expect( new Pheasant.Color( -Infinity, 2, -4242 ).toString() ).to.equal( '#000200' );

        });

        it( 'should normalize colors with float values', function() {

            expect( new Pheasant.Color( 0, 15.99, 1.42 ).toString() ).to.equal( '#001001' );

        });

        it( 'should normalize colors with negative float values', function() {

            expect( new Pheasant.Color( 0, -15.99, -1.42 ).toString() ).to.equal( '#000000' );

        });

        it( 'should not handle colors with NaN values', function() {

            expect( new Pheasant.Color( 0, NaN, 0 ).toString() ).to.be.null;

        });

    });

    describe( 'to CSS/SVG color names', function() {

        beforeEach(function() {

            Pheasant.setDefaultStringFormat( 'colorname' );

        });

        it( 'should normalize colors with values higher than 255', function() {

            expect( new Pheasant.Color( 256, 0, 0 ).toString() ).to.equal( 'red' );
            expect( new Pheasant.Color( Infinity, 0, 4242 ).toString() ).to.equal( 'fuchsia' );

        });

        it( 'should normalize colors with negative values', function() {

            expect( new Pheasant.Color( -1, 0, 0 ).toString() ).to.equal( 'black' );
            expect( new Pheasant.Color( -Infinity, 128, -4242 ).toString() ).to.equal( 'green' );

        });

        it( 'should normalize colors with float values', function() {

            expect( new Pheasant.Color( 0, 127.7, 0 ).toString() ).to.equal( 'green' );

        });

        it( 'should normalize colors with negative float values', function() {

            expect( new Pheasant.Color( 0, -15.99, -1.42 ).toString() ).to.equal( 'black' );

        });

        it( 'should not handle colors with NaN values', function() {

            expect( new Pheasant.Color( 0, NaN, 0 ).toString() ).to.be.null;

        });

    });

});
<|endoftext|>


<commit_before>var expect = require("chai").expect;
var request = require("request");

var baseURL = "http://localhost:4000";

describe("AirFlow", function () {
	describe("Server", function() {
		it("should respond OK", function(done) {
			request.get(baseURL, function(error, response, body) {
	        	expect(response.statusCode).to.be.equal(200);
	        	done();
	     	});
		});
		describe("Default Case", function() {
			it("should have defaultCase.json", function(done) {
				request.get(baseURL + "/json/defaultCase.json", function(error, response, body) {
		        	expect(response.statusCode).to.be.equal(200);
		        	done();
		     	});
			});
			it("should be a valid .json", function(done) {
				request.get(baseURL + "/json/defaultCase.json", function(error, response, body) {
		        	expect(body).to.be.json;
		        	done();
		     	});
			});
			it("should contain: materials", function(done) {
				request.get(baseURL + "/json/defaultCase.json", function(error, response, body) {
		        	expect(body).to.contain("materials");
		        	done();
		     	});
			});
			it("should contain: dimensions", function(done) {
				request.get(baseURL + "/json/defaultCase.json", function(error, response, body) {
		        	expect(body).to.contain("dimensions");
		        	done();
		     	});
			});
		});
		describe("Default Fans", function() {
			it("should have defaultFans.json", function(done) {
				request.get(baseURL + "/json/defaultFans.json", function(error, response, body) {
		        	expect(response.statusCode).to.be.equal(200);
		        	done();
		     	});
			});
			it("should be a valid .json", function(done) {
				request.get(baseURL + "/json/defaultFans.json", function(error, response, body) {
		        	expect(body).to.be.json;
		        	done();
		     	});
			});
			it("should contain: at least one fan", function(done) {
				request.get(baseURL + "/json/defaultFans.json", function(error, response, body) {
		        	expect(body).to.contain("fanOne");
		        	done();
		     	});
			});
			it("fan should contain: a fan object", function(done) {
				request.get(baseURL + "/json/defaultFans.json", function(error, response, body) {
		        	expect(body).to.contain("fanObject");
		        	done();
		     	});
			});
			it("fan should contain: a fan AOE object", function(done) {
				request.get(baseURL + "/json/defaultFans.json", function(error, response, body) {
		        	expect(body).to.contain("fanAOEObject");
		        	done();
		     	});
			});
			it("fan should contain: properties", function(done) {
				request.get(baseURL + "/json/defaultFans.json", function(error, response, body) {
		        	expect(body).to.contain("properties");
		        	done();
		     	});
			});
		});
	});
});<commit_msg>Added more tests for remaining JSON files<commit_after>var expect = require("chai").expect;
var request = require("request");

var baseURL = "http://localhost:4000";

describe("AirFlow", function () {
	describe("Server", function() {
		it("should respond OK", function(done) {
			request.get(baseURL, function(error, response, body) {
	        	expect(response.statusCode).to.be.equal(200);
	        	done();
	     	});
		});
		describe("Default Project Details", function() {
			it("should have defaultProjectDetails.json", function(done) {
				request.get(baseURL + "/json/defaultProjectDetails.json", function(error, response, body) {
		        	expect(response.statusCode).to.be.equal(200);
		        	done();
		     	});
			});
			it("should be a valid .json", function(done) {
				request.get(baseURL + "/json/defaultProjectDetails.json", function(error, response, body) {
		        	expect(body).to.be.json;
		        	done();
		     	});
			});
			it("should contain a default project definition", function(done) {
				request.get(baseURL + "/json/defaultProjectDetails.json", function(error, response, body) {
		        	expect(body).to.contain("projectName");
		        	expect(body).to.contain("author");
		        	expect(body).to.contain("version");
		        	done();
		     	});
			});
		});
		describe("Default Case", function() {
			it("should have defaultCase.json", function(done) {
				request.get(baseURL + "/json/defaultCase.json", function(error, response, body) {
		        	expect(response.statusCode).to.be.equal(200);
		        	done();
		     	});
			});
			it("should be a valid .json", function(done) {
				request.get(baseURL + "/json/defaultCase.json", function(error, response, body) {
		        	expect(body).to.be.json;
		        	done();
		     	});
			});
			it("should contain a case definition", function(done) {
				request.get(baseURL + "/json/defaultCase.json", function(error, response, body) {
		        	expect(body).to.contain("materials");
		        	expect(body).to.contain("dimensions");
		        	done();
		     	});
			});
		});
		describe("Default Fans", function() {
			it("should have defaultFans.json", function(done) {
				request.get(baseURL + "/json/defaultFans.json", function(error, response, body) {
		        	expect(response.statusCode).to.be.equal(200);
		        	done();
		     	});
			});
			it("should be a valid .json", function(done) {
				request.get(baseURL + "/json/defaultFans.json", function(error, response, body) {
		        	expect(body).to.be.json;
		        	done();
		     	});
			});
			it("should contain at least one fan definition", function(done) {
				request.get(baseURL + "/json/defaultFans.json", function(error, response, body) {
		        	expect(body).to.contain("fanOne");
		        	expect(body).to.contain("fanObject");
		        	expect(body).to.contain("fanAOEObject");
		        	expect(body).to.contain("properties");
		        	done();
		     	});
			});
		});
		describe("Default New Fan", function() {
			it("should have defaultNewFanDetails.json", function(done) {
				request.get(baseURL + "/json/defaultNewFanDetails.json", function(error, response, body) {
		        	expect(response.statusCode).to.be.equal(200);
		        	done();
		     	});
			});
			it("should be a valid .json", function(done) {
				request.get(baseURL + "/json/defaultNewFanDetails.json", function(error, response, body) {
		        	expect(body).to.be.json;
		        	done();
		     	});
			});
			it("should contain a default new fan defintion", function(done) {
				request.get(baseURL + "/json/defaultNewFanDetails.json", function(error, response, body) {
		        	expect(body).to.contain("fanObject");
		        	expect(body).to.contain("material");
		        	expect(body).to.contain("fanAOEObject");
		        	expect(body).to.contain("properties");
		        	done();
		     	});
			});
		});
		describe("Stats Analysis JSON", function() {
			it("should have statsAnalysis.json", function(done) {
				request.get(baseURL + "/json/statsAnalysis.json", function(error, response, body) {
		        	expect(response.statusCode).to.be.equal(200);
		        	done();
		     	});
			});
			it("should be a valid .json", function(done) {
				request.get(baseURL + "/json/statsAnalysis.json", function(error, response, body) {
		        	expect(body).to.be.json;
		        	done();
		     	});
			});
			it("should contain stats analysis values", function(done) {
				request.get(baseURL + "/json/statsAnalysis.json", function(error, response, body) {
		        	expect(body).to.contain("overall");
		        	expect(body).to.contain("result");
		        	expect(body).to.contain("numFans");
		        	expect(body).to.contain("particleSuccessRatio");
		        	expect(body).to.contain("fanRatio");
		        	done();
		     	});
			});
		});
	});
});<|endoftext|>