<commit_before>var util = require ('util');

// Setup
// $ NODE_APP_IFACE=eth0 npm test
var app = require ('./') ({
 iface: process.env.NODE_APP_IFACE || null
});

// handle exits
var errors = 0;
process.on ('exit', function () {
  if (errors === 0) {
    console.log ('\n\033[1mDONE, no errors.\033[0m\n');
    process.exit (0);
  } else {
    console.log ('\n\033[1mFAIL, '+ errors +' error'+ (errors > 1 ? 's' : '') +' occurred!\033[0m\n');
    process.exit (1);
  }
});

// prevent errors from killing the process
process.on ('uncaughtException', function (err) {
  console.log ();
  console.error (err.stack);
  console.trace ();
  console.log ();
  errors++;
});

// Queue to prevent flooding
var queue = [];
var next = 0;

function doNext () {
  next++;
  if (queue [next]) {
    queue [next] ();
  }
}

// doTest( passErr, 'methods', [
//   ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
  if (err instanceof Error) {
    console.error (label +': \033[1m\033[31mERROR\033[0m\n');
    console.error (util.inspect (err, {depth: 10, colors: true}));
    console.log ();
    console.error (err.stack);
    console.log ();
    errors++;
  } else {
    var testErrors = [];
    for (var i = 0; i < tests.length; i++) {
      if (tests [i] [1] !== true) {
        testErrors.push (tests [i] [0]);
        errors++;
      }
    }

    if (testErrors.length === 0) {
      console.log (label +': \033[1m\033[32mok\033[0m');
    } else {
      console.error (label +': \033[1m\033[31mfailed\033[0m ('+ testErrors.join (', ') +')');
    }
  }

  doNext ();
}

queue.push (function () {
  app.getConfig (function (err, data) {
    doTest (err, 'getConfig', [
      ['DatabaseDir', !!data.DatabaseDir],
      ['Interface', !!data.Interface]
    ]);
  })
});

queue.push (function () {
  app.getStats (app.set.iface, function (err, data) {
    doTest (err, 'getStats iface', [
      ['data type', typeof data === 'object'],
      ['id', data.id === app.set.config.Interface],
      ['traffic.days type', data.traffic && data.traffic.days instanceof Array],
      ['traffic.days item', data.traffic && typeof data.traffic.days [0] .rx === 'number']
    ]);
  });
});

queue.push (function () {
  app.getStats (function (err, data) {
    doTest (err, 'getStats default', [
      ['data type', typeof data === 'object'],
      ['id', data.id === app.set.config.Interface],
      ['traffic.days type', data.traffic && data.traffic.days instanceof Array],
      ['traffic.days item', data.traffic && typeof data.traffic.days [0] .rx === 'number']
    ]);
  });
});

queue.push (function () {
  app.getStats ('unreal-iface', function (err) {
    doTest (null, 'getStats error', [
      ['type', err instanceof Error],
      ['message', err.message === 'invalid xml'],
      ['details', !!~err.details.indexOf ('Unable to read database')]
    ]);
  });
});

// Start the tests
console.log ('Running tests...\n');
queue [0] ();
<commit_msg>Test: removed console.trace<commit_after>var util = require ('util');

// Setup
// $ NODE_APP_IFACE=eth0 npm test
var app = require ('./') ({
 iface: process.env.NODE_APP_IFACE || null
});

// handle exits
var errors = 0;
process.on ('exit', function () {
  if (errors === 0) {
    console.log ('\n\033[1mDONE, no errors.\033[0m\n');
    process.exit (0);
  } else {
    console.log ('\n\033[1mFAIL, '+ errors +' error'+ (errors > 1 ? 's' : '') +' occurred!\033[0m\n');
    process.exit (1);
  }
});

// prevent errors from killing the process
process.on ('uncaughtException', function (err) {
  console.log ();
  console.error (err.stack);
  console.log ();
  errors++;
});

// Queue to prevent flooding
var queue = [];
var next = 0;

function doNext () {
  next++;
  if (queue [next]) {
    queue [next] ();
  }
}

// doTest( passErr, 'methods', [
//   ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
  if (err instanceof Error) {
    console.error (label +': \033[1m\033[31mERROR\033[0m\n');
    console.error (util.inspect (err, {depth: 10, colors: true}));
    console.log ();
    console.error (err.stack);
    console.log ();
    errors++;
  } else {
    var testErrors = [];
    for (var i = 0; i < tests.length; i++) {
      if (tests [i] [1] !== true) {
        testErrors.push (tests [i] [0]);
        errors++;
      }
    }

    if (testErrors.length === 0) {
      console.log (label +': \033[1m\033[32mok\033[0m');
    } else {
      console.error (label +': \033[1m\033[31mfailed\033[0m ('+ testErrors.join (', ') +')');
    }
  }

  doNext ();
}

queue.push (function () {
  app.getConfig (function (err, data) {
    doTest (err, 'getConfig', [
      ['DatabaseDir', !!data.DatabaseDir],
      ['Interface', !!data.Interface]
    ]);
  })
});

queue.push (function () {
  app.getStats (app.set.iface, function (err, data) {
    doTest (err, 'getStats iface', [
      ['data type', typeof data === 'object'],
      ['id', data.id === app.set.config.Interface],
      ['traffic.days type', data.traffic && data.traffic.days instanceof Array],
      ['traffic.days item', data.traffic && typeof data.traffic.days [0] .rx === 'number']
    ]);
  });
});

queue.push (function () {
  app.getStats (function (err, data) {
    doTest (err, 'getStats default', [
      ['data type', typeof data === 'object'],
      ['id', data.id === app.set.config.Interface],
      ['traffic.days type', data.traffic && data.traffic.days instanceof Array],
      ['traffic.days item', data.traffic && typeof data.traffic.days [0] .rx === 'number']
    ]);
  });
});

queue.push (function () {
  app.getStats ('unreal-iface', function (err) {
    doTest (null, 'getStats error', [
      ['type', err instanceof Error],
      ['message', err.message === 'invalid xml'],
      ['details', !!~err.details.indexOf ('Unable to read database')]
    ]);
  });
});

// Start the tests
console.log ('Running tests...\n');
queue [0] ();
<|endoftext|>


<commit_before>import path from 'path';
import del from 'del';
import pify from 'pify';
import executable from 'executable';
import exists from 'exists-file';
import test from 'ava';
import arduino from './';

const fixture = path.join.bind(path, __dirname, 'fixtures');

test('arduino should fail to download an unreleased version', async t => {
  const arduinoObj = arduino({version: '1000.0.0', tag: 'fail'});
  const err = await t.throws(pify(arduinoObj.load)());
  t.is(err.statusCode, 404);
});

test('arduino should fail if non semver version is provided', async t => {
  const arduinoObj = arduino({version: '🦄'});
  const err = await t.throws(pify(arduinoObj.load)());
  t.is(err.message, 'Non semver version provided');
});

test('arduino should fail to download versions < 1.5.2', async t => {
  const arduinoObj = arduino({version: '1.5.0'});
  const err = await t.throws(pify(arduinoObj.load)());
  t.is(err.message, 'Arduino command line options are avaiable from the version 1.5.2');
});

test('arduino should load and unload arduino latest', async t => {
  const arduinoObj = arduino({path: 'tmp', tag: 'load'});
  let err = await pify(arduinoObj.load)();
  t.is(err, undefined);
  const bin = await pify(arduinoObj.binary)();
  const exec = await executable(bin);
  t.is(exec, true);
  err = await pify(arduinoObj.unload)();
  t.is(err, undefined);
  const result = await exists(bin);
  t.is(result, false);
});

testVersion('1.8.3');
testVersion('1.8.2');
testVersion('1.8.1');
testVersion('1.8.0');

testVersion('1.7.11');
testVersion('1.7.10');
testVersion('1.7.9');
testVersion('1.7.8');
testVersion('1.7.7');
testVersion('1.7.6');
testVersion('1.7.5');
testVersion('1.7.4');
testVersion('1.7.3');
testVersion('1.7.2');
testVersion('1.7.1');
testVersion('1.7.0');

testVersion('1.6.13');
testVersion('1.6.12');
testVersion('1.6.11');
testVersion('1.6.10');
testVersion('1.6.9');
testVersion('1.6.8');
testVersion('1.6.7');
testVersion('1.6.6');
testVersion('1.6.5');
testVersion('1.6.4');
testVersion('1.6.3');
testVersion('1.6.2');
testVersion('1.6.1');
testVersion('1.6.0');

testVersion('1.5.8');
testVersion('1.5.7');
testVersion('1.5.6');
testVersion('1.5.5');
testVersion('1.5.4');
testVersion('1.5.3');
testVersion('1.5.2');

test.after('cleanup', async t => {
  await t.notThrows(del('tmp'));
});

function testVersion(ver) {
  return test('arduino verify should compile on arduino ' + ver, async t => {
    const arduinoObj = arduino({tag: 'verify', version: ver});
    await pify(arduinoObj.load)();
    const err = await t.throws(pify(arduinoObj.run)(['--verify', fixture('invalid/invalid.ino')]));
    t.is(err.failed, true);
    const out = await pify(arduinoObj.run)(['--verify', fixture('empty/empty.ino')]);
    t.is(out.failed, false);
  });
}
<commit_msg>Update tests<commit_after>import path from 'path';
import del from 'del';
import pify from 'pify';
import executable from 'executable';
import exists from 'exists-file';
import test from 'ava';
import arduino from './';

const fixture = path.join.bind(path, __dirname, 'fixtures');

test('arduino should fail to download versions not available', async t => {
  const arduinoObj = arduino({version: '1.5.0'});
  const err = await t.throws(pify(arduinoObj.load)());
  t.is(err.message, 'The version provided is not available');
});

test('arduino should load and unload arduino latest', async t => {
  const arduinoObj = arduino({path: 'tmp', tag: 'load'});
  let err = await pify(arduinoObj.load)();
  t.is(err, undefined);
  const bin = await pify(arduinoObj.binary)();
  const exec = await executable(bin);
  t.is(exec, true);
  err = await pify(arduinoObj.unload)();
  t.is(err, undefined);
  const result = await exists(bin);
  t.is(result, false);
});

testVersion('1.8.3');
testVersion('1.8.2');
testVersion('1.8.1');
testVersion('1.8.0');

testVersion('1.7.11');
testVersion('1.7.10');
testVersion('1.7.9');
testVersion('1.7.8');
testVersion('1.7.7');
testVersion('1.7.6');
testVersion('1.7.5');
testVersion('1.7.4');
testVersion('1.7.3');
testVersion('1.7.2');
testVersion('1.7.1');
testVersion('1.7.0');

testVersion('1.6.13');
testVersion('1.6.12');
testVersion('1.6.11');
testVersion('1.6.10');
testVersion('1.6.9');
testVersion('1.6.8');
testVersion('1.6.7');
testVersion('1.6.6');
testVersion('1.6.5');
testVersion('1.6.4');
testVersion('1.6.3');
testVersion('1.6.2');
testVersion('1.6.1');
testVersion('1.6.0');

testVersion('1.5.8');
testVersion('1.5.7');
testVersion('1.5.6');
testVersion('1.5.5');
testVersion('1.5.4');
testVersion('1.5.3');
testVersion('1.5.2');

test.after('cleanup', async t => {
  await t.notThrows(del('tmp'));
});

function testVersion(ver) {
  return test('arduino verify should compile on arduino ' + ver, async t => {
    const arduinoObj = arduino({tag: 'verify', version: ver});
    await pify(arduinoObj.load)();
    const err = await t.throws(pify(arduinoObj.run)(['--verify', fixture('invalid/invalid.ino')]));
    t.is(err.failed, true);
    const out = await pify(arduinoObj.run)(['--verify', fixture('empty/empty.ino')]);
    t.is(out.failed, false);
  });
}
<|endoftext|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-20 10:57:55<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

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

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


<commit_before>'use strict';

const fs = require('fs');
const assert = require('assert');
const proxyquire = require('proxyquire');
const _ = require('lodash');
const inventory = proxyquire('./index', {got: gotStub});

function gotStub() {
	return new Promise(resolve => {
		resolve({
			body: fs.readFileSync('./fixtures/success').toString()
		});
	});
}

it('Returnin item attributes', () => {
	return inventory('fooo').then(data => {
		let awp = _.find(data, item => {
			return item.id === '310918879_480995726';
		});

		assert.equal(awp.name, 'StatTrak™ AWP | Redline');
		assert.equal(awp.link, 'steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D7795427765223739405');
		assert.equal(awp.image, 'http://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot621FAR17PLfYQJB496klb-GkvP9JrbummpD78A_3LGXrI-i31fm_Uc5MW_3I4LDelc2YQmF-FPtl7_uh8PtupTMn3pnvD5iuyj-_v0pRA');
		assert.equal(awp.category, 'Sniper Rifle');
		assert.equal(awp.type, 'AWP');
		assert.equal(awp.exterior, 'Field-Tested');
		assert.equal(awp.quality, 'StatTrak™');
	});
});

// it('Return empty array for private user', () => {
// 	return inventory('234234234').then(data => {
// 		assert.equal(data.length, 0);
// 	});
// });

it('Username is mandatory', () => {
	assert.throws(() => {
		inventory();
	});
});
<commit_msg>cleanup tests<commit_after>'use strict';

const fs = require('fs');
const assert = require('assert');
const proxyquire = require('proxyquire');
const _ = require('lodash');

let stub = {};
['success', 'private', 'error'].forEach(item => {
	stub[item] = function () {
		return new Promise(resolve => {
			resolve({
				body: fs.readFileSync(`./fixtures/${item}`).toString()
			});
		});
	};
});

const inventory = proxyquire('./index', {got: stub.success});
const inventory2 = proxyquire('./index', {got: stub.private});
const inventory3 = proxyquire('./index', {got: stub.error});

it('Returnin item attributes', () => {
	return inventory('fooo').then(data => {
		let awp = _.find(data, item => {
			return item.id === '310918879_480995726';
		});

		assert.equal(awp.name, 'StatTrak™ AWP | Redline');
		assert.equal(awp.link, 'steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D7795427765223739405');
		assert.equal(awp.image, 'http://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot621FAR17PLfYQJB496klb-GkvP9JrbummpD78A_3LGXrI-i31fm_Uc5MW_3I4LDelc2YQmF-FPtl7_uh8PtupTMn3pnvD5iuyj-_v0pRA');
		assert.equal(awp.category, 'Sniper Rifle');
		assert.equal(awp.type, 'AWP');
		assert.equal(awp.exterior, 'Field-Tested');
		assert.equal(awp.quality, 'StatTrak™');
	});
});

it('Return empty array for private user', () => {
	return inventory2('234234234').then(data => {
		assert.equal(data.length, 0);
	});
});

it('Return empty array for non existing user', () => {
	return inventory3('234234234').then(data => {
		assert.equal(data.length, 0);
	});
});

it('Username is mandatory', () => {
	assert.throws(() => {
		inventory();
	});
});
<|endoftext|>


<commit_before>var WooCommerce = require('./index.js');
var chai = require('chai');
var nock = require('nock');

describe('#Construct', function() {
  it('should throw an error if the url, consumerKey or consumerSecret are missing', function() {
    chai.expect(function() {
      new WooCommerce();
    }).to.throw(Error);
  });

  it('should set the default options', function() {
    var api = new WooCommerce({
      url: 'http://test.dev',
      consumerKey: 'foo',
      consumerSecret: 'foo'
    });

    chai.expect(api.version).to.equal('v3');
    chai.expect(api.isSsl).to.be.false;
    chai.expect(api.verifySsl).to.be.true;
    chai.expect(api.encoding).to.equal('utf8');
  });
});

describe('#Requests', function() {
  beforeEach(function() {
    nock.cleanAll();
  });

  var api = new WooCommerce({
    url: 'https://test.dev',
    consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  });

  it('should return content for basic auth', function(done) {
    nock('https://test.dev/wc-api/v3').post('/orders', {}).reply(200, {
      ok: true
    });

    api.post('orders', {}, function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for get requests', function(done) {
    nock('https://test.dev/wc-api/v3').get('/orders').reply(200, {
      ok: true
    });

    api.get('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for put requests', function(done) {
    nock('https://test.dev/wc-api/v3').put('/orders', {}).reply(200, {
      ok: true
    });

    api.put('orders', {}, function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for delete requests', function(done) {
    nock('https://test.dev/wc-api/v3').delete('/orders').reply(200, {
      ok: true
    });

    api.delete('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should no return content when not using ssl', function(done) {
    nock('http://test.dev/wc-api/v3').get('/orders').reply(200, {
      ok: true
    });

    api.get('orders', function(err, data) {
      chai.expect(err).to.exist;
      chai.expect(data).to.not.exist;
      done();
    });
  });

  it('should return content for OAuth', function(done) {
    var oAuth = new WooCommerce({
      url: 'http://test.dev',
      consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    });

    nock('http://test.dev/wc-api/v3').filteringPath(/\?.*/, '?params').get('/orders?params').reply(200, {
      ok: true
    });

    oAuth.get('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

});
<commit_msg>Updated test example<commit_after>var WooCommerce = require('./index.js');
var chai = require('chai');
var nock = require('nock');

describe('#Construct', function() {
  it('should throw an error if the url, consumerKey or consumerSecret are missing', function() {
    chai.expect(function() {
      new WooCommerce();
    }).to.throw(Error);
  });

  it('should set the default options', function() {
    var api = new WooCommerce({
      url: 'http://test.dev',
      consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    });

    chai.expect(api.version).to.equal('v3');
    chai.expect(api.isSsl).to.be.false;
    chai.expect(api.verifySsl).to.be.true;
    chai.expect(api.encoding).to.equal('utf8');
  });
});

describe('#Requests', function() {
  beforeEach(function() {
    nock.cleanAll();
  });

  var api = new WooCommerce({
    url: 'https://test.dev',
    consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  });

  it('should return content for basic auth', function(done) {
    nock('https://test.dev/wc-api/v3').post('/orders', {}).reply(200, {
      ok: true
    });

    api.post('orders', {}, function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for get requests', function(done) {
    nock('https://test.dev/wc-api/v3').get('/orders').reply(200, {
      ok: true
    });

    api.get('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for put requests', function(done) {
    nock('https://test.dev/wc-api/v3').put('/orders', {}).reply(200, {
      ok: true
    });

    api.put('orders', {}, function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for delete requests', function(done) {
    nock('https://test.dev/wc-api/v3').delete('/orders').reply(200, {
      ok: true
    });

    api.delete('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should no return content when not using ssl', function(done) {
    nock('http://test.dev/wc-api/v3').get('/orders').reply(200, {
      ok: true
    });

    api.get('orders', function(err, data) {
      chai.expect(err).to.exist;
      chai.expect(data).to.not.exist;
      done();
    });
  });

  it('should return content for OAuth', function(done) {
    var oAuth = new WooCommerce({
      url: 'http://test.dev',
      consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    });

    nock('http://test.dev/wc-api/v3').filteringPath(/\?.*/, '?params').get('/orders?params').reply(200, {
      ok: true
    });

    oAuth.get('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

});
<|endoftext|>


<commit_before>var RRD = require('./index.js');

var rrd = new RRD('foo')
  .step('1s')
  .gauge('bar')
  .gauge('foo')
  .average({
    resolution: '1s',
    for: '1h'
  })
  .average({
    resolution: '5s',
    for: '5h'
  })
  /*.create(function(err) {
    if(err) console.log(err);
    else console.log('Success!');
  });*/

var i = 0;
setInterval(function() {
  var i = (new Date().getTime()/1000).toFixed(0)
  rrd.update(
    [(Math.sin(i*Math.PI/180)+1)*5000,
    Math.random()*10000], function(err) {
      if(err) console.log(err);
      else console.log('Updated!');
    });
}, 1000);

rrd.graph()
  .from('-10m')
  .smooth('foo', '1m')
    .as('foo_smooth')
  .smooth('bar', '2m')
    .as('bar_smooth')
  .line('foo', '#ff000044')
  .line('bar', '#00ff0044')
  .line('foo_smooth', '#ff0000')
  .line('bar_smooth', '#00ff00')
  .table()
  .create('file.png');
<commit_msg>Example updated<commit_after>var RRD = require('./index.js');

var rrd = new RRD('foo')
  .step('1s')
  .gauge('bar')
  .gauge('foo')
  .average({
    resolution: '1s',
    for: '1h'
  })
  .average({
    resolution: '5s',
    for: '5h'
  })
  /*.create(function(err) {
    if(err) console.log(err);
    else console.log('Success!');
  });*/

var i = 0;
setInterval(function() {
  var i = (new Date().getTime()/1000).toFixed(0)
  rrd.update(
    [(Math.sin(i*Math.PI/180)+1)*5000,
    Math.random()*10000], function(err) {
      if(err) console.log(err);
      else console.log('Updated!');
    });
}, 1000);

rrd.graph()
  .from('-10m')
  .title('Example graph with random values')
  .watermark('%a')
  .vlabel('Awesomeness')
  .smooth('foo', '10s')
    .as('foo_smooth')
  .smooth('bar', '3m')
    .as('bar_smooth')
  .line('foo', '#ff000044')
  .line('bar', '#00ff0044')
  .line('foo_smooth', '#ff0000')
  .line('bar_smooth', '#00ff00')
  .table()
  .create('file.png');
<|endoftext|>


<commit_before>'use strict';

/**
 * Test runner for gulp-cordova-plugin.
 *
 * @author Sam Verschueren      <sam.verschueren@gmail.com>
 * @since  19 Aug. 2015
 */

// module dependencies
var chai = require('chai'),
    sinon = require('sinon'),
    sinonChai = require('sinon-chai'),
    cordova = require('cordova-lib').cordova.raw,
    Q = require('q'),
    gutil = require('gulp-util');

// Use should flavour and use sinon-chai
chai.should();
chai.use(sinonChai);

var preference = require('./');

describe('gulp-cordova-plugin', function() {

    beforeEach(function() {
        // Set the plugin method to a spy function
        cordova.plugin = sinon.spy();
    });

    describe('Simple plugin', function() {

        it('Should add the `cordova-plugin-globalization` plugin', function(done) {
            var stream = preference('cordova-plugin-globalization');

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWithExactly('add', 'cordova-plugin-globalization', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `cordova-plugin-globalization@1.0.0` plugin if the version is provided as 2nd argument', function(done) {
            var stream = preference('cordova-plugin-globalization', '1.0.0');

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'cordova-plugin-globalization@1.0.0', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `cordova-plugin-globalization@1.0.0` plugin if the version is provided in the object as 2nd argument', function(done) {
            var stream = preference('cordova-plugin-globalization', {version: '1.0.0'});

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'cordova-plugin-globalization@1.0.0', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `plugin.google.maps` plugin with variables if the variables are added in the options object', function(done) {
            var vars = {
                'API_KEY_FOR_ANDROID': 'ANDROID_KEY',
                'API_KEY_FOR_IOS': 'IOS_KEY'
            };

            var stream = preference('plugin.google.maps', {variables: vars});

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'plugin.google.maps', {cli_variables: vars});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `plugin.google.maps@latest` plugin with variables if the version and variables are added in the options object', function(done) {
            var vars = {
                'API_KEY_FOR_ANDROID': 'ANDROID_KEY',
                'API_KEY_FOR_IOS': 'IOS_KEY'
            };

            var stream = preference('plugin.google.maps', {version: 'latest', variables: vars});

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'plugin.google.maps@latest', {cli_variables: vars});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });
    });

    describe('Plugin list', function() {

        it('Should call the add plugin method twice if two plugins are provided', function(done) {
            var stream = preference([
                'org.apache.cordova.dialogs',
                'org.apache.cordova.camera'
            ]);

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledTwice;

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `org.apache.cordova.dialogs` and `org.apache.cordova.camera` plugins', function(done) {
            var stream = preference([
                'org.apache.cordova.dialogs',
                'org.apache.cordova.camera'
            ]);

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.dialogs', {});
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.camera', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should do nothing with the options object if provided', function(done) {
            var stream = preference([
                'org.apache.cordova.dialogs',
                'org.apache.cordova.camera'
            ], {version: '1.0.0', variables: {foo: 'bar'}});

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.dialogs', {});
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.camera', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });
    });
});<commit_msg>Added tests for the plugin object<commit_after>'use strict';

/**
 * Test runner for gulp-cordova-plugin.
 *
 * @author Sam Verschueren      <sam.verschueren@gmail.com>
 * @since  19 Aug. 2015
 */

// module dependencies
var chai = require('chai'),
    sinon = require('sinon'),
    sinonChai = require('sinon-chai'),
    cordova = require('cordova-lib').cordova.raw,
    Q = require('q'),
    gutil = require('gulp-util');

// Use should flavour and use sinon-chai
chai.should();
chai.use(sinonChai);

var preference = require('./');

describe('gulp-cordova-plugin', function() {

    beforeEach(function() {
        // Set the plugin method to a spy function
        cordova.plugin = sinon.spy();
    });

    describe('Simple plugin', function() {

        it('Should add the `cordova-plugin-globalization` plugin', function(done) {
            var stream = preference('cordova-plugin-globalization');

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWithExactly('add', 'cordova-plugin-globalization', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `cordova-plugin-globalization@1.0.0` plugin if the version is provided as 2nd argument', function(done) {
            var stream = preference('cordova-plugin-globalization', '1.0.0');

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'cordova-plugin-globalization@1.0.0', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `cordova-plugin-globalization@1.0.0` plugin if the version is provided in the object as 2nd argument', function(done) {
            var stream = preference('cordova-plugin-globalization', {version: '1.0.0'});

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'cordova-plugin-globalization@1.0.0', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `plugin.google.maps` plugin with variables if the variables are added in the options object', function(done) {
            var vars = {
                'API_KEY_FOR_ANDROID': 'ANDROID_KEY',
                'API_KEY_FOR_IOS': 'IOS_KEY'
            };

            var stream = preference('plugin.google.maps', {variables: vars});

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'plugin.google.maps', {cli_variables: vars});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `plugin.google.maps@latest` plugin with variables if the version and variables are added in the options object', function(done) {
            var vars = {
                'API_KEY_FOR_ANDROID': 'ANDROID_KEY',
                'API_KEY_FOR_IOS': 'IOS_KEY'
            };

            var stream = preference('plugin.google.maps', {version: 'latest', variables: vars});

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'plugin.google.maps@latest', {cli_variables: vars});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });
    });

    describe('Plugin list', function() {

        it('Should call the add plugin method twice if two plugins are provided', function(done) {
            var stream = preference([
                'org.apache.cordova.dialogs',
                'org.apache.cordova.camera'
            ]);

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledTwice;

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `org.apache.cordova.dialogs` and `org.apache.cordova.camera` plugins', function(done) {
            var stream = preference([
                'org.apache.cordova.dialogs',
                'org.apache.cordova.camera'
            ]);

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.dialogs', {});
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.camera', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should do nothing with the options object if provided', function(done) {
            var stream = preference([
                'org.apache.cordova.dialogs',
                'org.apache.cordova.camera'
            ], {version: '1.0.0', variables: {foo: 'bar'}});

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.dialogs', {});
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.camera', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });
    });

    describe('Plugin object', function() {

        it('Should call the add plugin method twice if two plugins are provided', function(done) {
            var stream = preference({
                'org.apache.cordova.dialogs': 'latest',
                'org.apache.cordova.camera': '1.0.0'
            });

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledTwice;

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `org.apache.cordova.dialogs@latest` and `org.apache.cordova.camera@1.0.0` plugins', function(done) {
            var stream = preference({
                'org.apache.cordova.dialogs': 'latest',
                'org.apache.cordova.camera': '1.0.0'
            });

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.dialogs@latest', {});
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.camera@1.0.0', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `org.apache.cordova.dialogs@latest`, `org.apache.cordova.camera@1.0.0` and `plugin.google.maps` with variables', function(done) {
            var stream = preference({
                'org.apache.cordova.dialogs': 'latest',
                'org.apache.cordova.camera': '1.0.0',
                'plugin.google.maps': {
                    variables : {
                        'API_KEY_FOR_ANDROID': 'ANDROID_KEY',
                        'API_KEY_FOR_IOS': 'IOS_KEY'
                    }
                }
            });

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.dialogs@latest', {});
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.camera@1.0.0', {});
                cordova.plugin.should.have.been.calledWith('add', 'plugin.google.maps', { cli_variables: { 'API_KEY_FOR_ANDROID': 'ANDROID_KEY', 'API_KEY_FOR_IOS': 'IOS_KEY' }});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should add the `org.apache.cordova.dialogs@latest`, `org.apache.cordova.camera@1.0.0` and `plugin.google.maps@1.0.0` with variables', function(done) {
            var stream = preference({
                'org.apache.cordova.dialogs': 'latest',
                'org.apache.cordova.camera': '1.0.0',
                'plugin.google.maps': {
                    version: '1.0.0',
                    variables : {
                        'API_KEY_FOR_ANDROID': 'ANDROID_KEY',
                        'API_KEY_FOR_IOS': 'IOS_KEY'
                    }
                }
            });

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.dialogs@latest', {});
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.camera@1.0.0', {});
                cordova.plugin.should.have.been.calledWith('add', 'plugin.google.maps@1.0.0', { cli_variables: { 'API_KEY_FOR_ANDROID': 'ANDROID_KEY', 'API_KEY_FOR_IOS': 'IOS_KEY' }});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });

        it('Should do nothing with the options object if provided', function(done) {
            var stream = preference({
                'org.apache.cordova.dialogs': 'latest',
                'org.apache.cordova.camera': '1.0.0'
            }, {version: '1.0.0', variables: {foo: 'bar'}});

            stream.on('end', function() {
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.dialogs@latest', {});
                cordova.plugin.should.have.been.calledWith('add', 'org.apache.cordova.camera@1.0.0', {});

                done();
            });

            stream.on('data', function() {});

            stream.end();
        });
    });
});<|endoftext|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-6-14 17:15:53<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

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

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


<commit_before>const Q = require('./lib/q').default;
const redis = require('redis');
require('colors');

function queueTest() {
  console.log('Queue test'.green);

  function Herp() {
  }
  Herp.prototype.toRedisString = function () {
    throw new Error('lol');
  };

  const client = redis.createClient();
  const q = new Q(client, 'herp');
  q.enqueue(new Herp)
    .then(n => {
      console.log(`Now there are ${n} items`)
      client.quit();
    })
    .catch(err => {
      console.error(err);
      client.quit();
    });
}

function parseTest() {
  console.log('Parse test'.green);
  const fs = require('fs');
  const parsePipeline = require('./lib/esprima-pipeline.js').default;

  const file = fs.readFileSync('test.js', 'utf8');
  const result = parsePipeline(file);
  console.dir(result);
}

parseTest();
<commit_msg>Start writing test...<commit_after>const fs = require('fs');
require('colors');

function queueTest() {
  console.log('Queue test'.green);

  const Q = require('./lib/q').default;
  const redis = require('redis');

  function Herp() {
  }
  Herp.prototype.toRedisString = function () {
    throw new Error('lol');
  };

  const client = redis.createClient();
  const q = new Q(client, 'herp');
  q.enqueue(new Herp)
    .then(n => {
      console.log(`Now there are ${n} items`)
      client.quit();
    })
    .catch(err => {
      console.error(err);
      client.quit();
    });
}

function parseTest() {
  console.log('Parse test'.green);
  const parsePipeline = require('./lib/esprima-pipeline.js').default;

  const file = fs.readFileSync('test.js', 'utf8');
  const result = parsePipeline(file);
  console.dir(result);
}

function dbTest() {
  console.log('Database test'.green);

  const sqlite3 = require('sqlite3').verbose();
  const db = new sqlite3.Database(':memory:');

  const schema = fs.readFileSync('./schema.sql', 'utf8');

  db.serialize(() => {
    db.run(schema);
  });

  db.close();
}

dbTest();
<|endoftext|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-24 01:41:22<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

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

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


<commit_before>(function(){
	"use strict";
	/*
	  (TODO) data format for expedition table:
	  - for income modifier:

	      - standard modifier:

		  { type: "normal",
	        gs: true / false,
			daihatsu: 0 ~ 4
		  }

			  - "gs" indicates whether great success is intended
			  - whoever saves the data is responsible for its consistency
			    if say daihatsu value turns out to be 5, that's not my fault

		  - custom modifier:

          { type: "direct",
		    value: a number, from 1.0 to perhaps 2.0 (meaning 100% ~ 200%)
		  }

		      - great success should be taken into account by custom modifier.
			    which means if user intends to carry 4 daihatsus and ensure GS,
				this value needs to be 1.8 (1.5 * 1.2)
			  - the design decision is made in this way so that if future update
                adds some mechanism that affect GS modifier, we will still be flexible.

	  - for cost:
	      - cost deals with the problem that user might carry extra ships for
            a higher GS rate.

	      - standard:

		  { type: "costmodel",
		    wildcard: "DD" / "SS" / false,
			count: 0 ~ 6
		  }

		  - custom:

		  { type: "custom",
		    fuel: integer (non-negative),
			ammo: integer (non-negative)
		  }
	 */

	KC3StrategyTabs.expedtable = new KC3StrategyTab("expedtable");

	KC3StrategyTabs.expedtable.definition = {
		tabSelf: KC3StrategyTabs.expedtable,

		/* INIT: mandatory
		Prepares initial static data needed.
		---------------------------------*/
		init: function() {
		},

		/* RELOAD: optional
		Loads latest player or game data if needed.
		---------------------------------*/
		reload: function() {
		},

		/* EXECUTE: mandatory
		Places data onto the interface from scratch.
		---------------------------------*/
		execute: function() {
			var ExpedInfo = PS["KanColle.Expedition.New.Info"];
			var ExpedSType = PS["KanColle.Expedition.New.SType"];
			var factory = $(".tab_expedtable .factory");
			var expedTableRoot = $("#exped_table_content_root");
			var ExpedCostModel = PS["KanColle.Expedition.New.CostModel"];
			var Maybe = PS["Data.Maybe"];
			var PartialUnsafe = PS["Partial.Unsafe"];
			function calcCostModel(stypeInstance, num) {
				return ExpedCostModel.normalCostModel(stypeInstance)(num);
			}

			var allExpeds = [];
			var i;
			for (i=1; i<=40; ++i)
				allExpeds.push(i);

			function makeWinItem( jqObj, winItemArr ) {
				var itemId = winItemArr[0];
				var idToItem = {
					1: "bucket",
					2: "ibuild",
					3: "devmat",
					10: "box1",
					11: "box2",
					12: "box3"
				};
				if (itemId !== 0) {
					jqObj
						.append($(
							"<img>",
							{src: "../../assets/img/client/"+idToItem[itemId]+".png"}))
					    .append("x" + winItemArr[1]);
				} else {
					jqObj.text( "-" );
				}
			}

			allExpeds.forEach( function(eId) {
				var expedRow = $(".exped_row", factory).clone();
				var resourceInfo = ExpedInfo.getInformation( eId ).resource;
				var masterInfo = KC3Master._raw.mission[eId];

				$(".info_col.id", expedRow).text( eId );
				$(".info_col.time", expedRow).text( String( 60 * masterInfo.api_time ).toHHMMSS() );

				["fuel", "ammo", "steel", "bauxite"].forEach( function(name) {
					$(".info_col." + name, expedRow).text( resourceInfo[name] );
				});

				makeWinItem( $(".info_col.item1", expedRow), masterInfo.api_win_item1 );
				makeWinItem( $(".info_col.item2", expedRow), masterInfo.api_win_item2 );

				var mkFlg = () => Math.random() > 0.5;

				var flg = mkFlg();
				$(".modifier .view.view_general", expedRow).toggle( flg );
				$(".modifier .view.view_normal", expedRow).toggle( !flg );

				var flg2 = mkFlg();
				$(".cost .view.view_general", expedRow).toggle( flg2 );
				$(".cost .view.view_normal", expedRow).toggle( !flg2 );

				$(".modifier .view.view_general", expedRow).text("+50.00%");

				$(".modifier .view.view_normal img.gs", expedRow).attr(
					"src", mkFlg()
						? "../../assets/img/ui/btn-gs.png"
						: "../../assets/img/ui/btn-xgs.png" );
				$(".modifier .view.view_normal .dht_times", expedRow).text("x4");

				$(".cost .view.view_general .fuel", expedRow).text("-100");
				$(".cost .view.view_general .ammo", expedRow).text("-100");

				expedTableRoot.append( expedRow );
			});

			// setup cost model
			let tableRoot = $(".tab_expedtable #cost_model_content_root table");

			// setup slider controls
			let ticks = Array.from(Array(10 + 1).keys(), x => x * 10);
			let sliderSettings = {
				// ticks = [0,10..100]
				ticks: Array.from(Array(10 + 1).keys(), x => x * 10),
				step: 10,
				value: 80,
				tooltip: "hide"
			};
			$("input#cost_model_fuel").slider(sliderSettings).on("change", function(e) {
				console.log("fuel", e.value.newValue);
			});
			$("input#cost_model_ammo").slider(sliderSettings).on("change", function(e) {
				console.log("ammo", e.value.newValue);
			});

			// setup table
			let stypeTexts = [
				"DD", "CL", "CVLike", "SSLike",
				"CA", "BBV", "AS", "CT", "AV"];

			let tableBody = $("tbody",tableRoot);
			stypeTexts.map( function(stype) {
				let tblRow = $("<tr>");
				tblRow.append( $("<th>").text( stype ) );
				for (let i=1; i<=6; ++i) {

					let stypeInst = ExpedSType[stype].value;
					let costResult = calcCostModel(stypeInst, i);
					let cell;

					if (Maybe.isJust( costResult )) {
						cell = $(".tab_expedtable .factory .cost_cell").clone();
						let costSum = PartialUnsafe.unsafePartial(Maybe.fromJust)
							(costResult).reduce( function(acc, cur) {
							return { ammo: acc.ammo + cur.ammo,
									 fuel: acc.fuel + cur.fuel };
						}, {ammo: 0, fuel: 0});
						$(".ammo", cell).text( costSum.ammo );
						$(".fuel", cell).text( costSum.fuel );
					} else {
						cell = $(".tab_expedtable .factory .cost_cell_na").clone();
					}
					tblRow.append( $("<td />").append(cell) );
				}

				tableBody.append( tblRow );
			});
		},

		/* UPDATE: optional
		Partially update elements of the interface,
			possibly without clearing all contents first.
		Be careful! Do not only update new data,
			but also handle the old states (do cleanup).
		Return `false` if updating all needed,
			EXECUTE will be invoked instead.
		---------------------------------*/
		update: function(pageParams) {
			// Use `pageParams` for latest page hash values,
			// KC3StrategyTabs.pageParams keeps the old values for states tracking

			// Returning `true` means updating has been handled.
			return false;
		}
	};
})();
<commit_msg>attach max consumption to elements<commit_after>(function(){
	"use strict";
	/*
	  (TODO) data format for expedition table:
	  - for income modifier:

	      - standard modifier:

		  { type: "normal",
	        gs: true / false,
			daihatsu: 0 ~ 4
		  }

			  - "gs" indicates whether great success is intended
			  - whoever saves the data is responsible for its consistency
			    if say daihatsu value turns out to be 5, that's not my fault

		  - custom modifier:

          { type: "direct",
		    value: a number, from 1.0 to perhaps 2.0 (meaning 100% ~ 200%)
		  }

		      - great success should be taken into account by custom modifier.
			    which means if user intends to carry 4 daihatsus and ensure GS,
				this value needs to be 1.8 (1.5 * 1.2)
			  - the design decision is made in this way so that if future update
                adds some mechanism that affect GS modifier, we will still be flexible.

	  - for cost:
	      - cost deals with the problem that user might carry extra ships for
            a higher GS rate.

	      - standard:

		  { type: "costmodel",
		    wildcard: "DD" / "SS" / false,
			count: 0 ~ 6
		  }

		  - custom:

		  { type: "custom",
		    fuel: integer (non-negative),
			ammo: integer (non-negative)
		  }
	 */

	KC3StrategyTabs.expedtable = new KC3StrategyTab("expedtable");

	KC3StrategyTabs.expedtable.definition = {
		tabSelf: KC3StrategyTabs.expedtable,

		/* INIT: mandatory
		Prepares initial static data needed.
		---------------------------------*/
		init: function() {
		},

		/* RELOAD: optional
		Loads latest player or game data if needed.
		---------------------------------*/
		reload: function() {
		},

		/* EXECUTE: mandatory
		Places data onto the interface from scratch.
		---------------------------------*/
		execute: function() {
			var ExpedInfo = PS["KanColle.Expedition.New.Info"];
			var ExpedSType = PS["KanColle.Expedition.New.SType"];
			var factory = $(".tab_expedtable .factory");
			var expedTableRoot = $("#exped_table_content_root");
			var ExpedCostModel = PS["KanColle.Expedition.New.CostModel"];
			var Maybe = PS["Data.Maybe"];
			var PartialUnsafe = PS["Partial.Unsafe"];
			function calcCostModel(stypeInstance, num) {
				return ExpedCostModel.normalCostModel(stypeInstance)(num);
			}

			var allExpeds = [];
			var i;
			for (i=1; i<=40; ++i)
				allExpeds.push(i);

			function makeWinItem( jqObj, winItemArr ) {
				var itemId = winItemArr[0];
				var idToItem = {
					1: "bucket",
					2: "ibuild",
					3: "devmat",
					10: "box1",
					11: "box2",
					12: "box3"
				};
				if (itemId !== 0) {
					jqObj
						.append($(
							"<img>",
							{src: "../../assets/img/client/"+idToItem[itemId]+".png"}))
					    .append("x" + winItemArr[1]);
				} else {
					jqObj.text( "-" );
				}
			}

			allExpeds.forEach( function(eId) {
				var expedRow = $(".exped_row", factory).clone();
				var resourceInfo = ExpedInfo.getInformation( eId ).resource;
				var masterInfo = KC3Master._raw.mission[eId];

				$(".info_col.id", expedRow).text( eId );
				$(".info_col.time", expedRow).text( String( 60 * masterInfo.api_time ).toHHMMSS() );

				["fuel", "ammo", "steel", "bauxite"].forEach( function(name) {
					$(".info_col." + name, expedRow).text( resourceInfo[name] );
				});

				makeWinItem( $(".info_col.item1", expedRow), masterInfo.api_win_item1 );
				makeWinItem( $(".info_col.item2", expedRow), masterInfo.api_win_item2 );

				var mkFlg = () => Math.random() > 0.5;

				var flg = mkFlg();
				$(".modifier .view.view_general", expedRow).toggle( flg );
				$(".modifier .view.view_normal", expedRow).toggle( !flg );

				var flg2 = mkFlg();
				$(".cost .view.view_general", expedRow).toggle( flg2 );
				$(".cost .view.view_normal", expedRow).toggle( !flg2 );

				$(".modifier .view.view_general", expedRow).text("+50.00%");

				$(".modifier .view.view_normal img.gs", expedRow).attr(
					"src", mkFlg()
						? "../../assets/img/ui/btn-gs.png"
						: "../../assets/img/ui/btn-xgs.png" );
				$(".modifier .view.view_normal .dht_times", expedRow).text("x4");

				$(".cost .view.view_general .fuel", expedRow).text("-100");
				$(".cost .view.view_general .ammo", expedRow).text("-100");

				expedTableRoot.append( expedRow );
			});

			// setup cost model
			let contentRoot = $(".tab_expedtable #cost_model_content_root");
			let tableRoot = $("table", contentRoot);

			// setup slider controls
			let ticks = Array.from(Array(10 + 1).keys(), x => x * 10);
			let sliderSettings = {
				// ticks = [0,10..100]
				ticks: Array.from(Array(10 + 1).keys(), x => x * 10),
				step: 10,
				value: 80,
				tooltip: "hide"
			};
			let viewFuelPercent = $(".control_row.fuel .val");
			let viewAmmoPercent = $(".control_row.ammo .val");
			$("input#cost_model_fuel").slider(sliderSettings).on("change", function(e) {
				viewFuelPercent.text( e.value.newValue + "%" );
			});
			$("input#cost_model_ammo").slider(sliderSettings).on("change", function(e) {
				viewAmmoPercent.text( e.value.newValue + "%" );
			});

			// setup table
			let stypeTexts = [
				"DD", "CL", "CVLike", "SSLike",
				"CA", "BBV", "AS", "CT", "AV"];

			let tableBody = $("tbody",tableRoot);
			stypeTexts.map( function(stype) {
				let tblRow = $("<tr>");
				tblRow.append( $("<th>").text( stype ) );
				for (let i=1; i<=6; ++i) {

					let stypeInst = ExpedSType[stype].value;
					let costResult = calcCostModel(stypeInst, i);
					let cell;

					if (Maybe.isJust( costResult )) {
						cell = $(".tab_expedtable .factory .cost_cell").clone();
						let costSum = PartialUnsafe.unsafePartial(Maybe.fromJust)
							(costResult).reduce( function(acc, cur) {
							return { ammo: acc.ammo + cur.ammo,
									 fuel: acc.fuel + cur.fuel };
						}, {ammo: 0, fuel: 0});

						cell.data( "max-consumption", costSum );

						$(".ammo", cell).text( costSum.ammo );
						$(".fuel", cell).text( costSum.fuel );
					} else {
						cell = $(".tab_expedtable .factory .cost_cell_na").clone();
					}
					tblRow.append( $("<td />").append(cell) );
				}

				tableBody.append( tblRow );
			});
		},

		/* UPDATE: optional
		Partially update elements of the interface,
			possibly without clearing all contents first.
		Be careful! Do not only update new data,
			but also handle the old states (do cleanup).
		Return `false` if updating all needed,
			EXECUTE will be invoked instead.
		---------------------------------*/
		update: function(pageParams) {
			// Use `pageParams` for latest page hash values,
			// KC3StrategyTabs.pageParams keeps the old values for states tracking

			// Returning `true` means updating has been handled.
			return false;
		}
	};
})();
<|endoftext|>


<commit_before>import test from 'ava';
import shell from 'shelljs';
import m from './';

shell.config.silent = true;

test('mock and unmock git bla', async t => {
	const log = 'mocking git bla!';
	const unmock = await m(`console.log('${log}')`, 'bla');
	let actual = shell.exec('git bla').stdout;
	t.is(log + '\n', actual);

	actual = shell.exec('git').stdout;
	t.not(log + '\n', actual);

	unmock();
	actual = shell.exec('git bla').stdout;
	t.not(log + '\n', actual);
});

test('mock and unmock git --no-pager bla', async t => {
	const log = 'mocking git bla!';
	const unmock = await m(`console.log('${log}')`, 'bla');
	let actual = shell.exec('git --no-pager bla').stdout;
	t.is(log + '\n', actual);

	actual = shell.exec('git').stdout;
	t.not(log + '\n', actual);

	unmock();
	actual = shell.exec('git --no-pager bla').stdout;
	t.not(log + '\n', actual);
});

test('mocking bar does not affect foo', async t => {
	const fooLog = 'mocking foo!';
	await m(`console.log('${fooLog}')`, 'foo');

	const barLog = 'mocking bar!';
	await m(`console.log('${barLog}')`, 'bar');

	let barActual = shell.exec('git bar').stdout;
	t.is(barLog + '\n', barActual);

	barActual = shell.exec('git --no-pager bar').stdout;
	t.is(barLog + '\n', barActual);

	let fooActual = shell.exec('git foo').stdout;
	t.is(fooLog + '\n', fooActual);

	fooActual = shell.exec('git --no-pager foo').stdout;
	t.is(fooLog + '\n', fooActual);

	const stderr = shell.exec('git log').stderr;
	t.falsy(stderr);
});

test('mocking git', async t => {
	const log = 'mocking git!';
	const unmock = await m(`console.log('${log}')`);

	let actual = shell.exec('git');
	t.is(log + '\n', actual.stdout);
	t.falsy(actual.stderr);

	actual = shell.exec('git foo');
	t.is(log + '\n', actual.stdout);
	t.falsy(actual.stderr);

	actual = shell.exec('git --no-pager log');
	t.is(log + '\n', actual.stdout);
	t.falsy(actual.stderr);

	unmock();
	actual = shell.exec('git');
	t.not(log + '\n', actual.stdout);
	t.falsy(actual.stderr);
});

test('passing arguments while mocking only commit', async t => {
	const unmock = await m(`console.log(process.argv.splice(2).join(' '));`, 'commit');
	const args = 'commit --obviously-invalid-arg -m "second commit with spaces!"';

	const actual = shell.exec(`git ${args}`);
	t.falsy(actual.stderr);
	t.is(`${args.replace(new RegExp('"', 'g'), '')}\n`, actual.stdout);

	unmock();
});

test('passing arguments while mocking whole git', async t => {
	const unmock = await m(`console.log(process.argv.splice(2).join(' '));`);
	const args = 'commit --obviously-invalid-arg -m "third commit with spaces!"';

	const actual = shell.exec(`git ${args}`);
	t.falsy(actual.stderr);
	t.is(`${args.replace(new RegExp('"', 'g'), '')}\n`, actual.stdout);

	unmock();
});

test('passing through exit code', async t => {
	const unmock = await m('process.exitCode = 1');
	const args = 'foo';

	const actual = shell.exec(`git ${args}`);
	t.is(1, actual.code);

	unmock();
});

test('passing through exit code with multiple mocks', async t => {
	const unmock = [await m('process.exitCode = 1', 'one'), await m('process.exitCode = 2', 'two')];

	t.is(1, shell.exec(`git one`).code);
	t.is(2, shell.exec(`git two`).code);

	unmock[0]();
	unmock[1]();
});
<commit_msg>minor naming<commit_after>import test from 'ava';
import shell from 'shelljs';
import m from './';

shell.config.silent = true;

test('mock and unmock git bla', async t => {
	const log = 'mocking git bla!';
	const unmock = await m(`console.log('${log}')`, 'bla');
	let actual = shell.exec('git bla').stdout;
	t.is(log + '\n', actual);

	actual = shell.exec('git').stdout;
	t.not(log + '\n', actual);

	unmock();
	actual = shell.exec('git bla').stdout;
	t.not(log + '\n', actual);
});

test('mock and unmock git --no-pager bla', async t => {
	const log = 'mocking git bla!';
	const unmock = await m(`console.log('${log}')`, 'bla');
	let actual = shell.exec('git --no-pager bla').stdout;
	t.is(log + '\n', actual);

	actual = shell.exec('git').stdout;
	t.not(log + '\n', actual);

	unmock();
	actual = shell.exec('git --no-pager bla').stdout;
	t.not(log + '\n', actual);
});

test('mocking bar does not affect foo', async t => {
	const fooLog = 'mocking foo!';
	await m(`console.log('${fooLog}')`, 'foo');

	const barLog = 'mocking bar!';
	await m(`console.log('${barLog}')`, 'bar');

	let barActual = shell.exec('git bar').stdout;
	t.is(barLog + '\n', barActual);

	barActual = shell.exec('git --no-pager bar').stdout;
	t.is(barLog + '\n', barActual);

	let fooActual = shell.exec('git foo').stdout;
	t.is(fooLog + '\n', fooActual);

	fooActual = shell.exec('git --no-pager foo').stdout;
	t.is(fooLog + '\n', fooActual);

	const stderr = shell.exec('git log').stderr;
	t.falsy(stderr);
});

test('mocking git', async t => {
	const log = 'mocking git!';
	const unmock = await m(`console.log('${log}')`);

	let actual = shell.exec('git');
	t.is(log + '\n', actual.stdout);
	t.falsy(actual.stderr);

	actual = shell.exec('git foo');
	t.is(log + '\n', actual.stdout);
	t.falsy(actual.stderr);

	actual = shell.exec('git --no-pager log');
	t.is(log + '\n', actual.stdout);
	t.falsy(actual.stderr);

	unmock();
	actual = shell.exec('git');
	t.not(log + '\n', actual.stdout);
	t.falsy(actual.stderr);
});

test('passing arguments while mocking only commit', async t => {
	const unmock = await m(`console.log(process.argv.splice(2).join(' '));`, 'commit');
	const args = 'commit --obviously-invalid-arg -m "second commit with spaces!"';

	const actual = shell.exec(`git ${args}`);
	t.falsy(actual.stderr);
	t.is(`${args.replace(new RegExp('"', 'g'), '')}\n`, actual.stdout);

	unmock();
});

test('passing arguments while mocking whole git', async t => {
	const unmock = await m(`console.log(process.argv.splice(2).join(' '));`);
	const args = 'commit --obviously-invalid-arg -m "third commit with spaces!"';

	const actual = shell.exec(`git ${args}`);
	t.falsy(actual.stderr);
	t.is(`${args.replace(new RegExp('"', 'g'), '')}\n`, actual.stdout);

	unmock();
});

test('passing through exit code', async t => {
	const unmock = await m('process.exitCode = 1');
	const args = 'foo';

	const actual = shell.exec(`git ${args}`).code;
	t.is(1, actual);

	unmock();
});

test('passing through exit code with multiple mocks', async t => {
	const unmock = [await m('process.exitCode = 1', 'one'), await m('process.exitCode = 2', 'two')];

	t.is(1, shell.exec(`git one`).code);
	t.is(2, shell.exec(`git two`).code);

	unmock[0]();
	unmock[1]();
});
<|endoftext|>


<commit_before>'use strict';
var packageDeps = require('./index');
var assert = require('assert');
//var inspect = require('util').inspect;
var is = require('is2');
var _ = require('lodash');

describe('package-deps findAll', function() {
    it('throws with non-string argument', function() {
        var deps;
        try {
            deps = packageDeps.findAll();
        } catch(err) {
            assert.ok(err.message === 'pathToPackageJson argument is not str');
            return;
        }
        throw new Error('findAll unexpectedly worked.');
    });

    it('throws with an empty string argument', function() {
        var deps;
        try {
            deps = packageDeps.findAll();
        } catch(err) {
            assert.ok(err.message === 'pathToPackageJson argument is not str');
            return;
        }
        throw new Error('findAll unexpectedly worked.');
    });

    it('finds all the dependencies with "./"', function() {
        var expected = { dependencies:
            {  async: '0.2.9', debug: '0.7.4', have: '0.2.3', is2: '0.0.11', lodash: '2.4.1' }};

        var deps = packageDeps.findAll('./');
        assert.deepEqual(deps.dependencies, expected.dependencies);
        assert.ok(is.nonEmptyStr(deps.packageJson));
        assert.ok(is.nonEmptyObj(deps.async));
        assert.ok(is.nonEmptyObj(deps.debug));
        assert.ok(is.nonEmptyObj(deps.have));
        assert.ok(is.nonEmptyObj(deps.is2));
        assert.ok(is.nonEmptyObj(deps.lodash));
    });

    it('finds all the dependencies', function() {
        var expected = { dependencies:
            { async: '0.2.9', debug: '0.7.4', have: '0.2.3', is2: '0.0.11', lodash: '2.4.1' }
        };

        var deps = packageDeps.findAll('./package.json');
        assert.deepEqual(deps.dependencies, expected.dependencies);
        assert.ok(is.nonEmptyStr(deps.packageJson));
        assert.ok(is.nonEmptyObj(deps.async));
        assert.ok(is.nonEmptyObj(deps.debug));
        assert.ok(is.nonEmptyObj(deps.have));
        assert.ok(is.nonEmptyObj(deps.is2));
        assert.ok(is.nonEmptyObj(deps.is2.dependencies));
        assert.ok(is.nonEmptyStr(deps.is2.dependencies['deep-is']));
        assert.ok(is.nonEmptyObj(deps.is2['deep-is']));
    });

    it('finds only top-level dependencies, depth=1', function() {
        var expected = { dependencies:
            { async: '0.2.9', debug: '0.7.4', have: '0.2.3', is2: '0.0.11', lodash: '2.4.1' }
        };

        var depth = 1;
        var deps = packageDeps.findAll('./package.json', depth);
        assert.deepEqual(deps.dependencies, expected.dependencies);
        assert.ok(is.nonEmptyStr(deps.packageJson));
        assert.ok(is.nonEmptyObj(deps.async));
        assert.ok(is.nonEmptyObj(deps.debug));
        assert.ok(is.nonEmptyObj(deps.have));
        assert.ok(is.nonEmptyObj(deps.is2));
        assert.ok(_.keys(deps.is2).length === 1);
        assert.ok(is.nonEmptyObj(deps.lodash));
    });

    it('finds all dependencies, depth=2', function() {
        var expected = { dependencies:
            { async: '0.2.9', debug: '0.7.4', have: '0.2.3', is2: '0.0.11', lodash: '2.4.1' }
        };

        var depth = 2;
        var deps = packageDeps.findAll('./package.json', depth);
        assert.deepEqual(deps.dependencies, expected.dependencies);
        assert.ok(is.nonEmptyStr(deps.packageJson));
        assert.ok(is.nonEmptyObj(deps.async));
        assert.ok(is.nonEmptyObj(deps.debug));
        assert.ok(is.nonEmptyObj(deps.have));
        assert.ok(is.nonEmptyObj(deps.is2));
        assert.ok(is.nonEmptyObj(deps.is2.dependencies));
        assert.ok(is.nonEmptyStr(deps.is2.dependencies['deep-is']));
        assert.ok(is.nonEmptyObj(deps.is2['deep-is']));
    });
});

<commit_msg>Added test for depth === 0<commit_after>'use strict';
var packageDeps = require('./index');
var assert = require('assert');
//var inspect = require('util').inspect;
var is = require('is2');
var _ = require('lodash');

describe('package-deps findAll', function() {
    it('throws with non-string argument', function() {
        var deps;
        try {
            deps = packageDeps.findAll();
        } catch(err) {
            assert.ok(err.message === 'pathToPackageJson argument is not str');
            return;
        }
        throw new Error('findAll unexpectedly worked.');
    });

    it('throws with an empty string argument', function() {
        var deps;
        try {
            deps = packageDeps.findAll();
        } catch(err) {
            assert.ok(err.message === 'pathToPackageJson argument is not str');
            return;
        }
        throw new Error('findAll unexpectedly worked.');
    });

    it('finds all the dependencies with "./"', function() {
        var expected = { dependencies:
            {  async: '0.2.9', debug: '0.7.4', have: '0.2.3', is2: '0.0.11', lodash: '2.4.1' }};

        var deps = packageDeps.findAll('./');
        assert.deepEqual(deps.dependencies, expected.dependencies);
        assert.ok(is.nonEmptyStr(deps.packageJson));
        assert.ok(is.nonEmptyObj(deps.async));
        assert.ok(is.nonEmptyObj(deps.debug));
        assert.ok(is.nonEmptyObj(deps.have));
        assert.ok(is.nonEmptyObj(deps.is2));
        assert.ok(is.nonEmptyObj(deps.lodash));
    });

    it('finds all the dependencies', function() {
        var expected = { dependencies:
            { async: '0.2.9', debug: '0.7.4', have: '0.2.3', is2: '0.0.11', lodash: '2.4.1' }
        };

        var deps = packageDeps.findAll('./package.json');
        assert.deepEqual(deps.dependencies, expected.dependencies);
        assert.ok(is.nonEmptyStr(deps.packageJson));
        assert.ok(is.nonEmptyObj(deps.async));
        assert.ok(is.nonEmptyObj(deps.debug));
        assert.ok(is.nonEmptyObj(deps.have));
        assert.ok(is.nonEmptyObj(deps.is2));
        assert.ok(is.nonEmptyObj(deps.is2.dependencies));
        assert.ok(is.nonEmptyStr(deps.is2.dependencies['deep-is']));
        assert.ok(is.nonEmptyObj(deps.is2['deep-is']));
    });

    it('finds only top-level dependencies, depth=0', function() {
        var depth = 0;
        var deps = packageDeps.findAll('./package.json', depth);
        assert.ok(is.nonEmptyObj(deps));
        assert.ok(is.nonEmptyStr(deps.packageJson));
        assert.ok(Object.keys(deps).length === 1);
    });

    it('finds only top-level dependencies, depth=1', function() {
        var expected = { dependencies:
            { async: '0.2.9', debug: '0.7.4', have: '0.2.3', is2: '0.0.11', lodash: '2.4.1' }
        };

        var depth = 1;
        var deps = packageDeps.findAll('./package.json', depth);
        assert.deepEqual(deps.dependencies, expected.dependencies);
        assert.ok(is.nonEmptyStr(deps.packageJson));
        assert.ok(is.nonEmptyObj(deps.async));
        assert.ok(is.nonEmptyObj(deps.debug));
        assert.ok(is.nonEmptyObj(deps.have));
        assert.ok(is.nonEmptyObj(deps.is2));
        assert.ok(_.keys(deps.is2).length === 1);
        assert.ok(is.nonEmptyObj(deps.lodash));
    });

    it('finds all dependencies, depth=2', function() {
        var expected = { dependencies:
            { async: '0.2.9', debug: '0.7.4', have: '0.2.3', is2: '0.0.11', lodash: '2.4.1' }
        };

        var depth = 2;
        var deps = packageDeps.findAll('./package.json', depth);
        assert.deepEqual(deps.dependencies, expected.dependencies);
        assert.ok(is.nonEmptyStr(deps.packageJson));
        assert.ok(is.nonEmptyObj(deps.async));
        assert.ok(is.nonEmptyObj(deps.debug));
        assert.ok(is.nonEmptyObj(deps.have));
        assert.ok(is.nonEmptyObj(deps.is2));
        assert.ok(is.nonEmptyObj(deps.is2.dependencies));
        assert.ok(is.nonEmptyStr(deps.is2.dependencies['deep-is']));
        assert.ok(is.nonEmptyObj(deps.is2['deep-is']));
    });
});

<|endoftext|>


<commit_before>//node_modules/mocha/bin/mocha watch.js tmp/ -w

var jsdom = require("jsdom");
var request = require("request");
var expect = require('chai').expect;

var URL = "http://localhost:8080/index.html";

describe('Todo', function() {
    var self = this;
    var suiteGlobals = { }

    before(function(done) {
        var virtualConsole = jsdom.createVirtualConsole().sendTo(console);
        virtualConsole.on("log", function (message) {
            console.log("console.log called ->", message);
        });

        jsdom.env({
            url: URL,
            resourceLoader: function (resource, callback) {
                //return resource.defaultFetch(callback);
                //using a new request object instead of the jsdom one... errors with ECONRESET otherwise
                request({uri: resource.url.href}, function(error, response, body) {
                    callback(null, body);
                });

            },
            virtualConsole: virtualConsole,
            features: {
                FetchExternalResources: ["script"],
                ProcessExternalResources: ["script"],
                SkipExternalResources: false
            },
            created: function(error, win) {
                //stub to prevent error
                win.scrollTo = function() {};
            },
            done: function (err, win) {
                if (err) { console.log(err) }
                self.window = win;
                global.win = win;
                done();
            },
            agentOptions: { keepAlive: false, keepAliveMsecs: 0 }
            //pool: null
            //proxy: "http://192.168.2.36:8888"
        });
    });

    it('should not log in on bad username/password', function(done) {
        win.document.location.hash = '#/';
        var l = new win.login();
        l.vm.username("admin");
        l.vm.password("BADPASS");
        var controller = new l.controller();
        controller.login().then(function(json) {
            setTimeout(function() {
                expect(l.msg()).to.have.string('invalid');
                expect(win.document.location.hash).to.be.equal('#/');
                done();
            },10);

        });
    });

    it('should log in', function(done) {
        win.document.location.hash = '#/';
        var l = new win.login();
        l.vm.username("admin");
        l.vm.password("admin");
        var controller = new l.controller();
        controller.login().then(function(json) {
            //console.log(win.session.key);
            setTimeout(function() {
                expect(win.document.location.hash).to.be.equal('#/todo');
                done();
            },10);

        });
    });

    it('should fetch todos with session key', function(done) {
        var todo = new win.todo();
        var ctrl = new todo.controller();
        ctrl.refresh().then(function(json) {
            expect(todo.vm.list().length).to.be.above(0);
            done();
        });
    });

    it('adds a todo with session key', function(done) {
        var todo = new win.todo();
        var ctrl = new todo.controller();
        var todoTxt = (Math.random()*1e16).toString();
        todo.vm.description(todoTxt);
        var getNewID = function(json) {
            suiteGlobals.lastTodoID = json.nr;
            suiteGlobals.lastTodoTxt = todoTxt;
            return json
        };
        ctrl.add().then(getNewID).then(ctrl.refresh).then(function() {
            var itemsJSON = JSON.stringify(todo.vm.list());
            expect(itemsJSON).to.have.string(todoTxt);
            done();
        });
    });

    it('deletes a todo', function(done) {
        var todo = new win.todo();
        var ctrl = new todo.controller();
        ctrl.del({nr: suiteGlobals.lastTodoID}).then(ctrl.refresh).then(function(val) {
            var itemsJSON = JSON.stringify(todo.vm.list());
            expect(itemsJSON).to.not.have.string(suiteGlobals.lastTodoTxt);
            done();
        });
    });

});

<commit_msg>fix breaking test changes<commit_after>//node_modules/mocha/bin/mocha watch.js tmp/ -w

var jsdom = require("jsdom");
var request = require("request");
var expect = require('chai').expect;

var URL = "http://localhost:8088/index.html";

describe('Todo', function() {
    var self = this;
    var suiteGlobals = { }

    before(function(done) {
        var virtualConsole = jsdom.createVirtualConsole().sendTo(console);
        virtualConsole.on("log", function (message) {
            console.log("console.log called ->", message);
        });

        jsdom.env({
            url: URL,
            resourceLoader: function (resource, callback) {
                //return resource.defaultFetch(callback);
                //using a new request object instead of the jsdom one... errors with ECONRESET otherwise
                request({uri: resource.url.href}, function(error, response, body) {
                    callback(null, body);
                });

            },
            virtualConsole: virtualConsole,
            features: {
                FetchExternalResources: ["script"],
                ProcessExternalResources: ["script"],
                SkipExternalResources: false
            },
            created: function(error, win) {
                //stub to prevent error
                console.log(error);
                win.scrollTo = function() {};
            },
            done: function (err, win) {
                if (err) { console.log(err) }
                self.window = win;
                global.win = win;
                done();
            },
            agentOptions: { keepAlive: false, keepAliveMsecs: 0 }
            //pool: null
            //proxy: "http://192.168.2.36:8888"
        });
    });

    it('should not log in on bad username/password', function(done) {
        win.document.location.hash = '#/';
        var l = new win.login();
        l.vm.username("admin");
        l.vm.password("BADPASS");
        var controller = new l.controller();
        controller.login().then(function(json) {
            setTimeout(function() {
                expect(l.msg()).to.have.string('invalid');
                expect(win.document.location.hash).to.be.equal('#/');
                done();
            },10);

        });
    });

    it('should log in', function(done) {
        //win.document.location.hash = '#/';
        var l = new win.login();
        l.vm.username("admin");
        l.vm.password("admin");
        var controller = new l.controller();
        controller.login().then(function(json) {
            //console.log(win.session.key);
            setTimeout(function() {
                //expect(win.document.location.hash).to.be.equal('#/todo');
                done();
            },10);

        });
    });

    it('should fetch todos with session key', function(done) {
        var todo = new win.todo();
        var ctrl = new todo.controller();
        ctrl.refresh().then(function(json) {
            expect(todo.vm.list().length).to.be.above(0);
            done();
        });
    });

    it('adds a todo with session key', function(done) {
        var todo = new win.todo();
        var ctrl = new todo.controller();
        var todoTxt = (Math.random()*1e16).toString();
        todo.vm.row.desc(todoTxt);
        var getNewID = function(json) {
            suiteGlobals.lastTodoID = json.nr;
            suiteGlobals.lastTodoTxt = todoTxt;
            return json
        };
        ctrl.add().then(getNewID).then(ctrl.refresh).then(function() {
            var itemsJSON = JSON.stringify(todo.vm.list());
            expect(itemsJSON).to.have.string(todoTxt);
            done();
        });
    });

    it('deletes a todo', function(done) {
        var todo = new win.todo();
        var ctrl = new todo.controller();
        ctrl.del({nr: suiteGlobals.lastTodoID}).then(ctrl.refresh).then(function(val) {
            var itemsJSON = JSON.stringify(todo.vm.list());
            expect(itemsJSON).to.not.have.string(suiteGlobals.lastTodoTxt);
            done();
        });
    });

});

<|endoftext|>


<commit_before>/*
 * LICENCE : CloudUnit is available under the Affero Gnu Public License GPL V3 : https://www.gnu.org/licenses/agpl-3.0.html
 *     but CloudUnit is licensed too under a standard commercial license.
 *     Please contact our sales team if you would like to discuss the specifics of our Enterprise license.
 *     If you are not sure whether the GPL is right for you,
 *     you can always test our software under the GPL and inspect the source code before you contact us
 *     about purchasing a commercial license.
 *
 *     LEGAL TERMS : "CloudUnit" is a registered trademark of Treeptik and can't be used to endorse
 *     or promote products derived from this project without prior written permission from Treeptik.
 *     Products or services derived from this software may not be called "CloudUnit"
 *     nor may "Treeptik" or similar confusing terms appear in their names without prior written permission.
 *     For any questions, contact us : contact@treeptik.fr
 */

(function () {
  'use strict';

  angular
    .module ( 'webuiApp.editApplication' )
    .directive ( 'editAppMonitoringApplication', MonitoringApp );

  function MonitoringApp () {
    return {
      restrict: 'E',
      templateUrl: 'scripts/components/editApplication/monitoring/application/editApplication.monitoring.application.html',
      scope: {
        app: '='
      },
      controller: [
        '$scope',
        'ApplicationService',
        '$stateParams',
        'MonitoringService',
        '$interval',
        MonitoringAppCtrl
      ],
      controllerAs: 'monitoringApp',
      bindToController: true
    };
  }

  function MonitoringAppCtrl ( $scope, ApplicationService, $stateParams, MonitoringService, $interval ) {

    // ------------------------------------------------------------------------
    // MONITORING
    // ------------------------------------------------------------------------

    var vm = this;
    vm.cleanFirstValue = true;
    vm.queueName = '';
    vm.queueStats = {};
    vm.selectedQueueStats = {};
    vm.displayGraph = [];
    vm.queueNameTab = [];
    vm.timer = {};

    vm.loadStats = loadStats;
    vm.deleteGraph = deleteGraph;
    vm.chooseQueue = chooseQueue;

    var lastQueueNameSelected = '';

    $scope.$on ( '$destroy', function () {
      $interval.cancel(vm.timer);
      vm.timer = null;
    } );

    function referenceQueue(queueName) {
      if(!vm.queueNameTab.includes(queueName)) {
         vm.queueNameTab.push(queueName);
      }
      lastQueueNameSelected = queueName;
    }

    function chooseQueue(queueName) {
      vm.cleanFirstValue = true;
      MonitoringService.chooseQueue(vm.app.location, queueName)
        .then(success)
        .catch(error);

      function success(response) {
        vm.queueStats = response.value;

        // clean
        referenceQueue(vm.queueName);
        vm.errorMsg = '';
        vm.queueName = '';
        vm.selectedQueueStats = {};

        vm.timer = $interval ( function () {
          angular.forEach(vm.queueNameTab, function(queueName, key) {
            MonitoringService.chooseQueue(vm.app.location, queueName)
            .then(function(response) {
              angular.forEach(vm.displayGraph, function(value, key) {

                if(value.location == lastQueueNameSelected && vm.cleanFirstValue) {
                  vm.selectedQueueStats[value.id] = true;
                  vm.displayGraph[key].data.shift();
                }
                if(vm.displayGraph[key].location == queueName) {
                  vm.displayGraph[key].data.push(
                    {
                      "date":new Date(response.timestamp*1000),
                      "value":response.value[value.id]
                    }
                  );
                }
              });
              vm.cleanFirstValue = false;
            })
          });
        }, 1000 )
        vm.queueStatsPoll = MonitoringService.queueStats;
      }

      function error(response) {
        vm.errorMsg = response.data.message;
        return vm.errorMsg;
      }
    }

    function cleanAll() {
      vm.cleanFirstValue = true;
      angular.forEach(vm.displayGraph , function(value, index) {
        //delete all element already selected for the current queue
        vm.displayGraph[index].data = [{'date': new Date(), 'value': 0}];
      });

      vm.displayGraph = vm.displayGraph.filter(
        function(x) {
          return lastQueueNameSelected != x.location;
        }
      );
    }

    function loadStats(selectedQueueStats) {

      cleanAll();

      setTimeout(function() {
        angular.forEach(selectedQueueStats, function(isQueueSelected, key) {
          if(isQueueSelected) {
            vm.displayGraph.push({
              data: [{'date': new Date(), 'value': 0}],
              title: lastQueueNameSelected + " " + key,
              id: key,
              location: lastQueueNameSelected,
              description: lastQueueNameSelected,
              x_accessor:'date',
              y_accessor:'value',
              area: false
            });
          }
        });
      }, 0);

    }

   //TODO delete le celui de la bonne queue car l'heure actuelle supprime le premier qu'il trouve
   function deleteGraph(queueStatsName, queueLocation) {

     vm.displayGraph.splice(vm.displayGraph[
       vm.displayGraph.map(function(x) {return x.id; }).indexOf(queueStatsName)
     ], 1);
   }

  }
}) ();

<commit_msg>Update keep last value only<commit_after>/*
 * LICENCE : CloudUnit is available under the Affero Gnu Public License GPL V3 : https://www.gnu.org/licenses/agpl-3.0.html
 *     but CloudUnit is licensed too under a standard commercial license.
 *     Please contact our sales team if you would like to discuss the specifics of our Enterprise license.
 *     If you are not sure whether the GPL is right for you,
 *     you can always test our software under the GPL and inspect the source code before you contact us
 *     about purchasing a commercial license.
 *
 *     LEGAL TERMS : "CloudUnit" is a registered trademark of Treeptik and can't be used to endorse
 *     or promote products derived from this project without prior written permission from Treeptik.
 *     Products or services derived from this software may not be called "CloudUnit"
 *     nor may "Treeptik" or similar confusing terms appear in their names without prior written permission.
 *     For any questions, contact us : contact@treeptik.fr
 */

(function () {
  'use strict';

  angular
    .module ( 'webuiApp.editApplication' )
    .directive ( 'editAppMonitoringApplication', MonitoringApp );

  function MonitoringApp () {
    return {
      restrict: 'E',
      templateUrl: 'scripts/components/editApplication/monitoring/application/editApplication.monitoring.application.html',
      scope: {
        app: '='
      },
      controller: [
        '$scope',
        'ApplicationService',
        '$stateParams',
        'MonitoringService',
        '$interval',
        MonitoringAppCtrl
      ],
      controllerAs: 'monitoringApp',
      bindToController: true
    };
  }

  function MonitoringAppCtrl ( $scope, ApplicationService, $stateParams, MonitoringService, $interval ) {

    // ------------------------------------------------------------------------
    // MONITORING
    // ------------------------------------------------------------------------

    var vm = this;
    vm.cleanFirstValue = true;
    vm.queueName = '';
    vm.queueStats = {};
    vm.selectedQueueStats = {};
    vm.displayGraph = [];
    vm.queueNameTab = [];
    vm.timer = {};
    var test = 60;

    vm.loadStats = loadStats;
    vm.deleteGraph = deleteGraph;
    vm.chooseQueue = chooseQueue;

    var lastQueueNameSelected = '';

    $scope.$on ( '$destroy', function () {
      $interval.cancel(vm.timer);
      vm.timer = null;
    } );

    function referenceQueue(queueName) {
      if(!vm.queueNameTab.includes(queueName)) {
         vm.queueNameTab.push(queueName);
      }
      lastQueueNameSelected = queueName;
    }

    function chooseQueue(queueName) {
      vm.cleanFirstValue = true;
      MonitoringService.chooseQueue(vm.app.location, queueName)
        .then(success)
        .catch(error);

      function success(response) {
        vm.queueStats = response.value;

        // clean
        referenceQueue(vm.queueName);
        vm.errorMsg = '';
        vm.queueName = '';
        refreshSelectedQueueStats();

        vm.timer = $interval ( function () {
          angular.forEach(vm.queueNameTab, function(queueName, key) {
            MonitoringService.chooseQueue(vm.app.location, queueName)
            .then(function(response) {
              angular.forEach(vm.displayGraph, function(value, key) {

                if(value.location == lastQueueNameSelected && vm.cleanFirstValue) {
                  vm.selectedQueueStats[value.id] = true;
                  vm.displayGraph[key].data.shift();
                }
                if(vm.displayGraph[key].location == queueName) {

                  vm.displayGraph[key].data.push(
                    {
                      "date":new Date(response.timestamp*1000),
                      "value":response.value[value.id]
                    }
                  );

                  if(vm.displayGraph[key].data.length >= test) {
                    vm.displayGraph[key].data.splice(0, 1);
                  }
                }
              });
              vm.cleanFirstValue = false;
            })
          });
        }, 1000 )
        vm.queueStatsPoll = MonitoringService.queueStats;
      }

      function error(response) {
        vm.errorMsg = response.data.message;
        return vm.errorMsg;
      }
    }

    function cleanAll() {
      vm.cleanFirstValue = true;
      angular.forEach(vm.displayGraph , function(value, index) {
        //delete all element already selected for the current queue
        vm.displayGraph[index].data = [{'date': new Date(), 'value': 0}];
      });

      vm.displayGraph = vm.displayGraph.filter(
        function(x) {
          return lastQueueNameSelected != x.location;
        }
      );
    }

    function loadStats(selectedQueueStats) {

      cleanAll();

      setTimeout(function() {
        angular.forEach(selectedQueueStats, function(isQueueSelected, key) {
          if(isQueueSelected) {
            vm.displayGraph.push({
              data: [{'date': new Date(), 'value': 0}],
              title: lastQueueNameSelected + " " + key,
              id: key,
              location: lastQueueNameSelected,
              description: lastQueueNameSelected,
              x_accessor:'date',
              y_accessor:'value',
              area: false
            });
          }
        });
      }, 0);

    }

   function refreshSelectedQueueStats() {
      vm.selectedQueueStats = {};
      var res = vm.displayGraph.filter(
        function(x) {
          return lastQueueNameSelected == x.location;
        }
      );

      angular.forEach(res, function(graph, index) {
        console.log(graph.id);
        vm.selectedQueueStats[graph.id] = true;
      });
   }

   function deleteGraph(queueStatsName, queueLocation) {
     angular.forEach(vm.displayGraph, function(graph, index) {
       if(graph.id == queueStatsName && graph.location == queueLocation) {
        vm.displayGraph.splice(index, 1);
       }
     });
     refreshSelectedQueueStats();
   }

  }
}) ();

<|endoftext|>