<commit_before>'use strict'

const l = require('lodash')
const moment = require('moment-timezone')
const validate = require('validate-fptf')
const tape = require('tape')
const sncf = require('./index')

const validID = (s) => (/^[A-Z]+$/.test(s) && s.length === 5)

tape.skip('sncf.stations', (t) => {
	sncf.stations('Frankfurt').then((stations) => {
		stations.forEach(s => validate(s))
		t.ok(stations.length > 0, 'stations length')
		const [ff] = stations
		t.ok(ff.id === 'DEFRA', 'station id')
		t.ok(ff.name === 'Francfort (Frankfurt - toutes gares)', 'station name')
		t.end()
	})
	.catch(t.ifError)
})

tape('sncf.journeys', (t) => {
	sncf.journeys("DEFRA", "FRPAR", moment.tz("Europe/Paris").add(3, "days").startOf('day').add(7, "hours").toDate()).then(journeys => {
		t.ok(journeys.length > 0, 'journeys length')

		for (let journey of journeys) {
			validate(journey)

			t.ok(journey.legs[0].origin.substr(0, 3) === "DEF", 'origin')
			t.ok(journey.legs[journey.legs.length-1].destination.substr(0, 3) === "FRP", 'destination')

			t.ok(['DB', 'SN', 'CF'].includes(journey.legs[0].operator), 'leg operator')

			t.ok(journey.price.amount > 0, 'price amount')
			t.ok(journey.price.currency === 'EUR', 'price currency')
			t.ok(journey.price.fares.length > 0, 'price fares length')
			t.ok(journey.price.fares[0].price.amount > 0, 'price fare price amount')
			t.ok(journey.price.fares[0].price.currency === 'EUR', 'price fare price currency')
		}

		t.end()
	})
	.catch(t.ifError)
})

tape.skip('sncf.prices', (t) => {
	sncf.prices("DEFRA", "FRPAR", moment.tz("Europe/Paris").add(1, "months").toDate()).then(prices => {
		t.ok(prices.length >= 28, 'prices length')
		t.ok(l.isDate(new Date(prices[0].date)) && +new Date(prices[0].date) > +new Date(), 'price date')
		t.ok(prices[0].price.amount > 0, 'price price amount')
		t.ok(prices[0].price.currency === 'EUR', 'price price currency')

		t.end()
	})
	.catch(t.ifError)
})
<commit_msg>un-skip tests<commit_after>'use strict'

const l = require('lodash')
const moment = require('moment-timezone')
const validate = require('validate-fptf')
const tape = require('tape')
const sncf = require('./index')

const validID = (s) => (/^[A-Z]+$/.test(s) && s.length === 5)

tape('sncf.stations', (t) => {
	sncf.stations('Frankfurt').then((stations) => {
		stations.forEach(s => validate(s))
		t.ok(stations.length > 0, 'stations length')
		const [ff] = stations
		t.ok(ff.id === 'DEFRA', 'station id')
		t.ok(ff.name === 'Francfort (Frankfurt - toutes gares)', 'station name')
		t.end()
	})
	.catch(t.ifError)
})

tape('sncf.journeys', (t) => {
	sncf.journeys("DEFRA", "FRPAR", moment.tz("Europe/Paris").add(3, "days").startOf('day').add(7, "hours").toDate()).then(journeys => {
		t.ok(journeys.length > 0, 'journeys length')

		for (let journey of journeys) {
			validate(journey)

			t.ok(journey.legs[0].origin.substr(0, 3) === "DEF", 'origin')
			t.ok(journey.legs[journey.legs.length-1].destination.substr(0, 3) === "FRP", 'destination')

			t.ok(['DB', 'SN', 'CF'].includes(journey.legs[0].operator), 'leg operator')

			t.ok(journey.price.amount > 0, 'price amount')
			t.ok(journey.price.currency === 'EUR', 'price currency')
			t.ok(journey.price.fares.length > 0, 'price fares length')
			t.ok(journey.price.fares[0].price.amount > 0, 'price fare price amount')
			t.ok(journey.price.fares[0].price.currency === 'EUR', 'price fare price currency')
		}

		t.end()
	})
	.catch(t.ifError)
})

tape('sncf.prices', (t) => {
	sncf.prices("DEFRA", "FRPAR", moment.tz("Europe/Paris").add(1, "months").toDate()).then(prices => {
		t.ok(prices.length >= 28, 'prices length')
		t.ok(l.isDate(new Date(prices[0].date)) && +new Date(prices[0].date) > +new Date(), 'price date')
		t.ok(prices[0].price.amount > 0, 'price price amount')
		t.ok(prices[0].price.currency === 'EUR', 'price price currency')

		t.end()
	})
	.catch(t.ifError)
})
<|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-12-4 01:53: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|>


<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 09:38: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>describe('fittings', function () {
  'use strict';

  process.env.DIAGNOSTICS = 'fittings';

  var Fittings = require('./')
    , assume = require('assume');

  //
  // All Fitting instances require a `name` attribute. Instead of adding it to
  // each test, we just pre-define it on our customized fittings instance.
  //
  Fittings = Fittings.extend({
    name: 'fixture'
  });

  it('is exported as a function', function () {
    assume(Fittings).is.a('function');
  });

  it('writes to stdout when calling a method that is not overrided', function (next) {
    var write = process.stdout.write;

    process.stdout.write = function (data) {
      process.stdout.write = write;

      assume(data).includes('Missing override');
      assume(data).includes('`.template`');

      next();
    };

    var framework = new Fittings();

    framework.get('library');
    framework.get('template');
  });

  describe("#get", function () {
    it('returns an array for library', function () {
      var Framework = Fittings.extend({
        library: require.resolve('./test.js')
      }), f = new Framework();

      assume(f.get('library')).is.a('array');
      assume(f.get('library')).has.length(1);
    });

    it('attempts to resolve the library if its not an absolute path', function () {
      var Framework = Fittings.extend({
        library: './test.js'
      }), f = new Framework();

      assume(f.get('library')).has.length(1);
      assume(f.get('library')[0]).deep.equals({
        path: require.resolve('./test.js'),
        expose: 'test'
      });
    });

    it('executes the library function', function () {
      var Framework = Fittings.extend({
        library: function () {
          return ['1'];
        }
      }), f = new Framework();

      assume(f.get('library')[0]).deep.equals({
        path: '1',
        expose: '1'
      });
    });

    it('leaves arrays alone for now', function () {
      var Framework = Fittings.extend({
        library: ['./test.js']
      }), f = new Framework();

      assume(f.get('library')).has.length(1);
      assume(f.get('library')[0]).deep.equals({
        path: './test.js',
        expose: 'test'
      });
    });

    it('accepts objects', function () {
      var Framework = Fittings.extend({
        library: { path: './test.js', expose: 'moo' }
      }), f = new Framework();

      assume(f.get('library')).has.length(1);
      assume(f.get('library')[0]).deep.equals({
        path: './test.js',
        expose: 'moo'
      });
    });

    it('will replace {fittings:tags}', function () {
      /* istanbul ignore next */
      function woop(){ console.log('lol'); }

      var Framework = Fittings.extend({
        library: ['./test.js'],
        template: 'global[{fittings:hash}] = {fittings:client};'
      }), f = new Framework()
      , data = { hash: '"moo"', client: woop.toString() };

      assume(f.get('template', data)).equals('global["moo"] = '+ woop.toString() +';');
    });

    it('will replace multiple occurrences', function () {
      /* istanbul ignore next */
      function woop(){ console.log('lol'); }

      var Framework = Fittings.extend({
        template: '{fittings:hash} {fittings:hash}'
      }), f = new Framework()
      , data = { hash: '"moo"' };

      assume(f.get('template', data)).equals('"moo" "moo"');
    });

    it('assumes that functions replace stuff them selfs', function () {
      var Framework = Fittings.extend({
        library: ['./test.js'],
        template: function (dataset) {
          assume(dataset).deep.equals(data);
          return 'foo';
        }
      }), f = new Framework()
      , data = { what: 'ever', data: 'you', want: 'here' };

      assume(f.get('template', data)).equals('foo');
    });

    it('leaves $ signs alone', function () {
      function example() {
        if (!('$' in global)) return;

        console.log($);
      }

      var Framework = Fittings.extend({
        library: ['./test.js'],
        template: 'global[{fittings:hash}] = {fittings:client};'
      }), f = new Framework()
      , data = { hash: '"moo"', client: example.toString() };

      assume(f.get('template', data)).includes("'$'");
    });

    it('executes the set functions with context set to fittings', function (next) {
      var Framework = Fittings.extend({
        library: function () {
          assume(this).equals(f);
          next();

          return __filename;
        },
        template: function (dataset) {
          assume(this).equals(f);

          return f.get('library')[0].expose;
        }
      }), f = new Framework();

      assume(f.get('template')).equals('test');
    });
  });

  describe('.template', function () {
    it('returns a string', function () {
      var Framework = Fittings.extend({
        template: 'woop'
      }), f = new Framework();

      assume(f.get('template')).is.a('string');
      assume(f.get('template')).equals('woop');
    });
  });

  describe('.plugin', function () {
    it('returns a string', function () {
      var Framework = Fittings.extend({
        plugin: 'woop'
      }), f = new Framework();

      assume(f.get('plugin')).is.a('string');
      assume(f.get('plugin')).equals('woop');
    });
  });

  describe('.bootstrap', function () {
    it('returns a string', function () {
      var Framework = Fittings.extend({
        bootstrap: 'woop'
      }), f = new Framework();

      assume(f.get('bootstrap')).is.a('string');
      assume(f.get('bootstrap')).equals('woop');
    });
  });

  describe('.fragment', function () {
    it('returns a string', function () {
      var Framework = Fittings.extend({
        fragment: 'woop'
      }), f = new Framework();

      assume(f.get('fragment')).is.a('string');
      assume(f.get('fragment')).equals('woop');
    });
  });

  describe('.library', function () {
    it('returns an array', function () {
      var Framework = Fittings.extend({
        library: function () { return []; }
      }), f = new Framework();

      assume(f.get('library')).is.a('array');
    });
  });

  describe('.middleware', function () {
    it('returns an object for functions', function () {
      var Framework = Fittings.extend({
        middleware: function () { return {}; }
      }), f = new Framework();

      assume(f.get('middleware')).is.a('object');
    });

    it('returns an object', function () {
      var Framework = Fittings.extend({
        middleware: {}
      }), f = new Framework();

      assume(f.get('middleware')).is.a('object');
    });
  });

  describe('.use', function () {
    it('returns an object for functions', function () {
      var Framework = Fittings.extend({
        use: function () { return {}; }
      }), f = new Framework();

      assume(f.get('use')).is.a('object');
    });

    it('returns an object', function () {
      var Framework = Fittings.extend({
        use: {}
      }), f = new Framework();

      assume(f.get('use')).is.a('object');
    });
  });

  describe('integration', function () {
    var port = 2024
      , app;

    this.timeout(30000);

    beforeEach(function (next) {
      app = require('bigpipe').createServer({
        dist: '/tmp/dist',
        port: port++,
      });

      app.once('listening', next);
      app.once('error', next);
    });

    afterEach(function () {
      app.destroy();
    });

    it('automatically adds the set middleware', function () {
      /* istanbul ignore next */
      function middleware(req, res, next) {
        next();
      }

      var Framework = Fittings.extend({
        middleware: {
          foo: middleware
        }
      });

      assume(app.middleware.indexOf('foo')).equals(-1);
      assume(app.framework(Framework)).equals(app);
      assume(app._framework).is.instanceOf(Framework);
      assume(app.middleware.indexOf('foo')).does.not.equal(-1);
    });

    it('automatically adds the set plugin', function (next) {
      var Framework = Fittings.extend({
        use: {
          hello: {
            server: function (server) {
              assume(app).equals(server);
              next();
            }
          }
        }
      });

      assume(app.framework(Framework)).equals(app);
    });
  });
});
<commit_msg>[test] Adding tests for the `on` method<commit_after>describe('fittings', function () {
  'use strict';

  process.env.DIAGNOSTICS = 'fittings';

  var Fittings = require('./')
    , assume = require('assume');

  //
  // All Fitting instances require a `name` attribute. Instead of adding it to
  // each test, we just pre-define it on our customized fittings instance.
  //
  Fittings = Fittings.extend({
    name: 'fixture'
  });

  it('is exported as a function', function () {
    assume(Fittings).is.a('function');
  });

  it('writes to stdout when calling a method that is not overrided', function (next) {
    var write = process.stdout.write;

    process.stdout.write = function (data) {
      process.stdout.write = write;

      assume(data).includes('Missing override');
      assume(data).includes('`.template`');

      next();
    };

    var framework = new Fittings();

    framework.get('library');
    framework.get('template');
  });

  describe("#get", function () {
    it('returns an array for library', function () {
      var Framework = Fittings.extend({
        library: require.resolve('./test.js')
      }), f = new Framework();

      assume(f.get('library')).is.a('array');
      assume(f.get('library')).has.length(1);
    });

    it('attempts to resolve the library if its not an absolute path', function () {
      var Framework = Fittings.extend({
        library: './test.js'
      }), f = new Framework();

      assume(f.get('library')).has.length(1);
      assume(f.get('library')[0]).deep.equals({
        path: require.resolve('./test.js'),
        expose: 'test'
      });
    });

    it('executes the library function', function () {
      var Framework = Fittings.extend({
        library: function () {
          return ['1'];
        }
      }), f = new Framework();

      assume(f.get('library')[0]).deep.equals({
        path: '1',
        expose: '1'
      });
    });

    it('leaves arrays alone for now', function () {
      var Framework = Fittings.extend({
        library: ['./test.js']
      }), f = new Framework();

      assume(f.get('library')).has.length(1);
      assume(f.get('library')[0]).deep.equals({
        path: './test.js',
        expose: 'test'
      });
    });

    it('accepts objects', function () {
      var Framework = Fittings.extend({
        library: { path: './test.js', expose: 'moo' }
      }), f = new Framework();

      assume(f.get('library')).has.length(1);
      assume(f.get('library')[0]).deep.equals({
        path: './test.js',
        expose: 'moo'
      });
    });

    it('will replace {fittings:tags}', function () {
      /* istanbul ignore next */
      function woop(){ console.log('lol'); }

      var Framework = Fittings.extend({
        library: ['./test.js'],
        template: 'global[{fittings:hash}] = {fittings:client};'
      }), f = new Framework()
      , data = { hash: '"moo"', client: woop.toString() };

      assume(f.get('template', data)).equals('global["moo"] = '+ woop.toString() +';');
    });

    it('will replace multiple occurrences', function () {
      /* istanbul ignore next */
      function woop(){ console.log('lol'); }

      var Framework = Fittings.extend({
        template: '{fittings:hash} {fittings:hash}'
      }), f = new Framework()
      , data = { hash: '"moo"' };

      assume(f.get('template', data)).equals('"moo" "moo"');
    });

    it('assumes that functions replace stuff them selfs', function () {
      var Framework = Fittings.extend({
        library: ['./test.js'],
        template: function (dataset) {
          assume(dataset).deep.equals(data);
          return 'foo';
        }
      }), f = new Framework()
      , data = { what: 'ever', data: 'you', want: 'here' };

      assume(f.get('template', data)).equals('foo');
    });

    it('leaves $ signs alone', function () {
      function example() {
        if (!('$' in global)) return;

        console.log($);
      }

      var Framework = Fittings.extend({
        library: ['./test.js'],
        template: 'global[{fittings:hash}] = {fittings:client};'
      }), f = new Framework()
      , data = { hash: '"moo"', client: example.toString() };

      assume(f.get('template', data)).includes("'$'");
    });

    it('executes the set functions with context set to fittings', function (next) {
      var Framework = Fittings.extend({
        library: function () {
          assume(this).equals(f);
          next();

          return __filename;
        },
        template: function (dataset) {
          assume(this).equals(f);

          return f.get('library')[0].expose;
        }
      }), f = new Framework();

      assume(f.get('template')).equals('test');
    });
  });

  describe('.template', function () {
    it('returns a string', function () {
      var Framework = Fittings.extend({
        template: 'woop'
      }), f = new Framework();

      assume(f.get('template')).is.a('string');
      assume(f.get('template')).equals('woop');
    });
  });

  describe('.plugin', function () {
    it('returns a string', function () {
      var Framework = Fittings.extend({
        plugin: 'woop'
      }), f = new Framework();

      assume(f.get('plugin')).is.a('string');
      assume(f.get('plugin')).equals('woop');
    });
  });

  describe('.bootstrap', function () {
    it('returns a string', function () {
      var Framework = Fittings.extend({
        bootstrap: 'woop'
      }), f = new Framework();

      assume(f.get('bootstrap')).is.a('string');
      assume(f.get('bootstrap')).equals('woop');
    });
  });

  describe('.fragment', function () {
    it('returns a string', function () {
      var Framework = Fittings.extend({
        fragment: 'woop'
      }), f = new Framework();

      assume(f.get('fragment')).is.a('string');
      assume(f.get('fragment')).equals('woop');
    });
  });

  describe('.library', function () {
    it('returns an array', function () {
      var Framework = Fittings.extend({
        library: function () { return []; }
      }), f = new Framework();

      assume(f.get('library')).is.a('array');
    });
  });

  describe('.middleware', function () {
    it('returns an object for functions', function () {
      var Framework = Fittings.extend({
        middleware: function () { return {}; }
      }), f = new Framework();

      assume(f.get('middleware')).is.a('object');
    });

    it('returns an object', function () {
      var Framework = Fittings.extend({
        middleware: {}
      }), f = new Framework();

      assume(f.get('middleware')).is.a('object');
    });
  });

  describe('.use', function () {
    it('returns an object for functions', function () {
      var Framework = Fittings.extend({
        use: function () { return {}; }
      }), f = new Framework();

      assume(f.get('use')).is.a('object');
    });

    it('returns an object', function () {
      var Framework = Fittings.extend({
        use: {}
      }), f = new Framework();

      assume(f.get('use')).is.a('object');
    });
  });

  describe('integration', function () {
    var port = 2024
      , app;

    this.timeout(30000);

    beforeEach(function (next) {
      app = require('bigpipe').createServer({
        dist: '/tmp/dist',
        port: port++,
      });

      app.once('listening', next);
      app.once('error', next);
    });

    afterEach(function () {
      app.destroy();
    });

    it('automatically adds the set middleware', function () {
      /* istanbul ignore next */
      function middleware(req, res, next) {
        next();
      }

      var Framework = Fittings.extend({
        middleware: {
          foo: middleware
        }
      });

      assume(app.middleware.indexOf('foo')).equals(-1);
      assume(app.framework(Framework)).equals(app);
      assume(app._framework).is.instanceOf(Framework);
      assume(app.middleware.indexOf('foo')).does.not.equal(-1);
    });

    it('automatically adds the set plugin', function (next) {
      var Framework = Fittings.extend({
        use: {
          hello: {
            server: function (server) {
              assume(app).equals(server);
              next();
            }
          }
        }
      });

      assume(app.framework(Framework)).equals(app);
    });
  });

  describe('#on', function () {
    it('exposes the `on` method', function () {
      assume(Fittings.on).is.a('function');
    });

    it('assigns custom Fittings to module.exports', function () {
      var x = module.exports
        , Y = Fittings.extend({ woop: 'woop' });

      assume(Y.on(module)).equals(Y);
      assume(module.exports).equals(Y);

      module.exports = x;
    });
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var nodeo = require('./lib/nodeo.js');

var population_size = 16;
var chromosome_size = 16;
var population = new Array;
var fitness_of = new Object;

for ( var i = 0; i < population_size; i ++ )  {
    var chromosome = nodeo.random( chromosome_size );
    population.push( chromosome );
    var is_match = chromosome.match(/[01]+/g );
    fitness_of[chromosome] =  nodeo.max_ones( chromosome );
    var new_chromosome = nodeo.mutate(chromosome);
    console.log(new_chromosome+"\n"+chromosome+"\n");
    if ( i > 0 ) {
	var crossed = new Array;
	crossed = nodeo.crossover( population[i-1],chromosome);
	console.log(population[i-1]+"-"+chromosome + "\n"+crossed[0] + "-" + crossed[1]);
    }
}

var eo = new nodeo.Nodeo( { population_size: population_size,
			    chromosome_size: chromosome_size,
			    fitness_func: nodeo.max_ones } );
console.log(eo);<commit_msg>Adds tournament selection<commit_after>#!/usr/bin/env node

var nodeo = require('./lib/nodeo.js');

var population_size = 16;
var chromosome_size = 16;
var population = new Array;
var fitness_of = new Object;
var tournament_size = 2;
var pool_size = population_size;

for ( var i = 0; i < population_size; i ++ )  {
    var chromosome = nodeo.random( chromosome_size );
    population.push( chromosome );
    var is_match = chromosome.match(/[01]+/g );
    fitness_of[chromosome] =  nodeo.max_ones( chromosome );
    var new_chromosome = nodeo.mutate(chromosome);
    console.log(new_chromosome+"\n"+chromosome+"\n");
    if ( i > 0 ) {
	var crossed = new Array;
	crossed = nodeo.crossover( population[i-1],chromosome);
	console.log(population[i-1]+"-"+chromosome + "\n"+crossed[0] + "-" + crossed[1]);
    }
}

var eo = new nodeo.Nodeo( { population_size: population_size,
			    chromosome_size: chromosome_size,
			    fitness_func: nodeo.max_ones } );
console.log(eo);
var chosen = eo.tournament_selection( tournament_size, pool_size);

console.log(chosen);<|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-6 08:38: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>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:18:06<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

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

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


<commit_before>function runTest(master, testId) {
	if (testId === '1') {
		if (master.activeWindow.type === 'channel') {
			var channelOrQuery = master.activeWindow.object;

			master.user.applyStateChange('Join', master.activeWindow.windowPath, {
				nick: 'wezirc',
				user: 'user',
				host: 'host'
			});
		} else {
			master.showError('Must be used in a channel');
		}
	}
}

module.exports.runTest = runTest;
<commit_msg>added a test to join 1000 clients to a channel<commit_after>function runTest(master, testId) {
	if (testId === '1') {
		if (master.activeWindow.type === 'channel') {
			master.user.applyStateChange('Join', master.activeWindow.windowPath, {
				nick: 'wezirc',
				user: 'user',
				host: 'host'
			});
		} else {
			master.showError('Must be used in a channel');
		}
	} else if (testId === '2') {
		if (master.activeWindow.type === 'channel') {
			for (var i = 0; i < 1000; i++) {
				master.user.applyStateChange('Join', master.activeWindow.windowPath, {
					nick: 'u' + i,
					user: 'user',
					host: 'host'
				});
			}
		} else {
			master.showError('Must be used in a channel');
		}
	}
}

module.exports.runTest = runTest;
<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');
const HttpError = require('.');

describe('HttpError', function describe() {
  it('returns new HttpError', function it() {
    const httpError = new HttpError('Not Found', 404);

    assert.equal(httpError.message, 'Not Found');
    assert.equal(httpError.code, 404);
  });

  it('returns json representation', function it() {
    const httpError = new HttpError('Not Found', 404);

    assert.deepEqual(httpError.toJSON(), {
      code: 404,
      message: 'Not Found',
    });
  });

  it('returns string representation', function it() {
    const httpError = new HttpError('Not Found', 404);

    assert.equal(httpError.toString(), '404: Not Found');
  });

  it('wraps existing error', function it() {
    const error = new Error('Original Error');
    const httpError = new HttpError('Not Found', 404, error);

    assert.deepEqual(error, httpError.error);
  });
});
<commit_msg>chore(use): use arrow callback functions<commit_after>'use strict';

const assert = require('assert');
const HttpError = require('.');

describe('HttpError', () => {
  it('returns new HttpError', () => {
    const httpError = new HttpError('Not Found', 404);

    assert.equal(httpError.message, 'Not Found');
    assert.equal(httpError.code, 404);
  });

  it('returns json representation', () => {
    const httpError = new HttpError('Not Found', 404);

    assert.deepEqual(httpError.toJSON(), {
      code: 404,
      message: 'Not Found',
    });
  });

  it('returns string representation', () => {
    const httpError = new HttpError('Not Found', 404);

    assert.equal(httpError.toString(), '404: Not Found');
  });

  it('wraps existing error', () => {
    const error = new Error('Original Error');
    const httpError = new HttpError('Not Found', 404, error);

    assert.deepEqual(error, httpError.error);
  });
});
<|endoftext|>


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

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

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

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

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


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

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

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

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

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


<commit_before><commit_msg>Remove redundant test file<commit_after><|endoftext|>


<commit_before>var assert = require('assert');
var Store = require('./index.js').Store;
var StoreItem = require('./index.js').StoreItem;
var StoreCollection = require('./index.js').StoreCollection;

describe('The reactItemButton component', function() {

  describe('when no props are given', function() {
    var store, storeI, storeC;

    beforeEach(function(done) {
      store = new StoreCollection({
        identity: "user"
      });
      storeI = new StoreItem({
        identity: "user",
        value: {id: 5}
      });
      storeC = new StoreCollection({
        identity: "user",
        items: []
      });
      done()
    });

    it('check url for store class', function() {
      assert.equal(store.url, '/user');
    });
    it('check url for store Item class', function() {
      assert.equal(storeI.url, '/user/5');
    });
    it('check url for store Collection class', function() {
      assert.equal(storeC.url, '/user');
    });

  });

});
<commit_msg>add test<commit_after>var assert = require('assert');
var Store = require('./index.js').Store;
var StoreItem = require('./index.js').StoreItem;
var StoreCollection = require('./index.js').StoreCollection;

describe('Simulate wevsocket events with onChange function', function() {

  describe('When use StoreCollection', function() {
    var store;
    before(function(done) {
      store = new StoreCollection({
        identity: "user"
      });
      done()
    });
    it('url should equal to /user', function() {
      assert.equal(store.url, '/user');
    });
    it('should event sync is a function', function() {
      assert.equal(typeof store._events.sync, 'function');
    });
    it('should emit an created event and have 2 records', function() {
      store.add({name:'Mike', id:1});
      store.on('add', function(data){
        assert.equal(data[0].name, 'Mike');
        assert.equal(data.length, 2);
      });
      store.onChange({verb: 'created', data: {id:2, name:"John"}});
    });
    it('should emit a updated event and return an object have Name is Johnny', function() {
      store.on('update', function(data){
        assert.equal(data[1].name, 'Johnny');
        assert.equal(data.length, 3);
      });
      store.onChange({verb: 'updated', data: [{id:1, name:"Mike"}, {id:2, name:"Johnny"}, {id:3, name:"Paul"}]});
    });
    it('should emit a desroyed event and have 2 record', function() {
      store.on('remove', function(data){
        assert.equal(data.length, 2);
      });
      store.onChange({verb: 'destroyed', id: 1});
    });
  });

  describe('When use StoreItem', function() {
    var storeI;
    before(function(done) {
      storeI = new StoreItem({
        identity: "user",
        value: {id: 5, name: 'Mike'}
      });
      done()
    });
    it('url should equal to /user/5', function() {
      assert.equal(storeI.url, '/user/5');
    });
    it('should emit a updated event and return an object have Name is Johnny', function() {
      storeI.on('update', function(data){
        assert.equal(data.name, 'Johnny');
      });
      storeI.onChange({verb: 'updated', data:{name:"Johnny"}});
    });
  });

});
<|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-12-4 03:13: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|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-24 01:22:21<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-6-9 17:49:26<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 assert = require("assert");
var fs = require("fs");
var path = require("path");
var stream = require("stream");
var util = require("util");
var bufferEquals = require("buffer-equals");
var iconv = require("iconv-lite");
var convertNewline = require("./");

//
// const.
//
var PACKAGE_NAME = "convert-newline";
var UTF8 = "utf8";
var SHIFT_JIS = "shift_jis";

//
// Test Data
//
function getStringTestData() {
	return {
		cr: "aaa\rbbb\rccc\r",
		crlf: "aaa\r\nbbb\r\nccc\r\n",
		lf: "aaa\nbbb\nccc\n"
	};
}

function getUTF8FileTestData() {
	return {
		cr: fs.readFileSync(path.join("data", UTF8, "cr.txt")),
		crlf: fs.readFileSync(path.join("data", UTF8, "crlf.txt")),
		lf: fs.readFileSync(path.join("data", UTF8, "lf.txt"))
	};

}

function getUTF8BufferTestData() {
	return {
		cr: new Buffer("aaa\rbbb\rccc\r"),
		crlf: new Buffer("aaa\r\nbbb\r\nccc\r\n"),
		lf: new Buffer("aaa\nbbb\nccc\n")
	};
}

function getShiftJISFileTestData() {
	return {
		cr: fs.readFileSync(path.join("data", SHIFT_JIS, "cr.txt")),
		crlf: fs.readFileSync(path.join("data", SHIFT_JIS, "crlf.txt")),
		lf: fs.readFileSync(path.join("data", SHIFT_JIS, "lf.txt"))
	};
}

function getShiftJISBufferTestData() {
	// each hiragana letter is repeated 3 times.
	var HIRAGANA_LETTER_A = [0x82, 0xa0, 0x82, 0xa0, 0x82, 0xa0];
	var HIRAGANA_LETTER_I = [0x82, 0xa2, 0x82, 0xa2, 0x82, 0xa2];
	var HIRAGANA_LETTER_U = [0x82, 0xa4, 0x82, 0xa4, 0x82, 0xa4];
	var CR = 0x0d;
	var LF = 0x0a;

	return {
		cr: new Buffer([].concat(HIRAGANA_LETTER_A, CR, HIRAGANA_LETTER_I, CR, HIRAGANA_LETTER_U, CR)),
		crlf: new Buffer([].concat(HIRAGANA_LETTER_A, CR, LF, HIRAGANA_LETTER_I, CR, LF, HIRAGANA_LETTER_U, CR, LF)),
		lf: new Buffer([].concat(HIRAGANA_LETTER_A, LF, HIRAGANA_LETTER_I, LF, HIRAGANA_LETTER_U, LF))
	};
}

//
// Tests
//
describe(PACKAGE_NAME, function() {
	it("should throw for invalid option", function() {
		assert.throws(function() {
			convertNewline("\n");
		}, /Unsupported `newline`/);
	});

	it("should use \"lf\" as default option", function() {
		var testData = getStringTestData();
		var converter = convertNewline().string();
		var newlinews = Object.keys(testData);
		newlinews.forEach(function(fromNewline) {
			assert.strictEqual(converter(testData[fromNewline]), testData.lf);
		});
	});

	describe("in string mode", function() {
		var testData = getStringTestData();
		var newlinews = Object.keys(testData);
		newlinews.forEach(function(toNewline) {
			newlinews.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function() {
					var converter = convertNewline(toNewline).string();
					var reference = testData[toNewline];
					assert.strictEqual(converter(testData[fromNewline]), reference);
				});
			});
		});
	});

	describe("in buffer mode (simple)", function() {
		var testData = getUTF8BufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function(toNewline) {
			newlines.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function() {
					var converter = convertNewline(toNewline).buffer();
					var reference = testData[toNewline];
					assert.ok(bufferEquals(converter(testData[fromNewline]), reference));
				});
			});
		});
	});

	describe("in buffer mode (iconv)", function() {
		var testData = getShiftJISBufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function(toNewline) {
			newlines.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function() {
					var converter = convertNewline(toNewline, SHIFT_JIS).buffer();
					var reference = testData[toNewline];
					assert.ok(bufferEquals(converter(testData[fromNewline]), reference));
				});
			});
		});
	});

	describe("test code (utf8)", function() {
		var testData = getUTF8FileTestData();
		var referenceData = getUTF8BufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function(newline1) {
			it("should load test data correctly", function() {
				newlines.forEach(function (newline2) {
					var target = testData[newline2];
					var reference = referenceData[newline1];
					if (newline1 === newline2) {
						assert.ok(bufferEquals(target, reference), util.format("%s test data is loaded correctly", newline1));
					} else {
						assert.ok(!bufferEquals(target, reference), util.format("%s test data is not same as %s correctly", newline1, newline2));
					}
				});
			});
		});
	});

	describe("test code (utf8)", function() {
		var testData = getShiftJISFileTestData();
		var referenceData = getShiftJISBufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function(newline1) {
			it("should load test data correctly", function() {
				newlines.forEach(function (newline2) {
					var target = testData[newline2];
					var reference = referenceData[newline1];
					if (newline1 === newline2) {
						assert.ok(bufferEquals(target, reference), util.format("%s test data is loaded correctly", newline1));
					} else {
						assert.ok(!bufferEquals(target, reference), util.format("%s test data is not same as %s correctly", newline1, newline2));
					}
				});
			});
		});
	});

	describe("in stream mode (simple)", function() {
		function testStream(toNewline, fromNewline, reference, done) {
			var fromFilename = path.join("data", UTF8, fromNewline + ".txt");
			var targetFilename = fromFilename + "." + toNewline;
			var options = {
				encoding: UTF8
			};

			var reader = fs.createReadStream(fromFilename, options);
			var writer = fs.createWriteStream(targetFilename);
			var converter = convertNewline(toNewline).stream();

			writer.on("finish", function() {
				var target = fs.readFileSync(targetFilename);
				assert.ok(bufferEquals(target, reference));
				done();
			});

			reader
				.pipe(converter)
				.pipe(writer);
		}

		var references = getUTF8BufferTestData();
		var newlines = Object.keys(references);
		newlines.forEach(function (toNewline) {
			newlines.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function(done) {
					testStream(toNewline, fromNewline, references[toNewline], done);
				});
			});
		});

		it("should throw an error for non string stream", function(done) {
			var newline = "lf";
			var fromFilename = path.join("data", UTF8, newline + ".txt");
			var reader = fs.createReadStream(fromFilename);
			var converter = convertNewline(newline).stream();

			converter.on("error", function (err) {
				assert.ok(err instanceof Error);
				assert.strictEqual(err.message, util.format("%s needs string as its input.", PACKAGE_NAME));
				done();
			});
			reader
				.pipe(converter);
		});

		it("should treat a sequence of \\r and \\n as a newline", function(done) {
			var newline = "lf";
			var converter = convertNewline(newline).stream();
			var converted = [];
			converter.on("data", function (chunk) {
				converted.push(chunk);
			});
			converter.on("end", function () {
				assert.deepEqual(converted, ["aaa", "\n\nbbb", "\nccc", "\n"]);
				done();
			});

			var reader = new stream.Readable({
				encoding: UTF8
			});
			["aaa\r", "\rbbb\r", "\nccc\r"].forEach(function(item) {
				reader.push(item, UTF8);
			});
			reader.push(null);
			reader
				.pipe(converter);
		});

	});

	describe("in stream mode (iconv)", function() {
		function testStream(toNewline, fromNewline, reference, done) {
			var fromFilename = path.join("data", SHIFT_JIS, fromNewline + ".txt");
			var targetFilename = fromFilename + "." + toNewline;

			var reader = fs.createReadStream(fromFilename);
			var writer = fs.createWriteStream(targetFilename);
			var converter = convertNewline(toNewline).stream();

			writer.on("finish", function() {
				var target = fs.readFileSync(targetFilename);
				assert.ok(bufferEquals(target, reference));
				done();
			});

			reader
				.pipe(iconv.decodeStream(SHIFT_JIS))
				.pipe(converter)
				.pipe(iconv.encodeStream(SHIFT_JIS))
				.pipe(writer);
		}

		var references = getShiftJISBufferTestData();
		var newlines = Object.keys(references);
		newlines.forEach(function (toNewline) {
			newlines.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function(done) {
					testStream(toNewline, fromNewline, references[toNewline], done);
				});
			});
		});
	});
});
<commit_msg>Use variable names "actual"/"expected" in test code<commit_after>"use strict";
var assert = require("assert");
var fs = require("fs");
var path = require("path");
var stream = require("stream");
var util = require("util");
var bufferEquals = require("buffer-equals");
var iconv = require("iconv-lite");
var convertNewline = require("./");

//
// const.
//
var PACKAGE_NAME = "convert-newline";
var UTF8 = "utf8";
var SHIFT_JIS = "shift_jis";

//
// Test Data
//
function getStringTestData() {
	return {
		cr: "aaa\rbbb\rccc\r",
		crlf: "aaa\r\nbbb\r\nccc\r\n",
		lf: "aaa\nbbb\nccc\n"
	};
}

function getUTF8FileTestData() {
	return {
		cr: fs.readFileSync(path.join("data", UTF8, "cr.txt")),
		crlf: fs.readFileSync(path.join("data", UTF8, "crlf.txt")),
		lf: fs.readFileSync(path.join("data", UTF8, "lf.txt"))
	};

}

function getUTF8BufferTestData() {
	return {
		cr: new Buffer("aaa\rbbb\rccc\r"),
		crlf: new Buffer("aaa\r\nbbb\r\nccc\r\n"),
		lf: new Buffer("aaa\nbbb\nccc\n")
	};
}

function getShiftJISFileTestData() {
	return {
		cr: fs.readFileSync(path.join("data", SHIFT_JIS, "cr.txt")),
		crlf: fs.readFileSync(path.join("data", SHIFT_JIS, "crlf.txt")),
		lf: fs.readFileSync(path.join("data", SHIFT_JIS, "lf.txt"))
	};
}

function getShiftJISBufferTestData() {
	// each hiragana letter is repeated 3 times.
	var HIRAGANA_LETTER_A = [0x82, 0xa0, 0x82, 0xa0, 0x82, 0xa0];
	var HIRAGANA_LETTER_I = [0x82, 0xa2, 0x82, 0xa2, 0x82, 0xa2];
	var HIRAGANA_LETTER_U = [0x82, 0xa4, 0x82, 0xa4, 0x82, 0xa4];
	var CR = 0x0d;
	var LF = 0x0a;

	return {
		cr: new Buffer([].concat(HIRAGANA_LETTER_A, CR, HIRAGANA_LETTER_I, CR, HIRAGANA_LETTER_U, CR)),
		crlf: new Buffer([].concat(HIRAGANA_LETTER_A, CR, LF, HIRAGANA_LETTER_I, CR, LF, HIRAGANA_LETTER_U, CR, LF)),
		lf: new Buffer([].concat(HIRAGANA_LETTER_A, LF, HIRAGANA_LETTER_I, LF, HIRAGANA_LETTER_U, LF))
	};
}

//
// Tests
//
describe(PACKAGE_NAME, function() {
	it("should throw for invalid option", function() {
		assert.throws(function() {
			convertNewline("\n");
		}, /Unsupported `newline`/);
	});

	it("should use \"lf\" as default option", function() {
		var testData = getStringTestData();
		var converter = convertNewline().string();
		var newlinews = Object.keys(testData);
		newlinews.forEach(function(fromNewline) {
			assert.strictEqual(converter(testData[fromNewline]), testData.lf);
		});
	});

	describe("in string mode", function() {
		var testData = getStringTestData();
		var newlinews = Object.keys(testData);
		newlinews.forEach(function(toNewline) {
			newlinews.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function() {
					var converter = convertNewline(toNewline).string();
					var expected = testData[toNewline];
					assert.strictEqual(converter(testData[fromNewline]), expected);
				});
			});
		});
	});

	describe("in buffer mode (simple)", function() {
		var testData = getUTF8BufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function(toNewline) {
			newlines.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function() {
					var converter = convertNewline(toNewline).buffer();
					var expected = testData[toNewline];
					assert.ok(bufferEquals(converter(testData[fromNewline]), expected));
				});
			});
		});
	});

	describe("in buffer mode (iconv)", function() {
		var testData = getShiftJISBufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function(toNewline) {
			newlines.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function() {
					var converter = convertNewline(toNewline, SHIFT_JIS).buffer();
					var expected = testData[toNewline];
					assert.ok(bufferEquals(converter(testData[fromNewline]), expected));
				});
			});
		});
	});

	describe("test code (utf8)", function() {
		var testData = getUTF8FileTestData();
		var expectedData = getUTF8BufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function(newline1) {
			it("should load test data correctly", function() {
				newlines.forEach(function (newline2) {
					var actual = testData[newline2];
					var expected = expectedData[newline1];
					if (newline1 === newline2) {
						assert.ok(bufferEquals(actual, expected), util.format("%s test data is loaded correctly", newline1));
					} else {
						assert.ok(!bufferEquals(actual, expected), util.format("%s test data is not same as %s correctly", newline1, newline2));
					}
				});
			});
		});
	});

	describe("test code (utf8)", function() {
		var testData = getShiftJISFileTestData();
		var expectedData = getShiftJISBufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function(newline1) {
			it("should load test data correctly", function() {
				newlines.forEach(function (newline2) {
					var actual = testData[newline2];
					var expected = expectedData[newline1];
					if (newline1 === newline2) {
						assert.ok(bufferEquals(actual, expected), util.format("%s test data is loaded correctly", newline1));
					} else {
						assert.ok(!bufferEquals(actual, expected), util.format("%s test data is not same as %s correctly", newline1, newline2));
					}
				});
			});
		});
	});

	describe("in stream mode (simple)", function() {
		function testStream(toNewline, fromNewline, expected, done) {
			var fromFilename = path.join("data", UTF8, fromNewline + ".txt");
			var targetFilename = fromFilename + "." + toNewline;
			var options = {
				encoding: UTF8
			};

			var reader = fs.createReadStream(fromFilename, options);
			var writer = fs.createWriteStream(targetFilename);
			var converter = convertNewline(toNewline).stream();

			writer.on("finish", function() {
				var actual = fs.readFileSync(targetFilename);
				assert.ok(bufferEquals(actual, expected));
				done();
			});

			reader
				.pipe(converter)
				.pipe(writer);
		}

		var testData = getUTF8BufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function (toNewline) {
			newlines.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function(done) {
					testStream(toNewline, fromNewline, testData[toNewline], done);
				});
			});
		});

		it("should throw an error for non string stream", function(done) {
			var newline = "lf";
			var fromFilename = path.join("data", UTF8, newline + ".txt");
			var reader = fs.createReadStream(fromFilename);
			var converter = convertNewline(newline).stream();

			converter.on("error", function (err) {
				assert.ok(err instanceof Error);
				assert.strictEqual(err.message, util.format("%s needs string as its input.", PACKAGE_NAME));
				done();
			});
			reader
				.pipe(converter);
		});

		it("should treat a sequence of \\r and \\n as a newline", function(done) {
			var newline = "lf";
			var converter = convertNewline(newline).stream();
			var actual = [];
			converter.on("data", function (chunk) {
				actual.push(chunk);
			});
			converter.on("end", function () {
				assert.deepEqual(actual, ["aaa", "\n\nbbb", "\nccc", "\n"]);
				done();
			});

			var reader = new stream.Readable({
				encoding: UTF8
			});
			["aaa\r", "\rbbb\r", "\nccc\r"].forEach(function(item) {
				reader.push(item, UTF8);
			});
			reader.push(null);
			reader
				.pipe(converter);
		});

	});

	describe("in stream mode (iconv)", function() {
		function testStream(toNewline, fromNewline, expected, done) {
			var fromFilename = path.join("data", SHIFT_JIS, fromNewline + ".txt");
			var targetFilename = fromFilename + "." + toNewline;

			var reader = fs.createReadStream(fromFilename);
			var writer = fs.createWriteStream(targetFilename);
			var converter = convertNewline(toNewline).stream();

			writer.on("finish", function() {
				var actual = fs.readFileSync(targetFilename);
				assert.ok(bufferEquals(actual, expected));
				done();
			});

			reader
				.pipe(iconv.decodeStream(SHIFT_JIS))
				.pipe(converter)
				.pipe(iconv.encodeStream(SHIFT_JIS))
				.pipe(writer);
		}

		var testData = getShiftJISBufferTestData();
		var newlines = Object.keys(testData);
		newlines.forEach(function (toNewline) {
			newlines.forEach(function(fromNewline) {
				it(util.format("should convert from %s to %s", fromNewline, toNewline), function(done) {
					testStream(toNewline, fromNewline, testData[toNewline], done);
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const http = require('http');
const url = require('url');

// Headless browser
const { ChromeLauncher } = require('lighthouse/lighthouse-cli/chrome-launcher');
const chrome = require('chrome-remote-interface');
// Testing
const BlinkDiff = require('blink-diff');

// Package config
const config = require('./package').config;
// User config
const argv = require('minimist')(process.argv.slice(2));
const host = (argv && argv.host) || '';
const port = (argv && argv.port) || config.port || 80;
const location = 'http://' + (host || 'localhost') + ':' + port;
const browserWidth = (argv && argv.browserWidth  && !isNaN(parseInt(argv.browserWidth)) && parseInt(argv.browserWidth)) || 1280;
const browserHeight = (argv && argv.browserHeight  && !isNaN(parseInt(argv.browserHeight)) && parseInt(argv.browserHeight)) || 720;
const waitMsForServer = (argv && argv.waitMsForServer && !isNaN(parseInt(argv.waitMsForServer)) && parseInt(argv.waitMsForServer)) || 0;
const testOrderingSeed = (argv && argv.testOrderingSeed && !isNaN(parseFloat(argv.testOrderingSeed)) && parseFloat(argv.testOrderingSeed)) || Math.random();
const noRandomTestOrdering = (argv && argv.noRandomTestOrdering) || false;
let recording = (argv && argv.recording) || '';

const recordingsPath = path.resolve(__dirname, 'recordings');
if (!fs.existsSync(recordingsPath)) {
  fs.mkdirSync(recordingsPath);
}

const recordingsFolders = fs.readdirSync(recordingsPath).filter((folder) => fs.statSync(path.resolve(recordingsPath, folder)).isDirectory());
if (!recordingsFolders.length) {
  console.log('');
  console.log('No recordings found in: ' + recordingsPath);
  console.log('');
  process.exitCode = 1;
  return;
}

function shuffle(array) {
  let currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(testOrderingSeed * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

if (recording && recording[0] === '[') {
  try {
    recording = JSON.parse(recording);
  } catch (e) {
    console.log('Invalid array: ' + recording);
    process.exitCode = 1;
    return;
  }
}

let recordingsToTest = recording ? recording.constructor.name === 'Array' ? recording : [recording] : recordingsFolders;

const notFound = recordingsToTest.some((recordingToFind) => {
  const notFoundRecording = !fs.existsSync(path.resolve(recordingsPath, recordingToFind, 'recording.json'));
  if (notFoundRecording) {
    console.log('');
    console.log('Recording not found: ' + recordingToFind + ', does not exist: ' + path.resolve(recordingsPath, recordingToFind, 'recording.json'));
    console.log('');
  }
  return notFoundRecording;
});
if (notFound) {
  process.exitCode = 1;
  return;
}

if (noRandomTestOrdering) {
  console.log('');
  console.log('No random test ordering!');
  console.log('');
} else {
  console.log('');
  console.log('Shuffling test ordering using seed: ' + testOrderingSeed);
  console.log('');
  recordingsToTest = shuffle(recordingsToTest);
}
console.log('');
console.log('Running the following test ordering:');
recordingsToTest.forEach((value, index) => console.log('| ' + (index + 1) + ' | ' + value));
console.log('');

function startTests() {
  console.log('');
  console.log('Starting visual regression testing...');
  console.log('');
  startTestingEnvironment();
}

function checkIfUrlExists(callback) {
  const options = {
    method: 'HEAD',
    host: host,
    port: port,
    path: url.parse(location).pathname
  };
  const request = http.request(options, (response) => {
    if (response.statusCode === 200) {
      callback();
    } else {
      console.log('');
      console.log('No server found running at: ' + location);
      console.log('');
      process.exitCode = 1;
      return;
    }
  }).on('error', () => {
    console.log('');
    console.log('No server found running at: ' + location);
    console.log('');
    process.exitCode = 1;
    return;
  }).end();
}

if (waitMsForServer) {
  console.log('');
  console.log('Waiting ' + waitMsForServer + 'ms for ' + location + ' to be ready...');
  console.log('');
  setTimeout(() => {
    checkIfUrlExists(startTests);
  }, waitMsForServer);
} else {
  checkIfUrlExists(startTests);
}

/**
 * Launches a debugging instance of Chrome on port 9222.
 * @param {boolean=} headless True (default) to launch Chrome in headless mode.
 *     Set to false to launch Chrome normally.
 * @return {Promise<ChromeLauncher>}
 */
function launchChrome(headless = true) {
  const launcher = new ChromeLauncher({
    port: 9222,
    autoSelectChrome: true, // False to manually select which Chrome install.
    additionalFlags: [
      '--window-size=' + browserWidth + ',' + browserHeight,
      // '--remote-debugging-port=9222',
      '--disable-gpu',
      headless ? '--headless' : ''
    ]
  });

  return launcher.run().then(() => launcher)
    .catch(err => {
      return launcher.kill().then(() => { // Kill Chrome if there's an error.
        throw err;
      }, console.error);
    });
}

async function startTestingEnvironment() {
  const launcher = await launchChrome();
  chrome(async (protocol) => {
    // Extract the parts of the DevTools protocol we need for the task.
    // See API docs: https://chromedevtools.github.io/devtools-protocol/
    const { Page, Runtime } = protocol;

    const runScript = (script) => (Runtime.evaluate({ expression: script }));
    const captureScreenshot = () => (Page.captureScreenshot({ fromSurface: true }));
    const done = () => {
      protocol.close();
      launcher.kill(); // Kill Chrome.
    };

    // First, need to enable the domains we're going to use.
    await Page.enable();
    await Runtime.enable();
    Page.navigate({ url: location });

    // Wait for window.onload before doing stuff.
    Page.loadEventFired(async () => {
      await runScript('window.__IS_HEADLESS_BROWSER__ = true');
      const startReplayingDispatch = {
        type: 'START_REPLAYING@Replayer',
        payload: {}
      };
      await dispatcher(startReplayingDispatch, runScript);
      await runTests(recordingsToTest, runScript, captureScreenshot);
      const stopReplayingDispatch = {
        type: 'STOP_REPLAYING@Replayer'
      };
      await dispatcher(stopReplayingDispatch, runScript);
      done();
      console.log('');
      console.log('Visual regression testing has completed!');
      console.log('');
    });
  }).on('error', err => {
    throw Error('Cannot connect to Chrome:' + err);
  });
}

async function runTests(recordingsToTest, runScript, captureScreenshot) {
  for (let recordingToTest of recordingsToTest) {
    await runTest(recordingToTest, runScript, captureScreenshot);
  }
}

async function runTest(name, runScript, captureScreenshot) {
  console.log('');
  console.log('Visual regression testing started for recording: ' + name);
  console.log('');
  const replayedRecording = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'recordings', name, 'recording.json')));
  const initialStateDispatch = {
    type: 'SET_INITIAL_STATE@Replayer',
    payload: replayedRecording.initialState
  };
  await dispatchAndTakeScreenshot(name, 'initialState', initialStateDispatch, runScript, captureScreenshot);
  let index = 0;
  for (dispatch of replayedRecording.dispatches) {
    await dispatchAndTakeScreenshot(name, 'dispatch_' + index, dispatch, runScript, captureScreenshot, index);
    index = index + 1;
  }
  console.log('');
  console.log('Visual regression testing completed for recording: ' + name);
  console.log('');
}

async function dispatcher(dispatch, runScript, index) {
  const log = index !== undefined && index !== null ? '| ' + index + ' | ': '';
  console.log(log + 'Dispatching ' + dispatch.type);
  await runScript('window.__STORE__.dispatch(eval(' + JSON.stringify(dispatch) + '))');
}

async function dispatchAndTakeScreenshot(name, filename, dispatch, runScript, captureScreenshot, index) {
  await dispatcher(dispatch, runScript, index);
  const { data } = await captureScreenshot();
  if (fs.existsSync(path.resolve(__dirname, 'recordings', name, filename + '.png'))) {
    const originalFile = fs.readFileSync(path.resolve(__dirname, 'recordings', name, filename + '.png'));
    // console.log(originalFile.toString('base64') === data ? 'Match!' : 'Failed!');
    const comparisonFileBuffer = Buffer.from(data, 'base64');
    const diffConfig = {
      imageA: originalFile,
      imageB: comparisonFileBuffer,
      threshold: 0,
      imageOutputPath: path.resolve(__dirname, 'recordings', name, filename + '_diff.png')
    };
    const diff = new BlinkDiff(diffConfig);
    return new Promise((resolve, reject) => {
      diff.run((error, result) => {
        if (error) {
          reject(error);
        } else {
          if (diff.hasPassed(result.code)) {
            console.log('');
            console.log('Match!');
            console.log('Found ' + result.differences + ' differences.');
            console.log('This screenshot still matches the ' + filename + '.png baseline image!');
            console.log('');
            if (fs.existsSync(path.resolve(__dirname, 'recordings', name, filename + '_diff.png'))) {
              fs.unlinkSync(path.resolve(__dirname, 'recordings', name, filename + '_diff.png'));
            }
            if (fs.existsSync(path.resolve(__dirname, 'recordings', name, filename + '_new.png'))) {
              fs.unlinkSync(path.resolve(__dirname, 'recordings', name, filename + '_new.png'));
            }
          } else {
            process.exitCode = 1;
            fs.writeFileSync(path.resolve(__dirname, 'recordings', name, filename + '_new.png'), data, 'base64');
            console.log('');
            console.log('Failed!');
            console.log('Found ' + result.differences + ' differences.');
            console.log('Recorded ' + filename + '_diff.png for investigation.');
            console.log('Recorded ' + filename + '_new.png for possible replacement of the ' + filename + '.png baseline image.');
            console.log('');
          }
        }
        resolve();
      });
    });
  } else {
    fs.writeFileSync(path.resolve(__dirname, 'recordings', name, filename + '.png'), data, 'base64');
    console.log('');
    console.log('Recorded ' + filename + '.png baseline image.');
    console.log('');
  }
}
<commit_msg>exit normally if no recordings to test<commit_after>const fs = require('fs');
const path = require('path');
const http = require('http');
const url = require('url');

// Headless browser
const { ChromeLauncher } = require('lighthouse/lighthouse-cli/chrome-launcher');
const chrome = require('chrome-remote-interface');
// Testing
const BlinkDiff = require('blink-diff');

// Package config
const config = require('./package').config;
// User config
const argv = require('minimist')(process.argv.slice(2));
const host = (argv && argv.host) || '';
const port = (argv && argv.port) || config.port || 80;
const location = 'http://' + (host || 'localhost') + ':' + port;
const browserWidth = (argv && argv.browserWidth  && !isNaN(parseInt(argv.browserWidth)) && parseInt(argv.browserWidth)) || 1280;
const browserHeight = (argv && argv.browserHeight  && !isNaN(parseInt(argv.browserHeight)) && parseInt(argv.browserHeight)) || 720;
const waitMsForServer = (argv && argv.waitMsForServer && !isNaN(parseInt(argv.waitMsForServer)) && parseInt(argv.waitMsForServer)) || 0;
const testOrderingSeed = (argv && argv.testOrderingSeed && !isNaN(parseFloat(argv.testOrderingSeed)) && parseFloat(argv.testOrderingSeed)) || Math.random();
const noRandomTestOrdering = (argv && argv.noRandomTestOrdering) || false;
let recording = (argv && argv.recording) || '';

const recordingsPath = path.resolve(__dirname, 'recordings');
if (!fs.existsSync(recordingsPath)) {
  fs.mkdirSync(recordingsPath);
}

const recordingsFolders = fs.readdirSync(recordingsPath).filter((folder) => fs.statSync(path.resolve(recordingsPath, folder)).isDirectory());
if (!recordingsFolders.length) {
  console.log('');
  console.log('No recordings found in: ' + recordingsPath);
  console.log('');
  return;
}

function shuffle(array) {
  let currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(testOrderingSeed * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

if (recording && recording[0] === '[') {
  try {
    recording = JSON.parse(recording);
  } catch (e) {
    console.log('Invalid array: ' + recording);
    process.exitCode = 1;
    return;
  }
}

let recordingsToTest = recording ? recording.constructor.name === 'Array' ? recording : [recording] : recordingsFolders;

const notFound = recordingsToTest.some((recordingToFind) => {
  const notFoundRecording = !fs.existsSync(path.resolve(recordingsPath, recordingToFind, 'recording.json'));
  if (notFoundRecording) {
    console.log('');
    console.log('Recording not found: ' + recordingToFind + ', does not exist: ' + path.resolve(recordingsPath, recordingToFind, 'recording.json'));
    console.log('');
  }
  return notFoundRecording;
});
if (notFound) {
  process.exitCode = 1;
  return;
}

if (noRandomTestOrdering) {
  console.log('');
  console.log('No random test ordering!');
  console.log('');
} else {
  console.log('');
  console.log('Shuffling test ordering using seed: ' + testOrderingSeed);
  console.log('');
  recordingsToTest = shuffle(recordingsToTest);
}
console.log('');
console.log('Running the following test ordering:');
recordingsToTest.forEach((value, index) => console.log('| ' + (index + 1) + ' | ' + value));
console.log('');

function startTests() {
  console.log('');
  console.log('Starting visual regression testing...');
  console.log('');
  startTestingEnvironment();
}

function checkIfUrlExists(callback) {
  const options = {
    method: 'HEAD',
    host: host,
    port: port,
    path: url.parse(location).pathname
  };
  const request = http.request(options, (response) => {
    if (response.statusCode === 200) {
      callback();
    } else {
      console.log('');
      console.log('No server found running at: ' + location);
      console.log('');
      process.exitCode = 1;
      return;
    }
  }).on('error', () => {
    console.log('');
    console.log('No server found running at: ' + location);
    console.log('');
    process.exitCode = 1;
    return;
  }).end();
}

if (waitMsForServer) {
  console.log('');
  console.log('Waiting ' + waitMsForServer + 'ms for ' + location + ' to be ready...');
  console.log('');
  setTimeout(() => {
    checkIfUrlExists(startTests);
  }, waitMsForServer);
} else {
  checkIfUrlExists(startTests);
}

/**
 * Launches a debugging instance of Chrome on port 9222.
 * @param {boolean=} headless True (default) to launch Chrome in headless mode.
 *     Set to false to launch Chrome normally.
 * @return {Promise<ChromeLauncher>}
 */
function launchChrome(headless = true) {
  const launcher = new ChromeLauncher({
    port: 9222,
    autoSelectChrome: true, // False to manually select which Chrome install.
    additionalFlags: [
      '--window-size=' + browserWidth + ',' + browserHeight,
      // '--remote-debugging-port=9222',
      '--disable-gpu',
      headless ? '--headless' : ''
    ]
  });

  return launcher.run().then(() => launcher)
    .catch(err => {
      return launcher.kill().then(() => { // Kill Chrome if there's an error.
        throw err;
      }, console.error);
    });
}

async function startTestingEnvironment() {
  const launcher = await launchChrome();
  chrome(async (protocol) => {
    // Extract the parts of the DevTools protocol we need for the task.
    // See API docs: https://chromedevtools.github.io/devtools-protocol/
    const { Page, Runtime } = protocol;

    const runScript = (script) => (Runtime.evaluate({ expression: script }));
    const captureScreenshot = () => (Page.captureScreenshot({ fromSurface: true }));
    const done = () => {
      protocol.close();
      launcher.kill(); // Kill Chrome.
    };

    // First, need to enable the domains we're going to use.
    await Page.enable();
    await Runtime.enable();
    Page.navigate({ url: location });

    // Wait for window.onload before doing stuff.
    Page.loadEventFired(async () => {
      await runScript('window.__IS_HEADLESS_BROWSER__ = true');
      const startReplayingDispatch = {
        type: 'START_REPLAYING@Replayer',
        payload: {}
      };
      await dispatcher(startReplayingDispatch, runScript);
      await runTests(recordingsToTest, runScript, captureScreenshot);
      const stopReplayingDispatch = {
        type: 'STOP_REPLAYING@Replayer'
      };
      await dispatcher(stopReplayingDispatch, runScript);
      done();
      console.log('');
      console.log('Visual regression testing has completed!');
      console.log('');
    });
  }).on('error', err => {
    throw Error('Cannot connect to Chrome:' + err);
  });
}

async function runTests(recordingsToTest, runScript, captureScreenshot) {
  for (let recordingToTest of recordingsToTest) {
    await runTest(recordingToTest, runScript, captureScreenshot);
  }
}

async function runTest(name, runScript, captureScreenshot) {
  console.log('');
  console.log('Visual regression testing started for recording: ' + name);
  console.log('');
  const replayedRecording = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'recordings', name, 'recording.json')));
  const initialStateDispatch = {
    type: 'SET_INITIAL_STATE@Replayer',
    payload: replayedRecording.initialState
  };
  await dispatchAndTakeScreenshot(name, 'initialState', initialStateDispatch, runScript, captureScreenshot);
  let index = 0;
  for (dispatch of replayedRecording.dispatches) {
    await dispatchAndTakeScreenshot(name, 'dispatch_' + index, dispatch, runScript, captureScreenshot, index);
    index = index + 1;
  }
  console.log('');
  console.log('Visual regression testing completed for recording: ' + name);
  console.log('');
}

async function dispatcher(dispatch, runScript, index) {
  const log = index !== undefined && index !== null ? '| ' + index + ' | ': '';
  console.log(log + 'Dispatching ' + dispatch.type);
  await runScript('window.__STORE__.dispatch(eval(' + JSON.stringify(dispatch) + '))');
}

async function dispatchAndTakeScreenshot(name, filename, dispatch, runScript, captureScreenshot, index) {
  await dispatcher(dispatch, runScript, index);
  const { data } = await captureScreenshot();
  if (fs.existsSync(path.resolve(__dirname, 'recordings', name, filename + '.png'))) {
    const originalFile = fs.readFileSync(path.resolve(__dirname, 'recordings', name, filename + '.png'));
    // console.log(originalFile.toString('base64') === data ? 'Match!' : 'Failed!');
    const comparisonFileBuffer = Buffer.from(data, 'base64');
    const diffConfig = {
      imageA: originalFile,
      imageB: comparisonFileBuffer,
      threshold: 0,
      imageOutputPath: path.resolve(__dirname, 'recordings', name, filename + '_diff.png')
    };
    const diff = new BlinkDiff(diffConfig);
    return new Promise((resolve, reject) => {
      diff.run((error, result) => {
        if (error) {
          reject(error);
        } else {
          if (diff.hasPassed(result.code)) {
            console.log('');
            console.log('Match!');
            console.log('Found ' + result.differences + ' differences.');
            console.log('This screenshot still matches the ' + filename + '.png baseline image!');
            console.log('');
            if (fs.existsSync(path.resolve(__dirname, 'recordings', name, filename + '_diff.png'))) {
              fs.unlinkSync(path.resolve(__dirname, 'recordings', name, filename + '_diff.png'));
            }
            if (fs.existsSync(path.resolve(__dirname, 'recordings', name, filename + '_new.png'))) {
              fs.unlinkSync(path.resolve(__dirname, 'recordings', name, filename + '_new.png'));
            }
          } else {
            process.exitCode = 1;
            fs.writeFileSync(path.resolve(__dirname, 'recordings', name, filename + '_new.png'), data, 'base64');
            console.log('');
            console.log('Failed!');
            console.log('Found ' + result.differences + ' differences.');
            console.log('Recorded ' + filename + '_diff.png for investigation.');
            console.log('Recorded ' + filename + '_new.png for possible replacement of the ' + filename + '.png baseline image.');
            console.log('');
          }
        }
        resolve();
      });
    });
  } else {
    fs.writeFileSync(path.resolve(__dirname, 'recordings', name, filename + '.png'), data, 'base64');
    console.log('');
    console.log('Recorded ' + filename + '.png baseline image.');
    console.log('');
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import {
   ActionBar,
   Avatar,
   Button,
   ButtonGroup,
   Checkbox,
   CheckboxGroup,
   // Cover,
   Form,
   Grid,
   GridCell,
   // Icon,
   Input,
   Nav,
   Notification,
   Popover,
   Radio,
   RadioGroup,
   Select,
   Spacer,
   Switch,
   Text,
   Textarea,
   Title,
   TitleBar,
   ToolBar,
   View
} from './'

import styles from './foundation/styles.less' // eslint-disable-line no-unused-vars

class Demo extends React.Component {
   constructor(props, context) {
      super(props, context)

      this.state = {}
   }

   handleSubmit(data) {
      console.log(data) // eslint-disable-line
      // Simulate delayed promise
      return new Promise((resolve, reject) => {
         setTimeout(() => {
            resolve()
         }, 2000)
      })
   }

   handleError(errors) {
      console.log(errors) // eslint-disable-line
   }

   render() {
      const titleHeading = '1'
      const titleSize = '4'
      const notification = (this.state && this.state.notification) || {}

      return (
         <View format="auto">
            <View width="20%" height="100%" padding="24px[c] 38px[d]">
               <Notification
                  buttonAllAction={notification.buttonAllAction}
                  buttonFull={notification.buttonFull}
                  buttonFullAction={notification.buttonFullAction}
                  buttonOne={notification.buttonOne}
                  buttonOneAction={notification.buttonOneAction}
                  buttonTwo={notification.buttonTwo}
                  buttonTwoAction={notification.buttonTwoAction}
                  message={notification.message}
                  mode={notification.mode}
                  onHide={notification.onHide}
                  onShow={notification.onShow}
                  showing={notification.showing}
                  title={notification.title}
               />
               <Title heading={titleHeading} weight="light" size="9">OIO</Title>
               <Text weight="bold" color="gray40">A Happy Style Framework</Text>
               <Spacer size="4" />

                  Example
                  Actionbar
                  Avatar
                  Button
                  Button Group
                  Grid
                  GridCell
                  Icon
                  Spacer
                  Text
                  Title
                  Titlebar
                  Toolbar
                  View

            </View>
            <View width="80%" height="100%" padding="36px">
               <TitleBar title="Example" />
               <ActionBar>

                     Tab 1
                     Tab 2
                     Tab 3

                  <ButtonGroup align="right">
                     <Button name="Popover Button" onClick={event => this.popover.show(event)} />
                     <Popover
                        ref={(popover) => { this.popover = popover }}
                        width="300px"
                        offset="18px"
                        position="right"
                        className="p18">
                        I am a popover!
                     </Popover>
                  </ButtonGroup>
               </ActionBar>
               <View width="100%" height="75%" format="float" scroll="on">
                  <Grid columns="1[a] 2[b] 4[c] 4[d] 4[e]" gutter="30">
                     <GridCell>
                        <Form
                           onSubmit={data => this.handleSubmit(data)}
                           onError={error => this.handleError(error)}>

                                 <Input
                                    name="name.first"
                                    label="First Name"
                                    placeholder="Please enter your first name"
                                    value="Jared"
                                    rules={['required']}
                                 />

                           <Input
                              name="name.last"
                              label="Last Name"
                              placeholder="Please enter your last name"
                              value="Reich"
                           />
                           <Input
                              name="email"
                              label="Email"
                              placeholder="Please enter your email"
                              value="jared@mother.co"
                              rules={[
                                 'required',
                                 { test: 'email', message: 'Enter a valid email' },
                                 { test: value => value.length > 8, message: 'At least 8 characters' }
                              ]}
                           />
                           <Textarea
                              name="description"
                              label="Description"
                              placeholder="Please enter the subtitle"
                           />
                           <Select
                              name="choice"
                              label="A Choice"
                              options={[
                                 { value: '', text: 'Please select a choice' },
                                 { value: 'one', text: 'One' },
                                 { value: 'two', text: 'Two' },
                                 { value: 'three', text: 'Three' }
                              ]}
                              value={null || 'two'}
                              rules={['required']}
                           />
                           <RadioGroup
                              name="gender"
                              label="Gender"
                              rules={['required']}
                              value={null || 'female'}>
                              <Grid>
                                 <GridCell><Radio value="male" label="Male" /></GridCell>
                                 <GridCell>

                                          <Radio value="female" label="Female" />

                                 </GridCell>
                                 <GridCell><Radio value="undecided" label="Undecided" /></GridCell>
                              </Grid>
                           </RadioGroup>
                           <CheckboxGroup
                              name="sports"
                              label="Sports"
                              rules={['required']}
                              value={null || ['golf', 'hockey']}>
                              <Grid>
                                 <GridCell><Checkbox value="hockey" label="Hockey" /></GridCell>
                                 <GridCell>

                                          <Checkbox value="golf" label="Golf" />

                                 </GridCell>
                                 <GridCell><Checkbox value="baseball" label="Baseball" /></GridCell>
                              </Grid>
                           </CheckboxGroup>
                           <Switch name="notifications" label="Notifications" />
                           <Button name="Save Changes" type="submit" disabled={this.state.submitting} />
                        </Form>
                     </GridCell>
                     <GridCell>
                        Grid Cell 2
                     </GridCell>
                     <GridCell>
                        <Title heading={titleHeading} size={titleSize}>Avatar</Title>
                        <Avatar src="http://placekitten.com/g/500/500" style={{ width: '100px', height: '100px' }} />
                     </GridCell>
                     <GridCell colspan="4">
                        <Text size="10">This is some text</Text>
                        <Text size="9">This is some text</Text>
                        <Text size="8">This is some text</Text>
                        <Text size="7">This is some text</Text>
                        <Text size="6">This is some text</Text>
                        <Text size="5">This is some text</Text>
                        <Text size="4">This is some text</Text>
                        <Text size="3">This is some text</Text>
                        <Text size="2">This is some text</Text>
                        <Text size="1">This is some text</Text>

                        <ButtonGroup align="right">
                           <Button size="large" name="Big Button" icon="ion-ios-monitor-outline" />
                           <Button size="large" name="Big Button" />
                           <Button name="Big Button" outline />
                        </ButtonGroup>
                     </GridCell>
                  </Grid>

                     Offal tilde blog venmo sartorial, crucifix leggings
                     pork belly bitters. Banh mi iPhone cardigan tote bag.
                     Man bun narwhal pickled shoreditch kogi bespoke.
                     Vegan photo booth ethical, trust fund asymmetrical
                     neutra DIY banjo craft beer chia humblebrag church-key
                     hammock. Retro actually cold-pressed next level tofu vegan.
                     Shabby chic kogi mumblecore williamsburg. Mlkshk kale
                     chips venmo, synth pabst vegan lomo waistcoat whatever.

                     Narwhal selvage mixtape humblebrag messenger bag.
                     Meditation hella thundercats kitsch intelligentsia yr.
                     Umami ennui pug mlkshk you probably havent heard of
                     them, butcher gochujang four dollar toast kickstarter
                     single-origin coffee pabst brooklyn meditation waistcoat
                     kinfolk. Hashtag four dollar toast street art wolf
                     lumbersexual, cornhole bespoke farm-to-table 3 wolf
                     moon scenester slow-carb pop-up pitchfork.
                     Taxidermy pabst offal affogato, biodiesel echo park narwhal.
                     Master cleanse food truck artisan hammock, quinoa ugh
                     keffiyeh truffaut chia. Messenger bag knausgaard
                     lomo yuccie roof party.

                     Flexitarian biodiesel kale chips, hoodie lumbersexual
                     food truck keffiyeh umami single-origin coffee franzen.
                     Celiac viral put a bird on it, farm-to-table
                     heirloom everyday carry before they sold out locavore
                     listicle stumptown. Cold-pressed single-origin coffee seitan,
                     next level biodiesel vinyl synth chia pop-up sartorial ugh
                     post-ironic. Hella bitters cardigan affogato selfies
                     thundercats gentrify, man braid schlitz normcore banjo
                     umami messenger bag sartorial. Humblebrag freegan offal,
                     mumblecore tote bag mustache venmo meditation lumbersexual.
                     Put a bird on it intelligentsia lomo gluten-free bitters marfa.
                     Meh literally try-hard ugh everyday carry.

               </View>
               <ToolBar>
                  <ButtonGroup align="right">
                     <Button name="Previous" />
                     <Button name="Next" mode="loading" />
                  </ButtonGroup>
               </ToolBar>
            </View>
         </View>
      )
   }
}

ReactDOM.render(<Demo />, document.getElementById('container'))
<commit_msg>Remove button disabled prop<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import {
   ActionBar,
   Avatar,
   Button,
   ButtonGroup,
   Checkbox,
   CheckboxGroup,
   // Cover,
   Form,
   Grid,
   GridCell,
   // Icon,
   Input,
   Nav,
   Notification,
   Popover,
   Radio,
   RadioGroup,
   Select,
   Spacer,
   Switch,
   Text,
   Textarea,
   Title,
   TitleBar,
   ToolBar,
   View
} from './'

import styles from './foundation/styles.less' // eslint-disable-line no-unused-vars

class Demo extends React.Component {
   constructor(props, context) {
      super(props, context)

      this.state = {}
   }

   handleSubmit(data) {
      console.log(data) // eslint-disable-line
      // Simulate delayed promise
      return new Promise((resolve, reject) => {
         setTimeout(() => {
            resolve()
         }, 2000)
      })
   }

   handleError(errors) {
      console.log(errors) // eslint-disable-line
   }

   render() {
      const titleHeading = '1'
      const titleSize = '4'
      const notification = (this.state && this.state.notification) || {}

      return (
         <View format="auto">
            <View width="20%" height="100%" padding="24px[c] 38px[d]">
               <Notification
                  buttonAllAction={notification.buttonAllAction}
                  buttonFull={notification.buttonFull}
                  buttonFullAction={notification.buttonFullAction}
                  buttonOne={notification.buttonOne}
                  buttonOneAction={notification.buttonOneAction}
                  buttonTwo={notification.buttonTwo}
                  buttonTwoAction={notification.buttonTwoAction}
                  message={notification.message}
                  mode={notification.mode}
                  onHide={notification.onHide}
                  onShow={notification.onShow}
                  showing={notification.showing}
                  title={notification.title}
               />
               <Title heading={titleHeading} weight="light" size="9">OIO</Title>
               <Text weight="bold" color="gray40">A Happy Style Framework</Text>
               <Spacer size="4" />

                  Example
                  Actionbar
                  Avatar
                  Button
                  Button Group
                  Grid
                  GridCell
                  Icon
                  Spacer
                  Text
                  Title
                  Titlebar
                  Toolbar
                  View

            </View>
            <View width="80%" height="100%" padding="36px">
               <TitleBar title="Example" />
               <ActionBar>

                     Tab 1
                     Tab 2
                     Tab 3

                  <ButtonGroup align="right">
                     <Button name="Popover Button" onClick={event => this.popover.show(event)} />
                     <Popover
                        ref={(popover) => { this.popover = popover }}
                        width="300px"
                        offset="18px"
                        position="right"
                        className="p18">
                        I am a popover!
                     </Popover>
                  </ButtonGroup>
               </ActionBar>
               <View width="100%" height="75%" format="float" scroll="on">
                  <Grid columns="1[a] 2[b] 4[c] 4[d] 4[e]" gutter="30">
                     <GridCell>
                        <Form
                           onSubmit={data => this.handleSubmit(data)}
                           onError={error => this.handleError(error)}>

                                 <Input
                                    name="name.first"
                                    label="First Name"
                                    placeholder="Please enter your first name"
                                    value="Jared"
                                    rules={['required']}
                                 />

                           <Input
                              name="name.last"
                              label="Last Name"
                              placeholder="Please enter your last name"
                              value="Reich"
                           />
                           <Input
                              name="email"
                              label="Email"
                              placeholder="Please enter your email"
                              value="jared@mother.co"
                              rules={[
                                 'required',
                                 { test: 'email', message: 'Enter a valid email' },
                                 { test: value => value.length > 8, message: 'At least 8 characters' }
                              ]}
                           />
                           <Textarea
                              name="description"
                              label="Description"
                              placeholder="Please enter the subtitle"
                           />
                           <Select
                              name="choice"
                              label="A Choice"
                              options={[
                                 { value: '', text: 'Please select a choice' },
                                 { value: 'one', text: 'One' },
                                 { value: 'two', text: 'Two' },
                                 { value: 'three', text: 'Three' }
                              ]}
                              value={null || 'two'}
                              rules={['required']}
                           />
                           <RadioGroup
                              name="gender"
                              label="Gender"
                              rules={['required']}
                              value={null || 'female'}>
                              <Grid>
                                 <GridCell><Radio value="male" label="Male" /></GridCell>
                                 <GridCell>

                                          <Radio value="female" label="Female" />

                                 </GridCell>
                                 <GridCell><Radio value="undecided" label="Undecided" /></GridCell>
                              </Grid>
                           </RadioGroup>
                           <CheckboxGroup
                              name="sports"
                              label="Sports"
                              rules={['required']}
                              value={null || ['golf', 'hockey']}>
                              <Grid>
                                 <GridCell><Checkbox value="hockey" label="Hockey" /></GridCell>
                                 <GridCell>

                                          <Checkbox value="golf" label="Golf" />

                                 </GridCell>
                                 <GridCell><Checkbox value="baseball" label="Baseball" /></GridCell>
                              </Grid>
                           </CheckboxGroup>
                           <Switch name="notifications" label="Notifications" />
                           <Button name="Save Changes" type="submit" />
                        </Form>
                     </GridCell>
                     <GridCell>
                        Grid Cell 2
                     </GridCell>
                     <GridCell>
                        <Title heading={titleHeading} size={titleSize}>Avatar</Title>
                        <Avatar src="http://placekitten.com/g/500/500" style={{ width: '100px', height: '100px' }} />
                     </GridCell>
                     <GridCell colspan="4">
                        <Text size="10">This is some text</Text>
                        <Text size="9">This is some text</Text>
                        <Text size="8">This is some text</Text>
                        <Text size="7">This is some text</Text>
                        <Text size="6">This is some text</Text>
                        <Text size="5">This is some text</Text>
                        <Text size="4">This is some text</Text>
                        <Text size="3">This is some text</Text>
                        <Text size="2">This is some text</Text>
                        <Text size="1">This is some text</Text>

                        <ButtonGroup align="right">
                           <Button size="large" name="Big Button" icon="ion-ios-monitor-outline" />
                           <Button size="large" name="Big Button" />
                           <Button name="Big Button" outline />
                        </ButtonGroup>
                     </GridCell>
                  </Grid>

                     Offal tilde blog venmo sartorial, crucifix leggings
                     pork belly bitters. Banh mi iPhone cardigan tote bag.
                     Man bun narwhal pickled shoreditch kogi bespoke.
                     Vegan photo booth ethical, trust fund asymmetrical
                     neutra DIY banjo craft beer chia humblebrag church-key
                     hammock. Retro actually cold-pressed next level tofu vegan.
                     Shabby chic kogi mumblecore williamsburg. Mlkshk kale
                     chips venmo, synth pabst vegan lomo waistcoat whatever.

                     Narwhal selvage mixtape humblebrag messenger bag.
                     Meditation hella thundercats kitsch intelligentsia yr.
                     Umami ennui pug mlkshk you probably havent heard of
                     them, butcher gochujang four dollar toast kickstarter
                     single-origin coffee pabst brooklyn meditation waistcoat
                     kinfolk. Hashtag four dollar toast street art wolf
                     lumbersexual, cornhole bespoke farm-to-table 3 wolf
                     moon scenester slow-carb pop-up pitchfork.
                     Taxidermy pabst offal affogato, biodiesel echo park narwhal.
                     Master cleanse food truck artisan hammock, quinoa ugh
                     keffiyeh truffaut chia. Messenger bag knausgaard
                     lomo yuccie roof party.

                     Flexitarian biodiesel kale chips, hoodie lumbersexual
                     food truck keffiyeh umami single-origin coffee franzen.
                     Celiac viral put a bird on it, farm-to-table
                     heirloom everyday carry before they sold out locavore
                     listicle stumptown. Cold-pressed single-origin coffee seitan,
                     next level biodiesel vinyl synth chia pop-up sartorial ugh
                     post-ironic. Hella bitters cardigan affogato selfies
                     thundercats gentrify, man braid schlitz normcore banjo
                     umami messenger bag sartorial. Humblebrag freegan offal,
                     mumblecore tote bag mustache venmo meditation lumbersexual.
                     Put a bird on it intelligentsia lomo gluten-free bitters marfa.
                     Meh literally try-hard ugh everyday carry.

               </View>
               <ToolBar>
                  <ButtonGroup align="right">
                     <Button name="Previous" />
                     <Button name="Next" mode="loading" />
                  </ButtonGroup>
               </ToolBar>
            </View>
         </View>
      )
   }
}

ReactDOM.render(<Demo />, document.getElementById('container'))
<|endoftext|>