<commit_before>'use strict';

describe('card game', function () {
  beforeEach(function () {
    this.cards = [{
      suit: '♥',
      rank: '4'
    }, {
      suit: '♥',
      rank: '3'
    }, {
      suit: '♠',
      rank: '2'
    }, {
      suit: '♠',
      rank: 'A'
    }, {
      suit: '♦',
      rank: '8'
    }, {
      suit: '♦',
      rank: '9'
    }, {
      suit: '♦',
      rank: '4'
    }, {
      suit: '♦',
      rank: '5'
    }, {
      suit: '♣',
      rank: 'K'
    }, {
      suit: '♣',
      rank: '10'
    }, {
      suit: '♣',
      rank: 'J'
    }, {
      suit: '♣',
      rank: 'Q'
    }];
  });

  describe('function: shuffle', function () {
    beforeEach(function () {
      this.result = shuffle(this.cards);
    });
    it('returns cards in a different order', function () {
      expect(this.result).not.toEqual(this.cards);
    });
    it('returns a different order each time', function () {
      expect(this.result).not.toEqual(shuffle(this.cards));
    });
    it('returns the same number as given', function () {
      expect(this.result.count).toBe(this.cards.length);
    });
    it('includes all the cards', function () {
      this.cards.forEach(function (card) {
        expect(this.result).toContain(card);
      });
    });
  });

  describe('function: sortAscending', function () {
    beforeEach(function () {
      this.result = sortAscending(this.cards);
    });
    it('returns cards grouped by suits ♠, ♣, ♥ then ♦', function () {});
    it('returns the rank numbers in order', function () {});
    it('returns rank ace before two', function () {});
    it('returns cards for a rank by 10, jack, king then queen', function () {});
    it('returns cards in same order even after shuffling', function () {})
  });
});
<commit_msg>fleshed out sortAscending tests, refactor<commit_after>'use strict';

describe('card game', function () {
  beforeEach(function () {
    this.cards = [{
      suit: '♠',
      rank: '2'
    }, {
      suit: '♠',
      rank: 'A'
    }, {
      suit: '♦',
      rank: '8'
    }, {
      suit: '♦',
      rank: '9'
    }, {
      suit: '♦',
      rank: '4'
    }, {
      suit: '♦',
      rank: '5'
    }, {
      suit: '♣',
      rank: 'K'
    }, {
      suit: '♣',
      rank: '10'
    }, {
      suit: '♣',
      rank: 'J'
    }, {
      suit: '♣',
      rank: 'Q'
    }];
  });

  describe('function: shuffle', function () {
    beforeEach(function () {
      this.result = shuffle(this.cards);
    });

    it('returns cards in a different order', function () {
      expect(this.result).not.toEqual(this.cards);
    });

    it('returns a different order each time', function () {
      expect(this.result).not.toEqual(shuffle(this.cards));
    });

    it('returns the same number as given', function () {
      expect(this.result.count).toBe(this.cards.length);
    });

    it('includes all the cards', function () {
      this.cards.forEach(function (card) {
        expect(this.result).toContain(card);
      });
    });
  });

  describe('function: sortAscending', function () {
    beforeEach(function () {
      this.result = sortAscending(this.cards);
    });

    it('returns cards grouped by suits ♠, ♣, ♥ then ♦', function () {
      expect(getSuitsInOrderTheyAppear(this.result)).toEqual(['♠', '♣', '♥', '♦']);
    });

    it('returns the rank numbers in order', function () {
      expect(getRanksFilterBySuit(this.result, '♦')).toEqual(['4', '5', '6', '9']);
    });

    it('returns rank ace before two', function () {
      expect(getRanksFilterBySuit(this.result, '♠')).toEqual(['A', '2']);
    });

    it('returns cards for a rank by 10, jack, king then queen', function () {
      expect(getRanksFilterBySuit(this.result, '♣')).toEqual(['10', 'J', 'Q', 'K']);
    });

    it('returns cards in same order even after shuffling', function () {
      expect(this.result).toEqual(shuffle(this.result));
    });

    it('returns the same number as given', function () {
      expect(this.result.count).toBe(this.cards.length);
    });

    it('includes all the cards', function () {
      this.cards.forEach(function (card) {
        expect(this.result).toContain(card);
      });
    });

    function getRanksFilterBySuit(cards, suit) {
      return cards.filter(function (card) {
        return card.suit === suit;
      }).map(function (card) {
        return card.suit;
      });
    }

    function getSuitsInOrderTheyAppear(cards) {
      var suits = [];
      for (var i in result) {
        if (result[i - 1].suit !== result[i].suit) {
          suits.push(result[i].suit);
        }
      }
      return suits;
    }
  });
});
<|endoftext|>


<commit_before>const fs = require('fs');

var solc = require('solc');

fs.readdirSync('./').forEach(item => {
  if( '.sol' == item.substr(item.length - 4)) {
    console.log(item);
    code = fs.readFileSync(item,'utf8');
    var output = solc.compile(code, 1);
    if (output.errors) {
      console.log(output.errors);
      console.log("Build failed.")
      process.exit(1);
    }
  }
});

console.log("Build succeeded.")
<commit_msg>Remove unused test.js file<commit_after><|endoftext|>


<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.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) {
    console.log (util.inspect (err||data, {depth:10, colors:true}));
    doTest (err, 'getStats iface', [
      ['data type', typeof data === 'object'],
      ['id', data.id === app.set.config.Interface],
      ['traffic.days type', data.traffic.days && data.traffic.days instanceof Array],
      ['traffic.days item', data.traffic.days && 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.days && data.traffic.days instanceof Array],
      ['traffic.days item', data.traffic.days && 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 data'],
      ['details', !!~err.details.indexOf ('Unable to read database')]
    ]);
  });
});

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

// Setup
// $ NODE_APP_IFACE=eth0 npm test
var app = require ('./') ();

// 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 (process.env.NODE_APP_IFACE || 'eth0', function (err, data) {
    doTest (err, 'getStats iface', [
      ['data type', typeof data === 'object'],
      ['id', typeof data.id === 'string'],
      ['days type', data.traffic.days && data.traffic.days instanceof Array],
      ['days item', data.traffic.days && typeof data.traffic.days [0] .rx === 'number']
    ]);
  });
});

queue.push (function () {
  app.getStats (function (err, data) {
    doTest (err, 'getStats all', [
      ['data type', typeof data === 'object' && data instanceof Array]
    ]);
  });
});

queue.push (function () {
  app.getStats ('unreal-iface', function (err) {
    doTest (null, 'getStats error', [
      ['type', err instanceof Error],
      ['message', err.message === 'invalid interface']
    ]);
  });
});

// Start the tests
console.log ('Running tests...\n');
queue [0] ();
<|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-6-13 20:43:48<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 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-17 11:10:28<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';
var test = require('tape');
var childProcess = require('child_process');
var logSymbols = require('log-symbols');

test('Testing output', function (t) {
	t.plan(1);
	childProcess.execFile('./cli.js', ['www.google.com'], {cwd: __dirname}, function (err, stdout) {
		t.equal(stdout, logSymbols.success + ' Reachable');
	});
});
<commit_msg>added test<commit_after>'use strict';
var test = require('tape');
var childProcess = require('child_process');
test('Testing output', function (t) {
	t.plan(2);
	childProcess.execFile('./cli.js', ['www.google.com'], {cwd: __dirname}, function (err, stdout) {
		if (err) {
			t.end();
		}
		t.equal("✔ Reachable\n", stdout, "Both strings are equal");
	});
	childProcess.execFile('./cli.js', ['randowmtext'], {cwd: __dirname}, function (err, stdout) {
		if (err) {
			t.end();
		}
		t.equal("✖ Not Reachable\n", stdout, "Both strings are equal");
	});
});
<|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-6-13 18:38:41<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>/*
Name:           planetos - test.js
Source & docs:  https://github.com/fvdm/nodejs-planetos
Feedback:       https://github.com/fvdm/nodejs-planetos/issues
License:        Unlicense (public domain)
*/

var path = require ('path');
var dir = path.dirname (module.filename);

var pkg = require (path.join (dir, 'package.json'));
var app = require (path.join (dir));

var planetos;
var errors = 0;
var warnings = 0;
var queue = [];
var next = -1;

// Setup
// set env PLANETOS_APIKEY  (CI tests)
var config = {
  apikey: process.env.PLANETOS_APIKEY || null,
  endpoint: process.env.PLANETOS_ENDPOINT || null,
  timeout: process.env.PLANETOS_TIMEOUT || 5000
};

if (!config.apikey) {
  config.endpoint = 'https://frankl.in/u/ci_test.php?a=planetos&b=';
}

planetos = app (config);

/**
 * ANSI colorize a string
 *
 * @param color {String} - The color to add
 * @param str {String} - The string to alter
 * @returns {String}
 */

function colorStr (color, str) {
  var colors = {
    red: '\u001b[31m',
    green: '\u001b[32m',
    yellow: '\u001b[33m',
    blue: '\u001b[34m',
    magenta: '\u001b[35m',
    cyan: '\u001b[36m',
    gray: '\u001b[37m',
    bold: '\u001b[1m',
    plain: '\u001b[0m'
  };

  return colors [color] + str + colors.plain;
}

/**
 * console.log with style
 *
 * @param [type] {String=plain} - Formatting style
 * @param str {String} - The string to alter
 * @returns {void}
 */

function log (type, str) {
  var types = {
    fail: ['red', 'FAIL'],
    good: ['green', 'good'],
    warn: ['yellow', 'warn'],
    info: ['cyan', 'info']
  };

  if (!str) {
    str = type;
    type = 'plain';
  }

  switch (type) {
    case 'error': console.log (colorStr ('red', colorStr ('bold', 'ERROR   ')) + str + '\n'); break;
    case 'note': console.log (colorStr ('bold', str)); break;
    case 'plain': console.log (str); break;
    default:
      console.log (colorStr (types[type][0], types[type][1]) + '    ' + str);
      break;
  }
}

/**
 * Detect and wrap string type
 *
 * @param str {String} - The string
 * @returns {String}
 */

function typeStr (str) {
  if (typeof str === 'string') {
    str = '"' + str + '"';
  } else if (str instanceof Object) {
    str = 'Object';
  } else if (str instanceof Array) {
    str = 'Array';
  } else if (str instanceof Error) {
    str = 'Error';
  }

  return colorStr ('magenta', str);
}

// handle exits
process.on ('exit', function processExit () {
  console.log ();
  log ('info', errors + ' errors');
  log ('info', warnings + ' warnings');
  console.log ();

  if (errors) {
    process.exit (1);
  } else {
    process.exit (0);
  }
});

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

/**
 * Queue to prevent flooding
 *
 * @returns {void}
 */

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

/**
 * doTest checks for error
 * else runs specified tests
 *
 * @param {Error} err
 * @param {String} label
 * @param {Array} tests
 * @returns {void}
 *
 * doTest(err, 'label text', [
 *   ['fail', 'feeds', typeof feeds, 'object'],
 *   ['warn', 'music', music instanceof Array, true],
 *   ['info', 'tracks', music.length]
 * ]);
 */

function doTest (err, label, tests) {
  var level = 'good';
  var test;
  var i;

  if (err instanceof Error) {
    log ('error', label);
    console.dir (err, { depth: null, colors: true });
    console.log ();
    console.log (err.stack);
    console.log ();
    errors++;

    doNext ();
    return;
  }

  log ('note', colorStr ('blue', '(' + (next + 1) + '/' + queue.length + ') ') + label);

  for (i = 0; i < tests.length; i++) {
    test = {
      level: tests [i] [0],
      label: tests [i] [1],
      result: tests [i] [2],
      expect: tests [i] [3]
    };

    if (test.result === test.expect) {
      log ('good', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is exactly ' + typeStr (test.expect));
    }

    if (test.level === 'fail' && test.result !== test.expect) {
      errors++;
      level = 'fail';
      log ('fail', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is not ' + typeStr (test.expect));
    }

    if (test.level === 'warn' && test.result !== test.expect) {
      warnings++;
      level = level !== 'fail' && 'warn';
      log ('warn', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is not ' + typeStr (test.expect));
    }

    if (test.level === 'info') {
      log ('info', colorStr ('blue', test.label) + ': ' + typeStr (test.result));
    }
  }

  doNext ();
}

// module basics
queue.push (function () {
  doTest (null, 'Module', [
    ['fail', 'exports', typeof app, 'function'],
    ['fail', 'interface', typeof planetos, 'function']
  ]);
});

// method
queue.push (function () {
  var params = {
    lon: -50.5,
    lat: 49.5,
    count: 1,
    context: 'reftime_time_lat_lon'
  };

  planetos ('noaa_ww3_global_1.25x1d', params, function (err, data) {
    doTest (err, 'NOAA example', [
      ['fail', 'type', data instanceof Object, true],
      ['warn', '.stats', data && data.stats instanceof Object, true],
      ['warn', '.entries', data && data.entries instanceof Array, true],
      ['info', 'Pressure_surface',
        try {
          return data.entries[0].data.Pressure_surface;
        } catch (e) {
          return e;
        }
      ]
    ]);
  });
});

// Start the tests
log ('note', 'Running tests...\n');
log ('note', 'API endpoint:  ' + config.endpoint;
log ('note', 'Node.js:       ' + process.versions.node);
log ('note', 'Module:        ' + pkg.version);

doNext ();
<commit_msg>Test: minor code style fix<commit_after>/*
Name:           planetos - test.js
Source & docs:  https://github.com/fvdm/nodejs-planetos
Feedback:       https://github.com/fvdm/nodejs-planetos/issues
License:        Unlicense (public domain)
*/

var path = require ('path');
var dir = path.dirname (module.filename);

var pkg = require (path.join (dir, 'package.json'));
var app = require (path.join (dir));

var planetos;
var errors = 0;
var warnings = 0;
var queue = [];
var next = -1;

// Setup
// set env PLANETOS_APIKEY  (CI tests)
var config = {
  apikey: process.env.PLANETOS_APIKEY || null,
  endpoint: process.env.PLANETOS_ENDPOINT || null,
  timeout: process.env.PLANETOS_TIMEOUT || 5000
};

if (!config.apikey) {
  config.endpoint = 'https://frankl.in/u/ci_test.php?a=planetos&b=';
}

planetos = app (config);

/**
 * ANSI colorize a string
 *
 * @param color {String} - The color to add
 * @param str {String} - The string to alter
 * @returns {String}
 */

function colorStr (color, str) {
  var colors = {
    red: '\u001b[31m',
    green: '\u001b[32m',
    yellow: '\u001b[33m',
    blue: '\u001b[34m',
    magenta: '\u001b[35m',
    cyan: '\u001b[36m',
    gray: '\u001b[37m',
    bold: '\u001b[1m',
    plain: '\u001b[0m'
  };

  return colors [color] + str + colors.plain;
}

/**
 * console.log with style
 *
 * @param [type] {String=plain} - Formatting style
 * @param str {String} - The string to alter
 * @returns {void}
 */

function log (type, str) {
  var types = {
    fail: ['red', 'FAIL'],
    good: ['green', 'good'],
    warn: ['yellow', 'warn'],
    info: ['cyan', 'info']
  };

  if (!str) {
    str = type;
    type = 'plain';
  }

  switch (type) {
    case 'error': console.log (colorStr ('red', colorStr ('bold', 'ERROR   ')) + str + '\n'); break;
    case 'note': console.log (colorStr ('bold', str)); break;
    case 'plain': console.log (str); break;
    default:
      console.log (colorStr (types[type][0], types[type][1]) + '    ' + str);
      break;
  }
}

/**
 * Detect and wrap string type
 *
 * @param str {String} - The string
 * @returns {String}
 */

function typeStr (str) {
  if (typeof str === 'string') {
    str = '"' + str + '"';
  } else if (str instanceof Object) {
    str = 'Object';
  } else if (str instanceof Array) {
    str = 'Array';
  } else if (str instanceof Error) {
    str = 'Error';
  }

  return colorStr ('magenta', str);
}

// handle exits
process.on ('exit', function processExit () {
  console.log ();
  log ('info', errors + ' errors');
  log ('info', warnings + ' warnings');
  console.log ();

  if (errors) {
    process.exit (1);
  } else {
    process.exit (0);
  }
});

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

/**
 * Queue to prevent flooding
 *
 * @returns {void}
 */

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

/**
 * doTest checks for error
 * else runs specified tests
 *
 * @param {Error} err
 * @param {String} label
 * @param {Array} tests
 * @returns {void}
 *
 * doTest(err, 'label text', [
 *   ['fail', 'feeds', typeof feeds, 'object'],
 *   ['warn', 'music', music instanceof Array, true],
 *   ['info', 'tracks', music.length]
 * ]);
 */

function doTest (err, label, tests) {
  var level = 'good';
  var test;
  var i;

  if (err instanceof Error) {
    log ('error', label);
    console.dir (err, { depth: null, colors: true });
    console.log ();
    console.log (err.stack);
    console.log ();
    errors++;

    doNext ();
    return;
  }

  log ('note', colorStr ('blue', '(' + (next + 1) + '/' + queue.length + ') ') + label);

  for (i = 0; i < tests.length; i++) {
    test = {
      level: tests [i] [0],
      label: tests [i] [1],
      result: tests [i] [2],
      expect: tests [i] [3]
    };

    if (test.result === test.expect) {
      log ('good', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is exactly ' + typeStr (test.expect));
    }

    if (test.level === 'fail' && test.result !== test.expect) {
      errors++;
      level = 'fail';
      log ('fail', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is not ' + typeStr (test.expect));
    }

    if (test.level === 'warn' && test.result !== test.expect) {
      warnings++;
      level = level !== 'fail' && 'warn';
      log ('warn', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is not ' + typeStr (test.expect));
    }

    if (test.level === 'info') {
      log ('info', colorStr ('blue', test.label) + ': ' + typeStr (test.result));
    }
  }

  doNext ();
}

// module basics
queue.push (function () {
  doTest (null, 'Module', [
    ['fail', 'exports', typeof app, 'function'],
    ['fail', 'interface', typeof planetos, 'function']
  ]);
});

// method
queue.push (function () {
  var params = {
    lon: -50.5,
    lat: 49.5,
    count: 1,
    context: 'reftime_time_lat_lon'
  };

  planetos ('noaa_ww3_global_1.25x1d', params, function (err, data) {
    doTest (err, 'NOAA example', [
      ['fail', 'type', data instanceof Object, true],
      ['warn', '.stats', data && data.stats instanceof Object, true],
      ['warn', '.entries', data && data.entries instanceof Array, true],
      ['info', 'Pressure_surface',
        try {
          return data.entries [0].data.Pressure_surface;
        } catch (e) {
          return e;
        }
      ]
    ]);
  });
});

// Start the tests
log ('note', 'Running tests...\n');
log ('note', 'API endpoint:  ' + config.endpoint;
log ('note', 'Node.js:       ' + process.versions.node);
log ('note', 'Module:        ' + pkg.version);

doNext ();
<|endoftext|>


<commit_before>import test from 'ava';
import fn from './';

test('camelCase', t => {
	t.is(fn('foo'), 'Foo');
	t.is(fn('foo-bar'), 'FooBar');
	t.is(fn('foo-bar-baz'), 'FooBarBaz');
	t.is(fn('foo--bar'), 'FooBar');
	t.is(fn('--foo-bar'), 'FooBar');
	t.is(fn('--foo--bar'), 'FooBar');
	t.is(fn('FOO-BAR'), 'FooBar');
	t.is(fn('-foo-bar-'), 'FooBar');
	t.is(fn('--foo--bar--'), 'FooBar');
	t.is(fn('foo.bar'), 'FooBar');
	t.is(fn('foo..bar'), 'FooBar');
	t.is(fn('..foo..bar..'), 'FooBar');
	t.is(fn('foo_bar'), 'FooBar');
	t.is(fn('__foo__bar__'), 'FooBar');
	t.is(fn('__foo__bar__'), 'FooBar');
	t.is(fn('foo bar'), 'FooBar');
	t.is(fn('  foo  bar  '), 'FooBar');
	t.is(fn('-'), '-');
	t.is(fn(' - '), '-');
	t.is(fn('fooBar'), 'FooBar');
	t.is(fn('fooBar-baz'), 'FoobarBaz');
	t.is(fn('F'), 'F');
	t.is(fn('Foo'), 'Foo');
	t.is(fn('FOO'), 'Foo');
	t.is(fn('foo', 'bar'), 'FooBar');
	t.is(fn('foo', '-bar'), 'FooBar');
	t.is(fn('foo', '-bar', 'baz'), 'FooBarBaz');
	t.is(fn('', ''), '');
	t.is(fn('--'), '');
	t.is(fn(''), '');
	t.is(fn('--__--_--_'), '');
	t.is(fn('---_', '--', '', '-_- '), '');
	t.end();
});
<commit_msg>Fix typo in test<commit_after>import test from 'ava';
import fn from './';

test('UpperCamelCase', t => {
	t.is(fn('foo'), 'Foo');
	t.is(fn('foo-bar'), 'FooBar');
	t.is(fn('foo-bar-baz'), 'FooBarBaz');
	t.is(fn('foo--bar'), 'FooBar');
	t.is(fn('--foo-bar'), 'FooBar');
	t.is(fn('--foo--bar'), 'FooBar');
	t.is(fn('FOO-BAR'), 'FooBar');
	t.is(fn('-foo-bar-'), 'FooBar');
	t.is(fn('--foo--bar--'), 'FooBar');
	t.is(fn('foo.bar'), 'FooBar');
	t.is(fn('foo..bar'), 'FooBar');
	t.is(fn('..foo..bar..'), 'FooBar');
	t.is(fn('foo_bar'), 'FooBar');
	t.is(fn('__foo__bar__'), 'FooBar');
	t.is(fn('__foo__bar__'), 'FooBar');
	t.is(fn('foo bar'), 'FooBar');
	t.is(fn('  foo  bar  '), 'FooBar');
	t.is(fn('-'), '-');
	t.is(fn(' - '), '-');
	t.is(fn('fooBar'), 'FooBar');
	t.is(fn('fooBar-baz'), 'FoobarBaz');
	t.is(fn('F'), 'F');
	t.is(fn('Foo'), 'Foo');
	t.is(fn('FOO'), 'Foo');
	t.is(fn('foo', 'bar'), 'FooBar');
	t.is(fn('foo', '-bar'), 'FooBar');
	t.is(fn('foo', '-bar', 'baz'), 'FooBarBaz');
	t.is(fn('', ''), '');
	t.is(fn('--'), '');
	t.is(fn(''), '');
	t.is(fn('--__--_--_'), '');
	t.is(fn('---_', '--', '', '-_- '), '');
	t.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>🤖(break): 2017-7-20 10:14:52<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';
var test = require('ava');
var tempfile = require('tempfile');
var readPkg = require('read-pkg');
var fn = require('./');
var fixture = {foo: true};

test('async', function (t) {
	var tmp = tempfile();
	return fn(tmp, fixture).then(function () {
		var x = readPkg.sync(tmp);
		t.true(x.foo);
	});
});

test('sync', function (t) {
	var tmp = tempfile();
	fn.sync(tmp, fixture);
	var x = readPkg.sync(tmp);
	t.true(x.foo);
	t.end();
});
<commit_msg>update tests for latest AVA version<commit_after>'use strict';
var test = require('ava');
var tempfile = require('tempfile');
var readPkg = require('read-pkg');
var fn = require('./');
var fixture = {foo: true};

test('async', function (t) {
	var tmp = tempfile();
	return fn(tmp, fixture).then(function () {
		var x = readPkg.sync(tmp);
		t.true(x.foo);
	});
});

test('sync', function (t) {
	var tmp = tempfile();
	fn.sync(tmp, fixture);
	var x = readPkg.sync(tmp);
	t.true(x.foo);
});
<|endoftext|>


<commit_before>var test = require('tap').test
var fss = require('./')
var clone = require('clone')
var s = JSON.stringify

test('circular reference to root', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.circle = fixture
  var expected = s(
    {name: 'Tywin Lannister', circle: '[Circular]'}
  )
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular reference to root', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.id = {circle: fixture}
  var expected = s(
    {name: 'Tywin Lannister', id: {circle: '[Circular]'}}
  )
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('child circular reference', function (assert) {
  var fixture = {name: 'Tywin Lannister', child: {name: 'Tyrion Lannister'}}
  fixture.child.dinklage = fixture.child
  var expected = s({
    name: 'Tywin Lannister',
    child: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested child circular reference', function (assert) {
  var fixture = {name: 'Tywin Lannister', child: {name: 'Tyrion Lannister'}}
  fixture.child.actor = {dinklage: fixture.child}
  var expected = s({
    name: 'Tywin Lannister',
    child: {
      name: 'Tyrion Lannister', actor: {dinklage: '[Circular]'}
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('circular objects in an array', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.hand = [fixture, fixture]
  var expected = s({
    name: 'Tywin Lannister', hand: ['[Circular]', '[Circular]']
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular references in an array', function (assert) {
  var fixture = {
    name: 'Tywin Lannister',
    offspring: [{name: 'Tyrion Lannister'}, {name: 'Cersei Lannister'}]
  }
  fixture.offspring[0].dinklage = fixture.offspring[0]
  fixture.offspring[1].headey = fixture.offspring[1]

  var expected = s({
    name: 'Tywin Lannister',
    offspring: [
      {name: 'Tyrion Lannister', dinklage: '[Circular]'},
      {name: 'Cersei Lannister', headey: '[Circular]'}
    ]
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('circular arrays', function (assert) {
  var fixture = []
  fixture.push(fixture, fixture)
  var expected = s(['[Circular]', '[Circular]'])
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular arrays', function (assert) {
  var fixture = []
  fixture.push(
    {name: 'Jon Snow', bastards: fixture},
    {name: 'Ramsay Bolton', bastards: fixture}
  )
  var expected = s([
    {name: 'Jon Snow', bastards: '[Circular]'},
    {name: 'Ramsay Bolton', bastards: '[Circular]'}
  ])
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('repeated non-circular references in objects', function (assert) {
  var daenerys = {name: 'Daenerys Targaryen'}
  var fixture = {
    motherOfDragons: daenerys,
    queenOfMeereen: daenerys
  }
  var expected = s(fixture)
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('repeated non-circular references in arrays', function (assert) {
  var daenerys = {name: 'Daenerys Targaryen'}
  var fixture = [daenerys, daenerys]
  var expected = s(fixture)
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('double child circular reference', function (assert) {
  // create circular reference
  var child = {name: 'Tyrion Lannister'}
  child.dinklage = child

  // include it twice in the fixture
  var fixture = {name: 'Tywin Lannister', childA: child, childB: child}
  var cloned = clone(fixture)
  var expected = s({
    name: 'Tywin Lannister',
    childA: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    },
    childB: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)

  // check if the fixture has not been modified
  assert.deepEqual(fixture, cloned)
  assert.end()
})

test('child circular reference with toJSON', function (assert) {
  // Create a test object that has an overriden `toJSON` property
  TestObject.prototype.toJSON = function () { return { special: 'case' } }
  function TestObject (content) {}

  // Creating a simple circular object structure
  const parentObject = {}
  parentObject.childObject = new TestObject()
  parentObject.childObject.parentObject = parentObject

  // Creating a simple circular object structure
  const otherParentObject = new TestObject()
  otherParentObject.otherChildObject = {}
  otherParentObject.otherChildObject.otherParentObject = otherParentObject

  // Making sure our original tests work
  assert.deepEqual(parentObject.childObject.parentObject, parentObject)
  assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject)

  // Should both be idempotent
  assert.equal(fss(parentObject), '{"childObject":{"special":"case"}}')
  assert.equal(fss(otherParentObject), '{"special":"case"}')

  // Therefore the following assertion should be `true`
  assert.deepEqual(parentObject.childObject.parentObject, parentObject)
  assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject)

  assert.end()
})

<commit_msg>Add tests<commit_after>var test = require('tap').test
var fss = require('./')
var clone = require('clone')
var s = JSON.stringify

test('circular reference to root', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.circle = fixture
  var expected = s(
    {name: 'Tywin Lannister', circle: '[Circular]'}
  )
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular reference to root', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.id = {circle: fixture}
  var expected = s(
    {name: 'Tywin Lannister', id: {circle: '[Circular]'}}
  )
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('child circular reference', function (assert) {
  var fixture = {name: 'Tywin Lannister', child: {name: 'Tyrion Lannister'}}
  fixture.child.dinklage = fixture.child
  var expected = s({
    name: 'Tywin Lannister',
    child: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested child circular reference', function (assert) {
  var fixture = {name: 'Tywin Lannister', child: {name: 'Tyrion Lannister'}}
  fixture.child.actor = {dinklage: fixture.child}
  var expected = s({
    name: 'Tywin Lannister',
    child: {
      name: 'Tyrion Lannister', actor: {dinklage: '[Circular]'}
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('circular objects in an array', function (assert) {
  var fixture = {name: 'Tywin Lannister'}
  fixture.hand = [fixture, fixture]
  var expected = s({
    name: 'Tywin Lannister', hand: ['[Circular]', '[Circular]']
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular references in an array', function (assert) {
  var fixture = {
    name: 'Tywin Lannister',
    offspring: [{name: 'Tyrion Lannister'}, {name: 'Cersei Lannister'}]
  }
  fixture.offspring[0].dinklage = fixture.offspring[0]
  fixture.offspring[1].headey = fixture.offspring[1]

  var expected = s({
    name: 'Tywin Lannister',
    offspring: [
      {name: 'Tyrion Lannister', dinklage: '[Circular]'},
      {name: 'Cersei Lannister', headey: '[Circular]'}
    ]
  })
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('circular arrays', function (assert) {
  var fixture = []
  fixture.push(fixture, fixture)
  var expected = s(['[Circular]', '[Circular]'])
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('nested circular arrays', function (assert) {
  var fixture = []
  fixture.push(
    {name: 'Jon Snow', bastards: fixture},
    {name: 'Ramsay Bolton', bastards: fixture}
  )
  var expected = s([
    {name: 'Jon Snow', bastards: '[Circular]'},
    {name: 'Ramsay Bolton', bastards: '[Circular]'}
  ])
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('repeated non-circular references in objects', function (assert) {
  var daenerys = {name: 'Daenerys Targaryen'}
  var fixture = {
    motherOfDragons: daenerys,
    queenOfMeereen: daenerys
  }
  var expected = s(fixture)
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('repeated non-circular references in arrays', function (assert) {
  var daenerys = {name: 'Daenerys Targaryen'}
  var fixture = [daenerys, daenerys]
  var expected = s(fixture)
  var actual = fss(fixture)
  assert.is(actual, expected)
  assert.end()
})

test('double child circular reference', function (assert) {
  // create circular reference
  var child = {name: 'Tyrion Lannister'}
  child.dinklage = child

  // include it twice in the fixture
  var fixture = {name: 'Tywin Lannister', childA: child, childB: child}
  var cloned = clone(fixture)
  var expected = s({
    name: 'Tywin Lannister',
    childA: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    },
    childB: {
      name: 'Tyrion Lannister', dinklage: '[Circular]'
    }
  })
  var actual = fss(fixture)
  assert.is(actual, expected)

  // check if the fixture has not been modified
  assert.deepEqual(fixture, cloned)
  assert.end()
})

test('child circular reference with toJSON', function (assert) {
  // Create a test object that has an overriden `toJSON` property
  TestObject.prototype.toJSON = function () { return { special: 'case' } }
  function TestObject (content) {}

  // Creating a simple circular object structure
  const parentObject = {}
  parentObject.childObject = new TestObject()
  parentObject.childObject.parentObject = parentObject

  // Creating a simple circular object structure
  const otherParentObject = new TestObject()
  otherParentObject.otherChildObject = {}
  otherParentObject.otherChildObject.otherParentObject = otherParentObject

  // Making sure our original tests work
  assert.deepEqual(parentObject.childObject.parentObject, parentObject)
  assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject)

  // Should both be idempotent
  assert.equal(fss(parentObject), '{"childObject":{"special":"case"}}')
  assert.equal(fss(otherParentObject), '{"special":"case"}')

  // Therefore the following assertion should be `true`
  assert.deepEqual(parentObject.childObject.parentObject, parentObject)
  assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject)

  assert.end()
})

test('null object', function (assert) {
  var expected = s(null)
  var actual = fss(null)
  assert.is(actual, expected)
  assert.end()
})

test('null property', function (assert) {
  var expected = s({ f: null })
  var actual = fss({ f: null })
  assert.is(actual, expected)
  assert.end()
})
<|endoftext|>


<commit_before>/* TEST FILE - Copyright (c) 2017 fast-stream - Tanase Laurentiu Iulian - https://github.com/RealTimeCom/fast-stream */
'use strict';

const http = require('./index.js'),
    fs = require('fs'),
    net = require('net');

const config = {
    '*': {
        404: cb => cb('
404 Not Found
', null, 404), //optional, default 404 page
        GET: {
            '/': function(cb, req) {
                cb('' + JSON.stringify(req) + '' + JSON.stringify({
                    client: this.remoteAddress,
                    server: this.server.address()
                }) + '');
            },
            '/30-720.mp4': cb => cb({
                src: '/home/laur/30-720.mp4'
            }, {
                'Content-Type': http.type['mp4'],
                'Content-Disposition': 'inline',
                'Content-Duration': 171,
                'X-Content-Duration': 171
            }),
            '/close': function() {
                this.server.close();
            }
        }
    }
};

net.createServer(c => {
    console.log('client connected');
    c.
    on('error', e => console.log('socket error', e.toString())).
    on('end', () => console.log('socket end')).
    on('close', () => console.log('socket close')).
    pipe(new http(config, {
        limit: 1e4,
        chunked: 1e5,
        highWaterMark: 1e6
    })).
    on('httpError', e => console.log('httpError', e.toString())).
    pipe(c);
}).
on('error', e => console.log('server error', e.toString())).
on('close', () => console.log('server close')).
listen(80, function() {
    console.log('server start', this.address());
    net.connect(80, function() {
        console.log('client request');
        this.end('GET /close HTTP/1.0\r\n\r\n');
    });
});
<commit_msg>address<commit_after>/* TEST FILE - Copyright (c) 2017 fast-stream - Tanase Laurentiu Iulian - https://github.com/RealTimeCom/fast-stream */
'use strict';

const http = require('./index.js'),
    fs = require('fs'),
    net = require('net');

const config = {
    '*': {
        404: cb => cb('
404 Not Found
', null, 404), //optional, default 404 page
        GET: {
            '/': function(cb, req) {
                cb('' + JSON.stringify(req) + '' + JSON.stringify({
                    client: this.remoteAddress,
                    server: this.server.address()
                }) + '');
            },
            '/30-720.mp4': cb => cb({
                src: '/home/laur/30-720.mp4'
            }, {
                'Content-Type': http.type['mp4'],
                'Content-Disposition': 'inline',
                'Content-Duration': 171,
                'X-Content-Duration': 171
            }),
            '/close': function() {
                this.server.close();
            }
        }
    }
};

net.createServer(c => {
    console.log('client connected');
    c.
    on('error', e => console.log('socket error', e.toString())).
    on('end', () => console.log('socket end')).
    on('close', () => console.log('socket close')).
    pipe(new http(config, {
        limit: 1e4,
        chunked: 1e5,
        highWaterMark: 1e6
    })).
    on('httpError', e => console.log('httpError', e.toString())).
    pipe(c);
}).
on('error', e => console.log('server error', e.toString())).
on('close', () => console.log('server close')).
listen(function() {
    let a = this.address();
    console.log('server start', a);
    net.connect(a.port, a.address, function() {
        console.log('client request');
        this.end('GET /close HTTP/1.0\r\n\r\n');
    });
});
<|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-6 01:31:07<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>var napa = require('./cli.js')
var Pkg = require('./lib/pkg')
var test = require('tape')
var path = require('path')
var fs = require('fs')
var rimraf = require('rimraf')

function clean(filepaths, done) {
  var count = filepaths.length
  function cb() {
    count--
    if (count < 1) process.nextTick(done)
  }
  for (var i = 0; i < filepaths.length; i++) {
     rimraf(filepaths[i], cb)
  }
}

test('args', function(t) {
  t.plan(5)
  t.deepEqual(napa.args('user/repo'), ['git://github.com/user/repo', 'repo', ''])
  t.deepEqual(napa.args('https://github.com/user/repo:testing'), ['https://github.com/user/repo', 'testing', ''])
  t.deepEqual(napa.args('git://github.com/user/repo2'), ['git://github.com/user/repo2', 'repo2', ''])
  // when developing on windows, this returns zip, linux is tar.gz
  t.deepEqual(napa.args('angular/angular.js#v1.2.3:angular'), ['https://github.com/angular/angular.js/archive/v1.2.3.' + ((process.platform === 'win32') ? 'zip' : 'tar.gz'), 'angular', 'v1.2.3:angular'])
  t.deepEqual(napa.args('https://github.com/angular/angular.js/archive/master.zip:angular'), ['https://github.com/angular/angular.js/archive/master.zip', 'angular', ''])
})

test('cmds', function(t) {
  t.plan(8)
  var testPath = path.resolve('node_modules', 'test')
  var pkg = null

  function assertPkg(url, name, cb) {
    pkg = new Pkg(url, name, { _mock: cb })
    pkg.install()
  }

  // if github is in the url then its treated like a git+ url
  assertPkg('git://github.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'git://github.com/user/repo', testPath]])
  })
  assertPkg('https://github.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'https://github.com/user/repo', testPath]])
  })

  // git+ works like npm install see https://www.npmjs.org/doc/cli/npm-install.html
  assertPkg('git+http://test.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'http://test.com/user/repo', testPath]])
  })
  assertPkg('git+https://test.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'https://test.com/user/repo', testPath]])
  })
  assertPkg('git+ssh://test.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'ssh://test.com/user/repo', testPath]])
  })

  // download
  assertPkg('ssh://test.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['download', 'ssh://test.com/user/repo', testPath])
  })
  assertPkg('https://github.com/angular/angular.js/archive/master.zip', 'angular', function(result) {
    t.deepEqual(result, ['download', 'https://github.com/angular/angular.js/archive/master.zip', path.resolve('node_modules', 'angular')])
  })
  assertPkg('https://github.com/yahoo/pure/releases/download/v0.5.0/pure-0.5.0.tar.gz', 'pure', function(result) {
    t.deepEqual(result, ['download', 'https://github.com/yahoo/pure/releases/download/v0.5.0/pure-0.5.0.tar.gz', path.resolve('node_modules', 'pure')])
  })
})

test('readpkg', function(t) {
  t.plan(1)
  var actual = napa.readpkg()
  var expected = [
    ['git://github.com/foo/repo', 'foo', ''],
    ['https://github.com/emberjs/ember.js/archive/v1.7.0.tar.gz', 'ember', ''],
    ['git://github.com/components/handlebars.js', 'handlebars', ''],
  ]
  t.deepEqual(actual, expected)
})

test('pkg install', function(t) {
  t.plan(8)
  var url = 'https://github.com/emberjs/ember.js/archive/v1.7.0.tar.gz'
  var pkgName = 'ember'
  var pkg = new Pkg(url, pkgName)
  clean([pkg.cacheTo, pkg.installTo], function() {
    pkg.install(function() {
      t.ok(fs.existsSync(pkg.installTo), 'file was installed to node_modules')
      t.ok(pkg.installed, 'pkg says it was installed')
      t.ok(fs.existsSync(pkg.cacheTo), 'file was cached')
      t.ok(pkg.cached, 'pkg says it was cached')
      // Delete pkg and install again
      clean([pkg.installTo], function() {
        pkg = new Pkg(url, pkgName)
        t.ok(!pkg.installed, 'pkg says not installed after deleted')
        t.ok(fs.existsSync(pkg.cacheTo), 'pkg deleted but cache remains')
        pkg.install(function() {
          t.ok(fs.existsSync(pkg.installTo), 'pkg installed from cache')
          t.ok(pkg.installed, 'pkg says installed when from cache')
        })
      })
    })
  })
})

test('pkg install different version', function(t) {
  t.plan(2)
  var result = null
  var pkg = new Pkg('https://github.com/emberjs/ember.js/archive/v1.6.0.tar.gz', 'ember')
  pkg.install(function() {
    result = require(path.resolve(pkg.installTo, 'package.json'))[pkg._napaResolvedKey]
    t.equal(result, 'https://github.com/emberjs/ember.js/archive/v1.6.0.tar.gz', 'should have installed the older version')

    pkg = new Pkg('https://github.com/emberjs/ember.js/archive/v1.7.0.tar.gz', 'ember')
    pkg.install(function() {
      result = require(path.resolve(pkg.installTo, 'package.json'))[pkg._napaResolvedKey]
      t.equal(result, 'https://github.com/emberjs/ember.js/archive/v1.7.0.tar.gz', 'should have installed the newer version')
    })
  })
})

test('pkg install with ref', function(t) {
  t.plan(1)
  var result = null
  var pkg = new Pkg('https://github.com/twbs/bootstrap', 'bootstrap', {ref: 'v3.3.0'})

  clean([pkg.cacheTo, pkg.installTo], function() {
    pkg.install(function(err) {
      t.notOk(err, 'no error should occur')
    })
  })
})
<commit_msg>Add test cases for #10<commit_after>var napa = require('./cli.js')
var Pkg = require('./lib/pkg')
var test = require('tape')
var path = require('path')
var fs = require('fs')
var rimraf = require('rimraf')

function clean(filepaths, done) {
  var count = filepaths.length
  function cb() {
    count--
    if (count < 1) process.nextTick(done)
  }
  for (var i = 0; i < filepaths.length; i++) {
     rimraf(filepaths[i], cb)
  }
}

test('args', function(t) {
  t.plan(5)
  t.deepEqual(napa.args('user/repo'), ['git://github.com/user/repo', 'repo', ''])
  t.deepEqual(napa.args('https://github.com/user/repo:testing'), ['https://github.com/user/repo', 'testing', ''])
  t.deepEqual(napa.args('git://github.com/user/repo2'), ['git://github.com/user/repo2', 'repo2', ''])
  // when developing on windows, this returns zip, linux is tar.gz
  t.deepEqual(napa.args('angular/angular.js#v1.2.3:angular'), ['https://github.com/angular/angular.js/archive/v1.2.3.' + ((process.platform === 'win32') ? 'zip' : 'tar.gz'), 'angular', 'v1.2.3:angular'])
  t.deepEqual(napa.args('https://github.com/angular/angular.js/archive/master.zip:angular'), ['https://github.com/angular/angular.js/archive/master.zip', 'angular', ''])
})

test('cmds', function(t) {
  t.plan(8)
  var testPath = path.resolve('node_modules', 'test')
  var pkg = null

  function assertPkg(url, name, cb) {
    pkg = new Pkg(url, name, { _mock: cb })
    pkg.install()
  }

  // if github is in the url then its treated like a git+ url
  assertPkg('git://github.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'git://github.com/user/repo', testPath]])
  })
  assertPkg('https://github.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'https://github.com/user/repo', testPath]])
  })

  // git+ works like npm install see https://www.npmjs.org/doc/cli/npm-install.html
  assertPkg('git+http://test.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'http://test.com/user/repo', testPath]])
  })
  assertPkg('git+https://test.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'https://test.com/user/repo', testPath]])
  })
  assertPkg('git+ssh://test.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['git', ['clone', '--depth', '1', '-q', 'ssh://test.com/user/repo', testPath]])
  })

  // download
  assertPkg('ssh://test.com/user/repo', 'test', function(result) {
    t.deepEqual(result, ['download', 'ssh://test.com/user/repo', testPath])
  })
  assertPkg('https://github.com/angular/angular.js/archive/master.zip', 'angular', function(result) {
    t.deepEqual(result, ['download', 'https://github.com/angular/angular.js/archive/master.zip', path.resolve('node_modules', 'angular')])
  })
  assertPkg('https://github.com/yahoo/pure/releases/download/v0.5.0/pure-0.5.0.tar.gz', 'pure', function(result) {
    t.deepEqual(result, ['download', 'https://github.com/yahoo/pure/releases/download/v0.5.0/pure-0.5.0.tar.gz', path.resolve('node_modules', 'pure')])
  })
})

test('readpkg', function(t) {
  t.plan(1)
  var actual = napa.readpkg()
  var expected = [
    ['git://github.com/foo/repo', 'foo', ''],
    ['https://github.com/emberjs/ember.js/archive/v1.7.0.tar.gz', 'ember', ''],
    ['git://github.com/components/handlebars.js', 'handlebars', ''],
  ]
  t.deepEqual(actual, expected)
})

test('pkg install', function(t) {
  t.plan(11)
  var url = 'https://github.com/emberjs/ember.js/archive/v1.7.0.tar.gz'
  var pkgName = 'ember'
  var pkg = new Pkg(url, pkgName)
  clean([pkg.cacheTo, pkg.installTo], function() {
    pkg.install(function() {
      var packagePath, package;
      t.ok(fs.existsSync(pkg.installTo), 'file was installed to node_modules')
      t.ok(pkg.installed, 'pkg says it was installed')
      t.ok(fs.existsSync(pkg.cacheTo), 'file was cached')
      t.ok(pkg.cached, 'pkg says it was cached')
      t.ok(fs.existsSync(packagePath = path.resolve(pkg.installTo, 'package.json')), 'package.json has been generated')
      t.ok((package = require(packagePath)) && package.name && package.version, 'package.json has required fields')
      t.ok(package && package.description && package.readme && package.repository && package.repository.type, 'package.json has recommended fields')
      // Delete pkg and install again
      clean([pkg.installTo], function() {
        pkg = new Pkg(url, pkgName)
        t.ok(!pkg.installed, 'pkg says not installed after deleted')
        t.ok(fs.existsSync(pkg.cacheTo), 'pkg deleted but cache remains')
        pkg.install(function() {
          t.ok(fs.existsSync(pkg.installTo), 'pkg installed from cache')
          t.ok(pkg.installed, 'pkg says installed when from cache')
        })
      })
    })
  })
})

test('pkg install different version', function(t) {
  t.plan(2)
  var result = null
  var pkg = new Pkg('https://github.com/emberjs/ember.js/archive/v1.6.0.tar.gz', 'ember')
  pkg.install(function() {
    result = require(path.resolve(pkg.installTo, 'package.json'))[pkg._napaResolvedKey]
    t.equal(result, 'https://github.com/emberjs/ember.js/archive/v1.6.0.tar.gz', 'should have installed the older version')

    pkg = new Pkg('https://github.com/emberjs/ember.js/archive/v1.7.0.tar.gz', 'ember')
    pkg.install(function() {
      result = require(path.resolve(pkg.installTo, 'package.json'))[pkg._napaResolvedKey]
      t.equal(result, 'https://github.com/emberjs/ember.js/archive/v1.7.0.tar.gz', 'should have installed the newer version')
    })
  })
})

test('pkg install with ref', function(t) {
  t.plan(1)
  var result = null
  var pkg = new Pkg('https://github.com/twbs/bootstrap', 'bootstrap', {ref: 'v3.3.0'})

  clean([pkg.cacheTo, pkg.installTo], function() {
    pkg.install(function(err) {
      t.notOk(err, 'no error should occur')
    })
  })
})
<|endoftext|>


<commit_before>import test from 'ava';
import isPortReachable from '.';

test('ip', async t => {
	t.true(await isPortReachable(80, {host: '216.58.217.142'}));
});

test('domain', async t => {
	t.true(await isPortReachable(80, {host: 'google.com'}));
});

test('domain - alternative port', async t => {
	t.false(await isPortReachable(8000, {host: 'google.com'}));
});

test('fail', async t => {
	t.false(await isPortReachable(0));
});
<commit_msg>Fix Travis<commit_after>import test from 'ava';
import isPortReachable from '.';

if (!('CI' in process.env)) {
	test('ip', async t => {
		t.true(await isPortReachable(80, {host: '216.58.217.142'}));
	});
}

test('domain', async t => {
	t.true(await isPortReachable(80, {host: 'google.com'}));
});

test('domain - alternative port', async t => {
	t.false(await isPortReachable(8000, {host: 'google.com'}));
});

test('fail', async t => {
	t.false(await isPortReachable(0));
});
<|endoftext|>


<commit_before>'use strict';

require('mocha');
var isCI = process.env.TRAVIS || process.env.APPVEYOR || process.env.CI;
var assert = require('assert');
var utils = require('./utils');
var size = require('./');
var tty = require('tty');

function override(obj) {
  var getWindowSize = obj.getWindowSize;
  var columns = obj.columns;
  var rows = obj.rows;

  obj.getWindowSize = null;
  obj.columns = null;
  obj.rows = null;

  return function() {
    obj.getWindowSize = getWindowSize;
    obj.columns = columns;
    obj.rows = rows;
  };
}

describe('window-size', function() {
  it('should return an object with width and height', function() {
    if (!process.env.APPVEYOR) {
      assert.equal(typeof size.width, 'number');
      assert.equal(typeof size.height, 'number');
    }
  });

  it('should expose a `.get` method to get up-to-date size', function() {
    if (!process.env.APPVEYOR) {
      var s = size.get();
      assert.equal(typeof s.width, 'number');
      assert.equal(typeof s.height, 'number');
    }
  });

  it('should get size from process.stdout', function() {
    if (!process.env.APPVEYOR) {
      var count = 0;
      var restore = override(process.stdout);
      process.stdout.getWindowSize = function() {
        count++;
      };

      size.get();
      restore();
      assert.equal(count, 1);
    }
  });

  it('should get size from process.stderr', function() {
    if (!process.env.APPVEYOR) {
      var restoreOut = override(process.stdout);
      var restoreErr = override(process.stderr);

      var count = 0;
      process.stderr.getWindowSize = function() {
        count++;
      };

      size.get();
      restoreOut();
      restoreErr();
      assert.equal(count, 1);
    }
  });

  it('should get size from process.env', function() {
    if (!process.env.APPVEYOR) {
      process.env.COLUMNS = 80;
      process.env.ROWS = 25;

      var s = size.env();
      assert(s);
      assert.equal(s.width, 80);
      assert.equal(s.height, 25);

      process.env.COLUMNS = null;
      process.env.ROWS = null;
    }
  });

  it('should get size from tty', function() {
    if (!process.env.APPVEYOR) {
      var restoreOut = override(process.stdout);
      var restoreErr = override(process.stderr);
      var restoreTty = override(tty);

      var count = 0;
      tty.getWindowSize = function() {
        count++;
      };

      size.get();
      restoreOut();
      restoreErr();
      restoreTty();
      assert.equal(count, 1);
    }
  });

  it('should get size from tput', function() {
    if (!isCI) {
      var s = size.tput();
      assert(s);
      assert.equal(typeof s.width, 'number');
      assert.equal(typeof s.height, 'number');
    }
  });

  describe('utils', function() {
    it('should expose a `.get` method to get up-to-date size', function() {
      var s = utils.get();
      assert.equal(typeof s.width, 'number');
      assert.equal(typeof s.height, 'number');
    });

    it('should get size from process.env', function() {
      process.env.COLUMNS = 80;
      process.env.ROWS = 25;

      var s = utils.env();
      assert(s);
      assert.equal(s.width, 80);
      assert.equal(s.height, 25);

      process.env.COLUMNS = null;
      process.env.ROWS = null;
    });

    it('should get size from tty', function() {
      var restoreTty = override(tty);

      var count = 0;
      tty.getWindowSize = function() {
        count++;
      };

      utils.tty({});
      restoreTty();
      assert.equal(count, 1);
    });

    it('should get size from tput', function() {
      if (!isCI) {
        var s = utils.tput();
        assert(s);
        assert.equal(typeof s.width, 'number');
        assert.equal(typeof s.height, 'number');
      }
    });
  });
});

<commit_msg>normal get does not work on appveyor<commit_after>'use strict';

require('mocha');
var isCI = process.env.TRAVIS || process.env.APPVEYOR || process.env.CI;
var assert = require('assert');
var utils = require('./utils');
var size = require('./');
var tty = require('tty');

function override(obj) {
  var getWindowSize = obj.getWindowSize;
  var columns = obj.columns;
  var rows = obj.rows;

  obj.getWindowSize = null;
  obj.columns = null;
  obj.rows = null;

  return function() {
    obj.getWindowSize = getWindowSize;
    obj.columns = columns;
    obj.rows = rows;
  };
}

describe('window-size', function() {
  it('should return an object with width and height', function() {
    if (!process.env.APPVEYOR) {
      assert.equal(typeof size.width, 'number');
      assert.equal(typeof size.height, 'number');
    }
  });

  it('should expose a `.get` method to get up-to-date size', function() {
    if (!process.env.APPVEYOR) {
      var s = size.get();
      assert.equal(typeof s.width, 'number');
      assert.equal(typeof s.height, 'number');
    }
  });

  it('should get size from process.stdout', function() {
    if (!process.env.APPVEYOR) {
      var count = 0;
      var restore = override(process.stdout);
      process.stdout.getWindowSize = function() {
        count++;
      };

      size.get();
      restore();
      assert.equal(count, 1);
    }
  });

  it('should get size from process.stderr', function() {
    if (!process.env.APPVEYOR) {
      var restoreOut = override(process.stdout);
      var restoreErr = override(process.stderr);

      var count = 0;
      process.stderr.getWindowSize = function() {
        count++;
      };

      size.get();
      restoreOut();
      restoreErr();
      assert.equal(count, 1);
    }
  });

  it('should get size from process.env', function() {
    if (!process.env.APPVEYOR) {
      process.env.COLUMNS = 80;
      process.env.ROWS = 25;

      var s = size.env();
      assert(s);
      assert.equal(s.width, 80);
      assert.equal(s.height, 25);

      process.env.COLUMNS = null;
      process.env.ROWS = null;
    }
  });

  it('should get size from tty', function() {
    if (!process.env.APPVEYOR) {
      var restoreOut = override(process.stdout);
      var restoreErr = override(process.stderr);
      var restoreTty = override(tty);

      var count = 0;
      tty.getWindowSize = function() {
        count++;
      };

      size.get();
      restoreOut();
      restoreErr();
      restoreTty();
      assert.equal(count, 1);
    }
  });

  it('should get size from tput', function() {
    if (!isCI) {
      var s = size.tput();
      assert(s);
      assert.equal(typeof s.width, 'number');
      assert.equal(typeof s.height, 'number');
    }
  });

  describe('utils', function() {
    it('should expose a `.get` method to get up-to-date size', function() {
      var s = utils.get();
      if (process.env.APPVEYOR) {
        assert.equal(typeof s, 'undefined');
      } else {
        assert.equal(typeof s.width, 'number');
        assert.equal(typeof s.height, 'number');
      }
    });

    it('should get size from process.env', function() {
      process.env.COLUMNS = 80;
      process.env.ROWS = 25;

      var s = utils.env();
      assert(s);
      assert.equal(s.width, 80);
      assert.equal(s.height, 25);

      process.env.COLUMNS = null;
      process.env.ROWS = null;
    });

    it('should get size from tty', function() {
      var restoreTty = override(tty);

      var count = 0;
      tty.getWindowSize = function() {
        count++;
      };

      utils.tty({});
      restoreTty();
      assert.equal(count, 1);
    });

    it('should get size from tput', function() {
      if (!isCI) {
        var s = utils.tput();
        assert(s);
        assert.equal(typeof s.width, 'number');
        assert.equal(typeof s.height, 'number');
      }
    });
  });
});

<|endoftext|>


<commit_before>let jsroot = require("jsroot");
let fs = require("fs");

require("./../jsroot/demo/examples.js");

console.log('JSROOT version', jsroot.version);

let init_style = null,
    test_mode = "verify", nmatch = 0, ndiff = 0, nnew = 0,
    keyid = 'TH1', theonlykey = false, optid = -1,
    theOnlyOption, theOnlyOptionId = -100, itemid = -1,
    entry, entry_name = "", testfile = null, testobj = null;

if (process.argv && (process.argv.length > 2)) {

   for (let cnt=2;cnt<process.argv.length;++cnt)
      switch (process.argv[cnt]) {
        case "-v":
        case "--verify":  test_mode = "verify"; break;
        case "-c":
        case "--create": test_mode = "create"; break;
        case "-k":
        case "--key":
           keyid = process.argv[++cnt];
           theonlykey = true;
           if (!keyid || !examples_main[keyid])
              return console.log('Key not found', keyid);
           break;
        case "-o":
        case "--opt":
           theOnlyOption = process.argv[++cnt];
           theOnlyOptionId = parseInt(theOnlyOption);
           if (isNaN(theOnlyOptionId) || (theOnlyOptionId<0) || !examples_main[keyid][theOnlyOptionId]) {
              theOnlyOptionId = -100;
           } else {
              console.log('Select option', examples_main[keyid][theOnlyOptionId], 'for key', keyid);
              optid = theOnlyOptionId - 1;
              theOnlyOption = "";
           }
           break;
        case "-m":
        case "--more":
           require("./../jsroot/demo/examples_more.js");

           for (let key in examples_more) {
              if (key in examples_main) {
                 for (let n in examples_more[key])
                    examples_main[key].push(examples_more[key][n]);
              } else {
                 examples_main[key] = examples_more[key];
              }
           }

           break;

        default:
           console.log('Usage: node test.js [options]');
           console.log('   -v | --verify : check stored content against current JSROOT version');
           console.log('   -c | --create : perform checks and overwrite when results differ');
           console.log('   -k | --key keyname : select specific key (class name) like TH1 or TProfile for testing');
           console.log('   -o | --opt id : select specific option id (number or name), only when key is specified');
           console.log('   -m | --more : use more tests');
           return;
      }
}

function ProduceGlobalStyleCopy() {
   // copy style when painter is loaded
   if (!init_style && jsroot.Painter) init_style = jsroot.gStyle;
}

function ProduceFile(content, extension) {
   if (!entry_name) entry_name = keyid;

   entry_name = entry_name.replace(/\+/g,'p').replace(/\>/g,'more')
                          .replace(/\</g,'less').replace(/\|/g,'I')
                          .replace(/\[/g,'L').replace(/\]/g,'J').replace(/\*/g,'star');

   // in older node.js fs.constants not exists
   let w_ok = fs.constants ? fs.constants.W_OK : fs.W_OK;

   fs.access(keyid, w_ok, function(dir_err) {

      if (dir_err) fs.mkdirSync(keyid);

      let svgname = keyid + "/" + entry_name + extension,
          svg0 = null, result = "MATCH";

      try {
        svg0 = fs.readFileSync(svgname, 'utf-8');
        if (svg0 != content) result = "DIFF";
      } catch(e) {
        svg0 = null;
        result = "NEW";
      }

      switch (result) {
         case "NEW": nnew++; break;
         case "DIFF": ndiff++; break;
         default: nmatch++;
      }

      let clen = content ? content.length : -1;
      console.log(keyid, entry_name, 'result', result, 'len='+clen, (svg0 && result=='DIFF' ? 'rel0='+(clen/svg0.length*100).toFixed(1)+'\%' : ''));

      if ((result === "NEW") || ((test_mode === 'create') && (result!=='MATCH'))) {
         if (clen > 0)
            fs.writeFileSync(svgname, content);
         else if (result !== "NEW")
            fs.unlink(svgname);
      }

      ProcessNextOption();
   });
}

function ProduceSVG(obj, opt) {

   // use only for object reading
   if ((theOnlyOptionId>=0) && theOnlyOptionId!==optid)
      return ProcessNextOption();

   jsroot.MakeSVG({ object: obj, option: opt, width: 1200, height: 800 })
         .then(svg => ProduceFile(svg, ".svg"));
}

function ProduceJSON(tree, opt, branchname) {
   if (!tree) return ProcessNextOption();

   let args = { expr: opt, dump: true };
   if (branchname) {
      if (branchname === "/Event/Gen/Header/m_evtNumber") branchname = "/Event/Gen/Header.m_evtNumber"; // workaround
      if (branchname === "ESDfriend./fTracks/fTPCindex") branchname = "ESDfriend.fTracks.fTPCindex"; // workaround
      if (branchname === "event/fTracks/fMass2") branchname = "event.fTracks.fMass2"; // workaround
      if (branchname === "Rec::TrackParticleContainer_tlp1_MooreTrackParticles/m_hepSymMatrices/m_matrix_val")
          branchname = "Rec::TrackParticleContainer_tlp1_MooreTrackParticles.m_hepSymMatrices.m_matrix_val";
      args.branch = tree.FindBranch(branchname);
      if (!args.branch) console.log('Fail to find branch', branchname)
   }

   tree.Draw(args).then(res => {
      let json = res ? JSON.stringify(res) : "<fail>";
      ProduceFile(json, ".json");
   });
}

function ProcessNextOption(reset_mathjax) {

   if (!keyid) {
      console.log('No more data to process');
      console.log("SUMMARY: match", nmatch, "diff", ndiff, "new", nnew);
      return;
   }

   let opts = examples_main[keyid];
   if (!opts) return;

   if (!reset_mathjax) {
      if ((itemid>=0) || (itemid==-2)) {
         if (itemid==-2) itemid = -1; // special workaround for style entry, which is marked as itemid=-2
         if (++itemid>=opts[optid].items.length) itemid = -1;
      }

      if (itemid < 0) { // first check that all items are processed
         if (theOnlyOptionId == optid) {
            keyid = null;
            return ProcessNextOption();
         }
         if (++optid>=opts.length) {
            optid = -1;
            let found = false, next = null;
            for (let key in examples_main) {
               if (key === "TGeo") continue; // skip already here
               if (found) { next = key; break; }
               if (key == keyid) found = true;
            }

            keyid = next;
            if (theonlykey) keyid = null;
            return ProcessNextOption();
         }
      }
   }

   entry = opts[optid];

   entry_name = "";

   // exclude some entries from the test
   if (entry.notest) return ProcessNextOption();

   if (((entry.latex === "mathjax") || entry.reset_mathjax) && !reset_mathjax)
      return jsroot.require('latex')
                   .then(ltx => ltx.LoadMathjax())
                   .then(() => {
         MathJax.startup.defaultReady();
         console.log('Loading MathJax and doing extra reset!!!')
         ProcessNextOption(true);
      });

   let filename = "", itemname = "", itemfield = "", jsonname = "", url = "", opt = "", opt2 = "",
       filepath = "http://jsroot.gsi.de/files/";
//       filepath = "https://root.cern.ch/js/files/";

   if (entry.file) {
       filename = entry.file;
       if ((filename.indexOf("http:")<0) && (filename.indexOf("https:")<0)) filename = filepath + filename;
   }
   if (entry.item) {
      itemname = entry.item;
      if (entry.itemfield) { itemfield = entry.itemfield; itemname = itemname.substr(0, itemname.length - itemfield.length - 1); }
   }
   if (entry.testopt !== undefined) opt = entry.testopt; else if (entry.opt) opt = entry.opt;

   if (entry.json) {
      jsonname = entry.json;
      if ((jsonname.indexOf("http:")<0) && (jsonname.indexOf("https:")<0)) jsonname = filepath + jsonname;
   }
   if (entry.items) {
      if (itemid<0) {

         if ((itemid==-1) && entry.style) {
            itemid = -2;
            itemname = entry.style; // special case when style should be applied before objects drawing
         } else {
           itemid = 0;
         }
      }
      if (itemid>=0) {
         itemname = entry.items[itemid];
         if (entry.opts && (itemid < entry.opts.length)) opt = entry.opts[itemid];
      }
   }

   if (entry.r3d) opt2 = (opt ? "," : "") + "r3d_" + entry.r3d;

   if (entry.url) url = entry.url.replace(/\$\$\$/g, filepath); else
   if (entry.asurl) {
      url = ((entry.asurl === "browser") ? "?" : "?nobrowser&");
      url += jsonname ? "json=" + jsonname : "file=" + filename + "&item=" + itemname;
      url += itemname + "&opt=" + opt + opt2;
   }

   if ((opt=='inspect') || (opt=='count')) return ProcessNextOption();

   if (itemid >= 0)
      entry_name = (entry.name || keyid) + "_" + itemname + (opt ? "_" + opt : "");
   else if ('name' in entry)
      entry_name = entry.name;
   else
      entry_name = opt ? opt : keyid;

   if (theOnlyOption) {
      if (entry_name != theOnlyOption) return ProcessNextOption();
      console.log('Select option', entry);
   }

   ProduceGlobalStyleCopy();
   if (!entry.style && init_style) jsroot.gStyle = jsroot.extend({}, init_style);

   // ensure default options
   if (jsroot.Painter) jsroot.Painter.createRootColors(); // ensure default colors
   jsroot.settings.Latex = 2;
   if (entry.latex) jsroot.settings.Latex = jsroot.constants.Latex.fromString(entry.latex);
   // seedrandom('hello.', { global: true }); // set global random
   jsroot._.id_counter = 1; // used in some custom styles

   if (keyid === "TTree") {
      if (entry.url || entry.large) return ProcessNextOption(); // ignore direct URL
      // console.log('Processing ', entry);

      jsroot.OpenFile(filename).then(file => {
         let branchname = "", pos = itemname.indexOf(";1/");
         if (pos>0) { branchname = itemname.substr(pos+3); itemname = itemname.substr(0, pos+2); }
         if (!branchname && opt == "dump") {
            pos = itemname.indexOf("/");
            if (pos > 0) { branchname = itemname.substr(pos+1); itemname = itemname.substr(0, pos); }
         }
         file.ReadObject(itemname).then(tree => {
            // if (branchname) console.log('Branch name is', branchname);
            ProduceJSON(tree, opt+opt2, branchname);
         }).catch(()=> { console.log('Fail to find tree', itemname); ProcessNextOption(); });
      });
   } else if (((url.length > 0) && !entry.asurl)) {
      testfile = testobj = null;
      return ProcessNextOption();
   } else if (jsonname.length > 0) {
      testfile = testobj = null;
      jsroot.httpRequest(jsonname, 'object').then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt+opt2);
      });
   } else if (filename.length > 0) {
      jsroot.OpenFile(filename).then(file => {
         testfile = file;
         testfile.ReadObject(itemname).then(obj => {
            if (itemid==-2) {
               // special handling of style
               // Check that copy of gStyle exists
               ProduceGlobalStyleCopy();
               // first create copy of existing style
               let newstyle = jsroot.extend({}, jsroot.gStyle);
               // then apply changes to the
               jsroot.gStyle = jsroot.extend(newstyle, obj);
               return ProcessNextOption();
            } else {
               if (itemfield) {
                  if (itemfield == "Overlaps/ov00010") {
                     obj = obj.fOverlaps.arr[10];
                     console.log("found obj", obj ? obj._typename : "none");
                  } else if (obj[itemfield])
                     obj = obj[itemfield];
               }
               testobj = obj;
               ProduceSVG(testobj, opt+opt2);
            }
         });
      });
   } else if (itemname.length > 0) {
      testfile.ReadObject(itemname).then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt+opt2);
      });
   } else {
      ProduceSVG(testobj, opt+opt2);
   }
}

// start processing

ProcessNextOption();
<commit_msg>Rename OpenFile -> openFile<commit_after>let jsroot = require("jsroot");
let fs = require("fs");

require("./../jsroot/demo/examples.js");

console.log('JSROOT version', jsroot.version);

let init_style = null,
    test_mode = "verify", nmatch = 0, ndiff = 0, nnew = 0,
    keyid = 'TH1', theonlykey = false, optid = -1,
    theOnlyOption, theOnlyOptionId = -100, itemid = -1,
    entry, entry_name = "", testfile = null, testobj = null;

if (process.argv && (process.argv.length > 2)) {

   for (let cnt=2;cnt<process.argv.length;++cnt)
      switch (process.argv[cnt]) {
        case "-v":
        case "--verify":  test_mode = "verify"; break;
        case "-c":
        case "--create": test_mode = "create"; break;
        case "-k":
        case "--key":
           keyid = process.argv[++cnt];
           theonlykey = true;
           if (!keyid || !examples_main[keyid])
              return console.log('Key not found', keyid);
           break;
        case "-o":
        case "--opt":
           theOnlyOption = process.argv[++cnt];
           theOnlyOptionId = parseInt(theOnlyOption);
           if (isNaN(theOnlyOptionId) || (theOnlyOptionId<0) || !examples_main[keyid][theOnlyOptionId]) {
              theOnlyOptionId = -100;
           } else {
              console.log('Select option', examples_main[keyid][theOnlyOptionId], 'for key', keyid);
              optid = theOnlyOptionId - 1;
              theOnlyOption = "";
           }
           break;
        case "-m":
        case "--more":
           require("./../jsroot/demo/examples_more.js");

           for (let key in examples_more) {
              if (key in examples_main) {
                 for (let n in examples_more[key])
                    examples_main[key].push(examples_more[key][n]);
              } else {
                 examples_main[key] = examples_more[key];
              }
           }

           break;

        default:
           console.log('Usage: node test.js [options]');
           console.log('   -v | --verify : check stored content against current JSROOT version');
           console.log('   -c | --create : perform checks and overwrite when results differ');
           console.log('   -k | --key keyname : select specific key (class name) like TH1 or TProfile for testing');
           console.log('   -o | --opt id : select specific option id (number or name), only when key is specified');
           console.log('   -m | --more : use more tests');
           return;
      }
}

function ProduceGlobalStyleCopy() {
   // copy style when painter is loaded
   if (!init_style && jsroot.Painter) init_style = jsroot.gStyle;
}

function ProduceFile(content, extension) {
   if (!entry_name) entry_name = keyid;

   entry_name = entry_name.replace(/\+/g,'p').replace(/\>/g,'more')
                          .replace(/\</g,'less').replace(/\|/g,'I')
                          .replace(/\[/g,'L').replace(/\]/g,'J').replace(/\*/g,'star');

   // in older node.js fs.constants not exists
   let w_ok = fs.constants ? fs.constants.W_OK : fs.W_OK;

   fs.access(keyid, w_ok, function(dir_err) {

      if (dir_err) fs.mkdirSync(keyid);

      let svgname = keyid + "/" + entry_name + extension,
          svg0 = null, result = "MATCH";

      try {
        svg0 = fs.readFileSync(svgname, 'utf-8');
        if (svg0 != content) result = "DIFF";
      } catch(e) {
        svg0 = null;
        result = "NEW";
      }

      switch (result) {
         case "NEW": nnew++; break;
         case "DIFF": ndiff++; break;
         default: nmatch++;
      }

      let clen = content ? content.length : -1;
      console.log(keyid, entry_name, 'result', result, 'len='+clen, (svg0 && result=='DIFF' ? 'rel0='+(clen/svg0.length*100).toFixed(1)+'\%' : ''));

      if ((result === "NEW") || ((test_mode === 'create') && (result!=='MATCH'))) {
         if (clen > 0)
            fs.writeFileSync(svgname, content);
         else if (result !== "NEW")
            fs.unlink(svgname);
      }

      ProcessNextOption();
   });
}

function ProduceSVG(obj, opt) {

   // use only for object reading
   if ((theOnlyOptionId>=0) && theOnlyOptionId!==optid)
      return ProcessNextOption();

   jsroot.MakeSVG({ object: obj, option: opt, width: 1200, height: 800 })
         .then(svg => ProduceFile(svg, ".svg"));
}

function ProduceJSON(tree, opt, branchname) {
   if (!tree) return ProcessNextOption();

   let args = { expr: opt, dump: true };
   if (branchname) {
      if (branchname === "/Event/Gen/Header/m_evtNumber") branchname = "/Event/Gen/Header.m_evtNumber"; // workaround
      if (branchname === "ESDfriend./fTracks/fTPCindex") branchname = "ESDfriend.fTracks.fTPCindex"; // workaround
      if (branchname === "event/fTracks/fMass2") branchname = "event.fTracks.fMass2"; // workaround
      if (branchname === "Rec::TrackParticleContainer_tlp1_MooreTrackParticles/m_hepSymMatrices/m_matrix_val")
          branchname = "Rec::TrackParticleContainer_tlp1_MooreTrackParticles.m_hepSymMatrices.m_matrix_val";
      args.branch = tree.FindBranch(branchname);
      if (!args.branch) console.log('Fail to find branch', branchname)
   }

   tree.Draw(args).then(res => {
      let json = res ? JSON.stringify(res) : "<fail>";
      ProduceFile(json, ".json");
   });
}

function ProcessNextOption(reset_mathjax) {

   if (!keyid) {
      console.log('No more data to process');
      console.log("SUMMARY: match", nmatch, "diff", ndiff, "new", nnew);
      return;
   }

   let opts = examples_main[keyid];
   if (!opts) return;

   if (!reset_mathjax) {
      if ((itemid>=0) || (itemid==-2)) {
         if (itemid==-2) itemid = -1; // special workaround for style entry, which is marked as itemid=-2
         if (++itemid>=opts[optid].items.length) itemid = -1;
      }

      if (itemid < 0) { // first check that all items are processed
         if (theOnlyOptionId == optid) {
            keyid = null;
            return ProcessNextOption();
         }
         if (++optid>=opts.length) {
            optid = -1;
            let found = false, next = null;
            for (let key in examples_main) {
               if (key === "TGeo") continue; // skip already here
               if (found) { next = key; break; }
               if (key == keyid) found = true;
            }

            keyid = next;
            if (theonlykey) keyid = null;
            return ProcessNextOption();
         }
      }
   }

   entry = opts[optid];

   entry_name = "";

   // exclude some entries from the test
   if (entry.notest) return ProcessNextOption();

   if (((entry.latex === "mathjax") || entry.reset_mathjax) && !reset_mathjax)
      return jsroot.require('latex')
                   .then(ltx => ltx.LoadMathjax())
                   .then(() => {
         MathJax.startup.defaultReady();
         console.log('Loading MathJax and doing extra reset!!!')
         ProcessNextOption(true);
      });

   let filename = "", itemname = "", itemfield = "", jsonname = "", url = "", opt = "", opt2 = "",
       filepath = "http://jsroot.gsi.de/files/";
//       filepath = "https://root.cern.ch/js/files/";

   if (entry.file) {
       filename = entry.file;
       if ((filename.indexOf("http:")<0) && (filename.indexOf("https:")<0)) filename = filepath + filename;
   }
   if (entry.item) {
      itemname = entry.item;
      if (entry.itemfield) { itemfield = entry.itemfield; itemname = itemname.substr(0, itemname.length - itemfield.length - 1); }
   }
   if (entry.testopt !== undefined) opt = entry.testopt; else if (entry.opt) opt = entry.opt;

   if (entry.json) {
      jsonname = entry.json;
      if ((jsonname.indexOf("http:")<0) && (jsonname.indexOf("https:")<0)) jsonname = filepath + jsonname;
   }
   if (entry.items) {
      if (itemid<0) {

         if ((itemid==-1) && entry.style) {
            itemid = -2;
            itemname = entry.style; // special case when style should be applied before objects drawing
         } else {
           itemid = 0;
         }
      }
      if (itemid>=0) {
         itemname = entry.items[itemid];
         if (entry.opts && (itemid < entry.opts.length)) opt = entry.opts[itemid];
      }
   }

   if (entry.r3d) opt2 = (opt ? "," : "") + "r3d_" + entry.r3d;

   if (entry.url) url = entry.url.replace(/\$\$\$/g, filepath); else
   if (entry.asurl) {
      url = ((entry.asurl === "browser") ? "?" : "?nobrowser&");
      url += jsonname ? "json=" + jsonname : "file=" + filename + "&item=" + itemname;
      url += itemname + "&opt=" + opt + opt2;
   }

   if ((opt=='inspect') || (opt=='count')) return ProcessNextOption();

   if (itemid >= 0)
      entry_name = (entry.name || keyid) + "_" + itemname + (opt ? "_" + opt : "");
   else if ('name' in entry)
      entry_name = entry.name;
   else
      entry_name = opt ? opt : keyid;

   if (theOnlyOption) {
      if (entry_name != theOnlyOption) return ProcessNextOption();
      console.log('Select option', entry);
   }

   ProduceGlobalStyleCopy();
   if (!entry.style && init_style) jsroot.gStyle = jsroot.extend({}, init_style);

   // ensure default options
   if (jsroot.Painter) jsroot.Painter.createRootColors(); // ensure default colors
   jsroot.settings.Latex = 2;
   if (entry.latex) jsroot.settings.Latex = jsroot.constants.Latex.fromString(entry.latex);
   // seedrandom('hello.', { global: true }); // set global random
   jsroot._.id_counter = 1; // used in some custom styles

   if (keyid === "TTree") {
      if (entry.url || entry.large) return ProcessNextOption(); // ignore direct URL
      // console.log('Processing ', entry);

      jsroot.openFile(filename).then(file => {
         let branchname = "", pos = itemname.indexOf(";1/");
         if (pos>0) { branchname = itemname.substr(pos+3); itemname = itemname.substr(0, pos+2); }
         if (!branchname && opt == "dump") {
            pos = itemname.indexOf("/");
            if (pos > 0) { branchname = itemname.substr(pos+1); itemname = itemname.substr(0, pos); }
         }
         file.ReadObject(itemname).then(tree => {
            // if (branchname) console.log('Branch name is', branchname);
            ProduceJSON(tree, opt+opt2, branchname);
         }).catch(()=> { console.log('Fail to find tree', itemname); ProcessNextOption(); });
      });
   } else if (((url.length > 0) && !entry.asurl)) {
      testfile = testobj = null;
      return ProcessNextOption();
   } else if (jsonname.length > 0) {
      testfile = testobj = null;
      jsroot.httpRequest(jsonname, 'object').then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt+opt2);
      });
   } else if (filename.length > 0) {
      jsroot.openFile(filename).then(file => {
         testfile = file;
         return testfile.ReadObject(itemname);
      }).then(obj => {
         if (itemid==-2) {
            // special handling of style
            // Check that copy of gStyle exists
            ProduceGlobalStyleCopy();
            // first create copy of existing style
            let newstyle = jsroot.extend({}, jsroot.gStyle);
            // then apply changes to the
            jsroot.gStyle = jsroot.extend(newstyle, obj);
            return ProcessNextOption();
         } else {
            if (itemfield) {
               if (itemfield == "Overlaps/ov00010") {
                  obj = obj.fOverlaps.arr[10];
                  console.log("found obj", obj ? obj._typename : "none");
               } else if (obj[itemfield])
                  obj = obj[itemfield];
            }
            testobj = obj;
            ProduceSVG(testobj, opt+opt2);
         }
      });
   } else if (itemname.length > 0) {
      testfile.ReadObject(itemname).then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt+opt2);
      });
   } else {
      ProduceSVG(testobj, opt+opt2);
   }
}

// start processing

ProcessNextOption();
<|endoftext|>


<commit_before>var fs = require("fs");
var jison = require("jison");

var bnf = fs.readFileSync("parser.jison", "utf8");
var parser = new jison.Parser(bnf);

var example1 = fs.readFileSync("parseExample1.txt", "utf8");

var jsonString = parser.parse(example1);

console.log(jsonString);

var jsObject = JSON.parse(jsonString);
<commit_msg>syntax error gone, yay<commit_after>var fs = require("fs");
var jison = require("jison");

var bnf = fs.readFileSync("parser.jison", "utf8");
var parser = new jison.Parser(bnf);

var example1 = fs.readFileSync("parseExample1.txt", "utf8");

var jsonString = parser.parse(example1);

console.log(jsonString);

var jsObject = JSON.parse(jsonString);

console.log(jsObject);
<|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-9 18:24:19<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 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-13 21:01:52<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>var test = require("tape")
var extend = require("./")
var mutableExtend = require("./mutable")

test("merge", function(assert) {
    var a = { a: "foo" }
    var b = { b: "bar" }

    assert.deepEqual(extend(a, b), { a: "foo", b: "bar" })
    assert.end()
})

test("replace", function(assert) {
    var a = { a: "foo" }
    var b = { a: "bar" }

    assert.deepEqual(extend(a, b), { a: "bar" })
    assert.end()
})

test("undefined", function(assert) {
    var a = { a: undefined }
    var b = { b: "foo" }

    assert.deepEqual(extend(a, b), { a: undefined, b: "foo" })
    assert.deepEqual(extend(b, a), { a: undefined, b: "foo" })
    assert.end()
})

test("handle 0", function(assert) {
    var a = { a: "default" }
    var b = { a: 0 }

    assert.deepEqual(extend(a, b), { a: 0 })
    assert.deepEqual(extend(b, a), { a: "default" })
    assert.end()
})

test("is immutable", function (assert) {
    var record = {}

    extend(record, { foo: "bar" })
    assert.equal(record.foo, undefined)
    assert.end()
})

test("null as argument", function (assert) {
    var a = { foo: "bar" }
    var b = null
    var c = void 0

    assert.deepEqual(extend(b, a, c), { foo: "bar" })
    assert.end()
})

test("mutable", function (assert) {
    var a = { foo: "bar" }

    mutableExtend(a, { bar: "baz" })

    assert.equal(a.bar, "baz")
    assert.end()
})

test("null prototype", function(assert) {
    var a = { a: "foo" }
    var b = Object.create(null)
    b.b = "bar";

    assert.deepEqual(extend(a, b), { a: "foo", b: "bar" })
    assert.end()
})

test("null prototype mutable", function (assert) {
    var a = { foo: "bar" }
    var b = Object.create(null)
    b.bar = "baz";

    mutableExtend(a, b)

    assert.equal(a.bar, "baz")
    assert.end()
})
<commit_msg>Add tests for protoype pollution<commit_after>var test = require("tape")
var extend = require("./")
var mutableExtend = require("./mutable")

test("merge", function(assert) {
    var a = { a: "foo" }
    var b = { b: "bar" }

    assert.deepEqual(extend(a, b), { a: "foo", b: "bar" })
    assert.end()
})

test("replace", function(assert) {
    var a = { a: "foo" }
    var b = { a: "bar" }

    assert.deepEqual(extend(a, b), { a: "bar" })
    assert.end()
})

test("undefined", function(assert) {
    var a = { a: undefined }
    var b = { b: "foo" }

    assert.deepEqual(extend(a, b), { a: undefined, b: "foo" })
    assert.deepEqual(extend(b, a), { a: undefined, b: "foo" })
    assert.end()
})

test("handle 0", function(assert) {
    var a = { a: "default" }
    var b = { a: 0 }

    assert.deepEqual(extend(a, b), { a: 0 })
    assert.deepEqual(extend(b, a), { a: "default" })
    assert.end()
})

test("is immutable", function (assert) {
    var record = {}

    extend(record, { foo: "bar" })
    assert.equal(record.foo, undefined)
    assert.end()
})

test("null as argument", function (assert) {
    var a = { foo: "bar" }
    var b = null
    var c = void 0

    assert.deepEqual(extend(b, a, c), { foo: "bar" })
    assert.end()
})

test("mutable", function (assert) {
    var a = { foo: "bar" }

    mutableExtend(a, { bar: "baz" })

    assert.equal(a.bar, "baz")
    assert.end()
})

test("null prototype", function(assert) {
    var a = { a: "foo" }
    var b = Object.create(null)
    b.b = "bar";

    assert.deepEqual(extend(a, b), { a: "foo", b: "bar" })
    assert.end()
})

test("null prototype mutable", function (assert) {
    var a = { foo: "bar" }
    var b = Object.create(null)
    b.bar = "baz";

    mutableExtend(a, b)

    assert.equal(a.bar, "baz")
    assert.end()
})

test("prototype pollution", function (assert) {
    var a = {}
    var maliciousPayload = '{"__proto__":{"oops":"It works!"}}'

    assert.strictEqual(a.oops, undefined)
    extend({}, maliciousPayload)
    assert.strictEqual(a.oops, undefined)
    assert.end()
})

test("prototype pollution mutable", function (assert) {
    var a = {}
    var maliciousPayload = '{"__proto__":{"oops":"It works!"}}'

    assert.strictEqual(a.oops, undefined)
    mutableExtend({}, maliciousPayload)
    assert.strictEqual(a.oops, undefined)
    assert.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 10:39:04<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|>