<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);
    });
  });

  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;
    });
  });
});
<commit_msg>[test] Ignore example function<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 () {
      /* istanbul ignore next */
      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>'use strict';
var test = require('ava');
var cumberbatch = require('./');

test('returns a random Cumberbatch name', function (t) {
	t.assert(cumberbatch().length > 0);
});

test('returns a given name and a surname', function (t) {
	t.assert(cumberbatch().match(/^\w* \w*$/));
});
<commit_msg>update test<commit_after>'use strict';
var test = require('ava');
var cumberbatch = require('./');

test('returns a random Cumberbatch name', function (t) {
	t.assert(cumberbatch().length > 0);
});

test('returns a given name and a surname', function (t) {
	t.assert(cumberbatch().match(/^\w+ \w+$/));
});
<|endoftext|>


<commit_before>var smart = require('./smart');

smart.model(smart.connectors.mySql, {
    database: 'forum',
    user: 'mehrlich',
    password: ''
}).then(function (model)
{
    // Standard async
    model.user.with({name: 'chinese john'}).exec(function (err, user)
    {
        if(err)
            console.log(err);
        else
            console.log(user);

        console.log('Done!');
    });

    // Promise
    model.user.with({name: 'chinese john'})
        .then(function (user)
        {
            console.log(user);
        })
        .catch(function (err)
        {
            console.log(err);
        })
        .then(function ()
        {
            console.log('Done!');
        });

    // Stream
    var strm = model.user.with({name: 'chinese john'}).stream();

    strm.on('data', function (user)
    {
        console.log(user);
    });

    strm.on('error', function (err)
    {
        console.log(err);
    });

    str.on('end', function ()
    {
        console.log('Done!');
    });

    // strm.pipe(socketIO);
})
.catch(function (err)
{
    console.log(err);
});
<commit_msg>changed database to schema<commit_after>var smart = require('./smart');

smart.model(smart.connectors.mySql, {
    schema: 'forum',
    user: 'mehrlich',
    password: ''
}).then(function (model)
{
    // Standard async
    model.user.with({name: 'chinese john'}).exec(function (err, user)
    {
        if(err)
            console.log(err);
        else
            console.log(user);

        console.log('Done!');
    });

    // Promise
    model.user.with({name: 'chinese john'})
        .then(function (user)
        {
            console.log(user);
        })
        .catch(function (err)
        {
            console.log(err);
        })
        .then(function ()
        {
            console.log('Done!');
        });

    // Stream
    var strm = model.user.with({name: 'chinese john'}).stream();

    strm.on('data', function (user)
    {
        console.log(user);
    });

    strm.on('error', function (err)
    {
        console.log(err);
    });

    str.on('end', function ()
    {
        console.log('Done!');
    });

    // strm.pipe(socketIO);
})
.catch(function (err)
{
    console.log(err);
});
<|endoftext|>


<commit_before>import express from 'express'
import { apolloExpress, graphiqlExpress } from 'apollo-server'
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools'
import bodyParser from 'body-parser'
import Schema from './data/schema'
import Resolvers from './data/resolvers'

const GRAPHQL_PORT = 8080

const graphQLServer = express()

const executableSchema = makeExecutableSchema({
  typeDefs: Schema,
  resolvers: Resolvers,
  allowUndefinedInResolve: false,
  printErrors: true
})

graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({
  schema: executableSchema,
  context: {}
}))

graphQLServer.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql'
}))

graphQLServer.listen(GRAPHQL_PORT, () => console.log(
  `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphiql`
))
<commit_msg>restructured server<commit_after>import express from 'express'
import {apolloExpress, graphiqlExpress} from 'apollo-server'
import {makeExecutableSchema} from 'graphql-tools'
import bodyParser from 'body-parser'
import Schema from './data/schema'
import Resolvers from './data/resolvers'

const GRAPHQL_PORT = 3000

const graphQLServer = express()

const executableSchema = makeExecutableSchema({
  typeDefs: Schema,
  resolvers: Resolvers,
  allowUndefinedInResolve: false,
  printErrors: true
})

graphQLServer.use(express.static(`${__dirname}/../public`))

graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({
  schema: executableSchema,
  context: {}
}))

graphQLServer.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql'
}))

graphQLServer.listen(GRAPHQL_PORT, () => console.log(
  `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphiql`
))
<|endoftext|>


<commit_before>
var assert = require('assert');
var apple = require('./');
var buttons = require('./buttons');
var continues = require('./continues');

function validate_components(button, str) {
    // turn the sample string capture back into an array of hex bytes
    hex = str.match(/.{2}/g);
    var durations = apple.durations_from_hex_buffer(hex);
    assert(apple.valid_leader(durations), 'invalid lead: ' + durations.join());

    var binary = apple.binary_from_durations(durations);
    assert(apple.valid_binary(durations), 'invalid binary: ' + binary.join());

    var bytes = apple.bytes_from_binary(binary);
    assert(apple.valid_bytes(bytes), 'invalid bytes: ' + bytes.join(' '));
    assert(apple.valid_codes(bytes), 'invalid codes: ' + bytes.join(' '));

    var but = apple.button_from_bytes(bytes);
    assert(but == button, 'invalid button: ' + bytes[2] + ' should be ' + button);
}

function validate_buffer(button, str) {
    var buf = new Buffer(str, 'hex');
    var but = apple.button_from_buffer(buf);
    assert(but == button, 'invalid button: ' + but + ' should be ' + button);
}

function validate_continue(str) {
    var buf = new Buffer(str, 'hex');
    var cont = apple.continue_from_buffer(buf);
    assert(cont, 'invalid continue: should be true');
}

buttons.forEach(function(capture) {
    capture.hex.forEach(function(str) {
        validate_components(capture.button, str);
        validate_buffer(capture.button, str);
    });
});

continues.forEach(function(cont) {
    validate_continue(cont);
});
<commit_msg>supporting new aluminum remote data structure<commit_after>
var assert = require('assert');
var apple = require('./');
var buttons = require('./buttons');
var continues = require('./continues');

function validate_components(button, str) {
    // turn the sample string capture back into an array of hex bytes
    hex = str.match(/.{2}/g);
    var durations = apple.durations_from_hex_buffer(hex);
    assert(apple.valid_leader(durations), 'invalid lead: ' + durations.join());

    var binary = apple.binary_from_durations(durations);
    assert(apple.valid_binary(durations), 'invalid binary: ' + binary.join());

    var bytes = apple.bytes_from_binary(binary);
    assert(apple.valid_bytes(bytes), 'invalid bytes: ' + bytes.join(' '));

    var but = apple.button_from_bytes(bytes);
    assert(but == button, 'invalid button: ' + bytes[2] + ' should be ' + button);
}

function validate_buffer(button, str) {
    var buf = new Buffer(str, 'hex');
    var but = apple.button_from_buffer(buf);
    assert(but == button, 'invalid button: ' + but + ' should be ' + button);
}

function validate_continue(str) {
    var buf = new Buffer(str, 'hex');
    var cont = apple.continue_from_buffer(buf);
    assert(cont, 'invalid continue: should be true');
}

buttons.forEach(function(capture) {
    // capture.first.forEach(function(str) {
    //     validate_components(capture.button, str);
    //     validate_buffer(capture.button, str);
    // });

    console.log(capture.button)
    capture.second.forEach(function(str) {
        validate_components(capture.button, str);
        // validate_buffer(capture.button, str);
    });
});

continues.forEach(function(cont) {
    validate_continue(cont);
});

setInterval(function() {}, 1e3);<|endoftext|>


<commit_before>var $ = require('jquery');
var cdb = require('cartodb.js');
var Backbone = require('backbone');
var UserAssetsListView = require('../../../../../../../../../javascripts/cartodb3/components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view');

describe('components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view', function () {
  beforeEach(function () {
    this.model = new cdb.core.Model();
    this.selectedAsset = new cdb.core.Model();

    this._assetsCollection = new Backbone.Collection([{
      item: 1, state: ''
    }, {
      item: 2, state: ''
    }, {
      item: 3, state: ''
    }]);

    this.view = new UserAssetsListView({
      title: 'Title',
      model: this.model,
      assets: this._assetsCollection,
      selectedAsset: this.selectedAsset
    });

    this.view.render();
  });

  it('should render the assets', function () {
    expect(this.view.$el.find('.js-asset').length).toBe(this._assetsCollection.size() + 1);
  });

  it('should render the add button', function () {
    expect(this.view.$el.find('.AssetsList-item--text .js-asset').text().trim()).toBe('+');
    expect(this.view.$el.find('.AssetsList-item--text .js-asset').length).toBe(1);
  });

  it('should trigger an upload event when clicking the add button', function () {
    var triggered = false;

    this.view.bind('init-upload', function () {
      triggered = true;
    }, this);

    this.view.$el.find('.AssetsList-item--text .js-asset').click();
    expect(triggered).toBeTruthy();
  });

  it('should select an asset', function () {
    this._assetsCollection.at(0).set('state', '');
    this._assetsCollection.at(1).set('state', '');
    this._assetsCollection.at(2).set('state', '');

    expect(this._assetsCollection.where({ state: 'selected' }).length).toBe(0);
    $(this.view.$('.js-asset')[1]).click();
    expect(this.view.$('.is-selected').length).toBe(1);
    expect(this._assetsCollection.where({ state: 'selected' }).length).toBe(1);
    expect(this._assetsCollection.at(0).get('state')).toBe('selected');
  });

  it('should select all the assets', function () {
    this._assetsCollection.at(0).set('state', 'selected');

    this.view.$('.js-select-all').click();
    expect(this.view.$('.is-selected').length).toBe(3);
    expect(this._assetsCollection.at(0).get('state')).toBe('selected');
    expect(this._assetsCollection.at(1).get('state')).toBe('selected');
    expect(this._assetsCollection.at(2).get('state')).toBe('selected');
  });

  it('should deselect all the assets', function () {
    this._assetsCollection.at(0).set('state', 'selected');
    this._assetsCollection.at(1).set('state', 'selected');
    this._assetsCollection.at(2).set('state', 'selected');

    this.view.$('.js-deselect-all').click();
    expect(this._assetsCollection.at(0).get('state')).toBe('');
    expect(this._assetsCollection.at(1).get('state')).toBe('');
    expect(this._assetsCollection.at(2).get('state')).toBe('');
    expect(this.view.$('.is-selected').length).toBe(0);
  });

  it('should remove selected assets', function () {
    this._assetsCollection.at(0).set('state', 'selected');
    this._assetsCollection.at(1).set('state', 'selected');
    this._assetsCollection.at(2).set('state', '');

    this.view.$('.js-remove').click();
    expect(this._assetsCollection.size()).toBe(1);
  });

  afterEach(function () {
    this.view.clean();
  });
});

<commit_msg>Updates spec<commit_after>var $ = require('jquery');
var Backbone = require('backbone');
var UserAssetsListView = require('../../../../../../../../../javascripts/cartodb3/components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view');
var AssetsCollection = require('../../../../../../../../../javascripts/cartodb3/data/assets-collection');
var ConfigModel = require('../../../../../../../../../javascripts/cartodb3/data/config-model');
var UserModel = require('../../../../../../../../../javascripts/cartodb3/data/user-model');

describe('components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view', function () {
  beforeEach(function () {
    this.model = new Backbone.Model();
    this.selectedAsset = new Backbone.Model();

    var configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    var userModel = new UserModel({}, {
      configModel: configModel
    });

    this._assetsCollection = new AssetsCollection([{
      item: 1, state: ''
    }, {
      item: 2, state: ''
    }, {
      item: 3, state: ''
    }], {
      configModel: configModel,
      userModel: userModel
    });

    this.view = new UserAssetsListView({
      title: 'Title',
      model: this.model,
      assetsCollection: this._assetsCollection,
      selectedAsset: this.selectedAsset
    });

    this.view.render();
  });

  it('should render the assets', function () {
    expect(this.view.$el.find('.js-asset').length).toBe(this._assetsCollection.size() + 1);
  });

  it('should render the add button', function () {
    expect(this.view.$el.find('.AssetsList-item--text .js-asset').text().trim()).toBe('+');
    expect(this.view.$el.find('.AssetsList-item--text .js-asset').length).toBe(1);
  });

  it('should trigger an upload event when clicking the add button', function () {
    var triggered = false;

    this.view.bind('init-upload', function () {
      triggered = true;
    }, this);

    this.view.$el.find('.AssetsList-item--text .js-asset').click();
    expect(triggered).toBeTruthy();
  });

  it('should select an asset', function () {
    this._assetsCollection.at(0).set('state', '');
    this._assetsCollection.at(1).set('state', '');
    this._assetsCollection.at(2).set('state', '');

    expect(this._assetsCollection.where({ state: 'selected' }).length).toBe(0);
    $(this.view.$('.js-asset')[1]).click();
    expect(this.view.$('.is-selected').length).toBe(1);
    expect(this._assetsCollection.where({ state: 'selected' }).length).toBe(1);
    expect(this._assetsCollection.at(0).get('state')).toBe('selected');
  });

  it('should select all the assets', function () {
    this._assetsCollection.at(0).set('state', 'selected');

    this.view.$('.js-select-all').click();
    expect(this.view.$('.is-selected').length).toBe(3);
    expect(this._assetsCollection.at(0).get('state')).toBe('selected');
    expect(this._assetsCollection.at(1).get('state')).toBe('selected');
    expect(this._assetsCollection.at(2).get('state')).toBe('selected');
  });

  it('should deselect all the assets', function () {
    this._assetsCollection.at(0).set('state', 'selected');
    this._assetsCollection.at(1).set('state', 'selected');
    this._assetsCollection.at(2).set('state', 'selected');

    this.view.$('.js-deselect-all').click();
    expect(this._assetsCollection.at(0).get('state')).toBe('');
    expect(this._assetsCollection.at(1).get('state')).toBe('');
    expect(this._assetsCollection.at(2).get('state')).toBe('');
    expect(this.view.$('.is-selected').length).toBe(0);
  });

  it('should remove selected assets', function () {
    this._assetsCollection.at(0).set('state', 'selected');
    this._assetsCollection.at(1).set('state', 'selected');
    this._assetsCollection.at(2).set('state', '');

    this.view.$('.js-remove').click();
    expect(this._assetsCollection.size()).toBe(1);
  });

  afterEach(function () {
    this.view.clean();
  });
});

<|endoftext|>


<commit_before>'use strict'

var test = require('tape')
var loopbench = require('./')

function sleep (msec) {
  var start = now()
  while (now() - start < msec) {}
}

function now () {
  var ts = process.hrtime()
  return (ts[0] * 1e3) + (ts[1] / 1e6)
}

test('bench the event loop', function (t) {
  var instance = loopbench()

  t.equal(instance.limit, 42, 'default limit matches')
  t.equal(instance.sampleInterval, 5, 'default sampleInterval matches')
  t.equal(instance.delay, 0, 'delay starts at zero')

  instance.sampleInterval = 1

  sleep(4)
  setImmediate(function () {
    console.log('delay', instance.delay)
    t.ok(instance.delay < 8, 'delay must be less than 8 ms')
    t.ok(instance.delay > -1, 'delay must be greater than -1 ms')
    t.notOk(instance.overLimit, 'must not be overLimit')
    instance.stop()
    t.end()
  })
})

test('emits a "load" event when the limit is reached', function (t) {
  t.plan(7)

  var instance = loopbench({
    sampleInterval: 1, // ms
    limit: 10 // ms
  })

  t.equal(instance.limit, 10, 'limit matches')
  t.equal(instance.sampleInterval, 1, 'sampleInterval matches')

  t.equal(instance.delay, 0, 'delay starts at zero')

  instance.on('load', function () {
    console.log('delay', instance.delay)
    t.pass('load is emitted')
    t.ok(instance.delay > 10, 'delay must be greater than 10 ms')
    t.ok(instance.overLimit, 'must be overLimit')
  })

  setImmediate(function () {
    t.ok(instance.delay > 10, 'delay must be greater than 10 ms')
    instance.stop()
  })

  sleep(50)
})
<commit_msg>Adjusted test to check for overLimit = false.<commit_after>'use strict'

var test = require('tape')
var loopbench = require('./')

function sleep (msec) {
  var start = now()
  while (now() - start < msec) {}
}

function now () {
  var ts = process.hrtime()
  return (ts[0] * 1e3) + (ts[1] / 1e6)
}

test('bench the event loop', function (t) {
  var instance = loopbench()

  t.equal(instance.limit, 42, 'default limit matches')
  t.equal(instance.sampleInterval, 5, 'default sampleInterval matches')
  t.equal(instance.delay, 0, 'delay starts at zero')

  instance.sampleInterval = 1

  sleep(4)
  setImmediate(function () {
    console.log('delay', instance.delay)
    t.ok(instance.delay < 8, 'delay must be less than 8 ms')
    t.ok(instance.delay > -1, 'delay must be greater than -1 ms')
    t.notOk(instance.overLimit, 'must not be overLimit')
    instance.stop()
    t.end()
  })
})

test('emits a "load" event when the limit is reached', function (t) {
  t.plan(7)

  var instance = loopbench({
    sampleInterval: 1, // ms
    limit: 10 // ms
  })

  t.equal(instance.limit, 10, 'limit matches')
  t.equal(instance.sampleInterval, 1, 'sampleInterval matches')

  t.equal(instance.delay, 0, 'delay starts at zero')

  instance.on('load', function () {
    console.log('delay', instance.delay)
    t.pass('load is emitted')
    t.ok(instance.delay > 10, 'delay must be greater than 10 ms')
    t.ok(instance.overLimit, 'must be overLimit')

    setTimeout(function () {
      t.notOk(instance.overLimit, 'overLimit returned to false')
      instance.stop()
    }, instance.sampleInterval + 1)
  })

  sleep(50)
})
<|endoftext|>


<commit_before>'use strict';

/**
 * Dependencies.
 */

var fillers,
    assert;

fillers = require('./');
assert = require('assert');

/**
 * Tests.
 */

describe('fillers', function () {
    it('should be an `Object`', function () {
        assert(typeof fillers === 'object');
    });
});

describe('fillers.is(word)', function () {
    it('should return true if a word is a filler', function () {
        assert(fillers.is('like') === true);
    });

    it('should return false if a word is not a filler', function () {
        assert(fillers.is('unicorn') === false);
    });
});

describe('fillers.all()', function () {
    var all;

    all = fillers.all();

    it('should return an array', function () {
        assert('length' in all);

        assert(typeof all === 'object');
    });

    it('every entry should be lowercase', function () {
        all.forEach(function (value) {
            assert(value.toLowerCase() === value);
        });
    });

    it('every entry should only occur once', function () {
        all.forEach(function (value, index) {
            assert(all.indexOf(value, index + 1) === -1);
        });
    });

    it('should be immutable', function () {
        all.push('unicorn');

        assert(fillers.all().indexOf('unicorn') === -1);
    });
});

describe('fillers.add(filler) and fillers.remove(filler)', function () {
    it('should add and remove a filler', function () {
        assert(fillers.is('unicorn') === false);

        fillers.add('unicorn');

        assert(fillers.is('unicorn') === true);

        fillers.remove('unicorn');

        assert(fillers.is('unicorn') === false);
    });

    it('should add and remove multiple fillers', function () {
        assert(fillers.is('unicorn') === false);
        assert(fillers.is('rainbow') === false);

        fillers.add('unicorn', 'rainbow');

        assert(fillers.is('unicorn') === true);
        assert(fillers.is('rainbow') === true);

        fillers.remove('unicorn', 'rainbow');

        assert(fillers.is('unicorn') === false);
        assert(fillers.is('rainbow') === false);
    });

    it('should fail silently when removing a non-existing filler',
        function () {
            assert(fillers.is('unicorn') === false);

            fillers.remove('unicorn');

            assert(fillers.is('unicorn') === false);
        }
    );
});
<commit_msg>Fix incorrect executive rights on `test.js`<commit_after>'use strict';

/**
 * Dependencies.
 */

var fillers,
    assert;

fillers = require('./');
assert = require('assert');

/**
 * Tests.
 */

describe('fillers', function () {
    it('should be an `Object`', function () {
        assert(typeof fillers === 'object');
    });
});

describe('fillers.is(word)', function () {
    it('should return true if a word is a filler', function () {
        assert(fillers.is('like') === true);
    });

    it('should return false if a word is not a filler', function () {
        assert(fillers.is('unicorn') === false);
    });
});

describe('fillers.all()', function () {
    var all;

    all = fillers.all();

    it('should return an array', function () {
        assert('length' in all);

        assert(typeof all === 'object');
    });

    it('every entry should be lowercase', function () {
        all.forEach(function (value) {
            assert(value.toLowerCase() === value);
        });
    });

    it('every entry should only occur once', function () {
        all.forEach(function (value, index) {
            assert(all.indexOf(value, index + 1) === -1);
        });
    });

    it('should be immutable', function () {
        all.push('unicorn');

        assert(fillers.all().indexOf('unicorn') === -1);
    });
});

describe('fillers.add(filler) and fillers.remove(filler)', function () {
    it('should add and remove a filler', function () {
        assert(fillers.is('unicorn') === false);

        fillers.add('unicorn');

        assert(fillers.is('unicorn') === true);

        fillers.remove('unicorn');

        assert(fillers.is('unicorn') === false);
    });

    it('should add and remove multiple fillers', function () {
        assert(fillers.is('unicorn') === false);
        assert(fillers.is('rainbow') === false);

        fillers.add('unicorn', 'rainbow');

        assert(fillers.is('unicorn') === true);
        assert(fillers.is('rainbow') === true);

        fillers.remove('unicorn', 'rainbow');

        assert(fillers.is('unicorn') === false);
        assert(fillers.is('rainbow') === false);
    });

    it('should fail silently when removing a non-existing filler',
        function () {
            assert(fillers.is('unicorn') === false);

            fillers.remove('unicorn');

            assert(fillers.is('unicorn') === false);
        }
    );
});
<|endoftext|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-20 12:01:33<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-12-4 02:28: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>'use strict';

var http = require('http');
var assert = require('assert');
var requestStats = require('./index');

assert._statsCommon = function (stats) {
  assert(stats.req.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.req.headers.connection, 'string');
  assert.equal(stats.req.method, 'PUT');
  assert.equal(stats.req.path, '/');
  assert.equal(stats.res.status, 200);
};

// assertion helper for validating stats from HTTP requests that finished correctly
assert.statsFinished = function (stats) {
  assert(stats.ok);
  assert(stats.time >= 9); // The reason we don't just do >= 10, is because setTimeout is not that precise
  assert(stats.res.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.res.headers.connection, 'string');
  assert._statsCommon(stats);
};

// assertion helper for validating stats from HTTP requests that are closed before finishing
assert.statsClosed = function (stats) {
  assert(!stats.ok);
  assert(stats.time >= 0);
  assert.equal(stats.res.bytes, 0);
  assert.deepEqual(stats.res.headers, {});
  assert._statsCommon(stats);
};

var _listen = function (server, errorHandler) {
  server.listen(0, function () {
    var options = {
      host: 'localhost',
      port: server.address().port,
      method: 'PUT'
    };

    var req = http.request(options, function (res) {
      res.resume();
      res.once('end', function () {
        server.close();
      });
    });

    if (errorHandler)
      req.on('error', errorHandler);

    req.end('42');
  });
};

var _respond = function (req, res) {
  req.on('end', function () {
    setTimeout(function () {
      res.end('Answer to the Ultimate Question of Life, The Universe, and Everything');
    }, 10);
  });
  req.resume();
};

describe('request-stats', function () {
  afterEach(function () {
    requestStats().removeAllListeners();
  });

  describe('requestStats(req, res).once(...)', function () {
    it('should call the stats-listener on request end', function (done) {
      _listen(http.createServer(function (req, res) {
        requestStats(req, res).once('stats', function (stats) {
          assert.statsFinished(stats);
          done();
        });
        _respond(req, res);
      }));
    });
  });

  describe('requestStats(server).once(...)', function () {
    it('should call the stats-listener on request end', function (done) {
      var server = http.createServer(_respond);
      requestStats(server).once('stats', function (stats) {
        assert.statsFinished(stats);
        done();
      });
      _listen(server);
    });
  });

  describe('requestStats(req, res, onStats)', function () {
    it('should call the stats-listener on request end', function (done) {
      _listen(http.createServer(function (req, res) {
        requestStats(req, res, function (stats) {
          assert.statsFinished(stats);
          done();
        });
        _respond(req, res);
      }));
    });
  });

  describe('requestStats(server, onStats)', function () {
    it('should call the stats-listener on request end', function (done) {
      var server = http.createServer(_respond);
      requestStats(server, function (stats) {
        assert.statsFinished(stats);
        done();
      });
      _listen(server);
    });

    it('should call the stats-listener when the request is destroyed', function (done) {
      var server = http.createServer(function (req, res) {
        req.destroy();
      });
      requestStats(server, function (stats) {
        assert.statsClosed(stats);
      });
      _listen(server, function (err) {
        assert(err instanceof Error);
        done();
      });
    });
  });
});
<commit_msg>Clean up tests 2<commit_after>'use strict';

var http = require('http');
var assert = require('assert');
var requestStats = require('./index');

assert._statsCommon = function (stats) {
  assert(stats.req.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.req.headers.connection, 'string');
  assert.equal(stats.req.method, 'PUT');
  assert.equal(stats.req.path, '/');
  assert.equal(stats.res.status, 200);
};

// assertion helper for validating stats from HTTP requests that finished correctly
assert.statsFinished = function (stats) {
  assert(stats.ok);
  assert(stats.time >= 9); // The reason we don't just do >= 10, is because setTimeout is not that precise
  assert(stats.res.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.res.headers.connection, 'string');
  assert._statsCommon(stats);
};

// assertion helper for validating stats from HTTP requests that are closed before finishing
assert.statsClosed = function (stats) {
  assert(!stats.ok);
  assert(stats.time >= 0);
  assert.equal(stats.res.bytes, 0);
  assert.deepEqual(stats.res.headers, {});
  assert._statsCommon(stats);
};

var _listen = function (server, errorHandler) {
  server.listen(0, function () {
    var options = {
      host: 'localhost',
      port: server.address().port,
      method: 'PUT'
    };

    var req = http.request(options, function (res) {
      res.resume();
      res.once('end', function () {
        server.close();
      });
    });

    if (errorHandler)
      req.on('error', errorHandler);

    req.end('42');
  });
};

var _respond = function (req, res) {
  req.on('end', function () {
    setTimeout(function () {
      res.end('Answer to the Ultimate Question of Life, The Universe, and Everything');
    }, 10);
  });
  req.resume();
};

describe('request-stats', function () {
  afterEach(function () {
    requestStats().removeAllListeners();
  });

  describe('requestStats(server, onStats)', function () {
    it('should call the stats-listener on request end', function (done) {
      var server = http.createServer(_respond);
      requestStats(server, function (stats) {
        assert.statsFinished(stats);
        done();
      });
      _listen(server);
    });

    it('should call the stats-listener when the request is destroyed', function (done) {
      var server = http.createServer(function (req, res) {
        req.destroy();
      });
      requestStats(server, function (stats) {
        assert.statsClosed(stats);
      });
      _listen(server, function (err) {
        assert(err instanceof Error);
        done();
      });
    });
  });

  describe('requestStats(req, res).once(...)', function () {
    it('should call the stats-listener on request end', function (done) {
      _listen(http.createServer(function (req, res) {
        requestStats(req, res).once('stats', function (stats) {
          assert.statsFinished(stats);
          done();
        });
        _respond(req, res);
      }));
    });
  });

  describe('requestStats(server).once(...)', function () {
    it('should call the stats-listener on request end', function (done) {
      var server = http.createServer(_respond);
      requestStats(server).once('stats', function (stats) {
        assert.statsFinished(stats);
        done();
      });
      _listen(server);
    });
  });

  describe('requestStats(req, res, onStats)', function () {
    it('should call the stats-listener on request end', function (done) {
      _listen(http.createServer(function (req, res) {
        requestStats(req, res, function (stats) {
          assert.statsFinished(stats);
          done();
        });
        _respond(req, res);
      }));
    });
  });
});
<|endoftext|>


<commit_before>// var obj = {
// 	name: "rose",
// 	age: 18
// };

// watch(obj, function(prop, oldValue, newValue) {
// 	console.log(prop, oldValue, newValue);
// });

// console.log("** 直接修改对象属性 **");
// obj.age = 20;

// console.log(obj);
// console.log("** 新增对象属性 **");
// obj.$add("car", "BMW");

// console.log("** 删除对象属性 **");
// obj.$del("car");

// 纯数组
var arr = [1, 2, 3, 4, 5];
watch(arr, function(prop, oldValue, newValue) {
	console.log(prop, oldValue, newValue);
});

arr[0] = 22;
arr.splice(1, 1, 12);

// console.log(arr);

// 深层对象
// var fObj = {
// 	son: {
// 		name: "jack",
// 		age: 20
// 	},
// 	son2: {
// 		name: "candy",
// 		age: 17,
// 		grandSon: {
// 			name: "just",
// 			age: 2
// 		}
// 	}
// }

// watch(fObj, function(prop, oldValue, newValue) {
// 	console.log(prop, oldValue, newValue);
// });

// fObj.son2.grandSon.name = "newer";<commit_msg>add object list array<commit_after>// var obj = {
// 	name: "rose",
// 	age: 18
// };

// watch(obj, function(prop, oldValue, newValue) {
// 	console.log(prop, oldValue, newValue);
// });

// console.log("** 直接修改对象属性 **");
// obj.age = 20;

// console.log(obj);
// console.log("** 新增对象属性 **");
// obj.$add("car", "BMW");

// console.log("** 删除对象属性 **");
// obj.$del("car");

// 纯数组
// var arr = [1, 2, 3, 4, 5];
// watch(arr, function(prop, oldValue, newValue) {
// 	console.log(prop, oldValue, newValue);
// });

// arr[0] = 22;
// arr.splice(1, 1, 12);
// arr.pop();
// arr.push(999);
// console.log(arr);

// 深层对象
// var fObj = {
// 	son: {
// 		name: "jack",
// 		age: 20
// 	},
// 	son2: {
// 		name: "candy",
// 		age: 17,
// 		grandSon: {
// 			name: "just",
// 			age: 2
// 		}
// 	}
// }

// watch(fObj, function(prop, oldValue, newValue) {
// 	console.log(prop, oldValue, newValue);
// });

// fObj.son2.grandSon.name = "newer";
// fObj.son.name = "hi";

// 数组中的对象列表
var objArr = [{
	name: "first",
	age: 1
}, {
	name: "2rd",
	age: 2
}];

watch(objArr, function(prop, oldValue, newValue) {
	console.log(prop, oldValue, newValue);
});

objArr[0].name = "Im big";
objArr[1].age = 3;<|endoftext|>


<commit_before>import React from 'react';
import {shallow} from 'enzyme';
import Input from '../src/Input';

@Input
class CustomInput extends React.Component {
}

let formContext = {
    context: {
        _reactForm: {
            attach: jest.fn(),
            detach: jest.fn()
        }
    }
};

describe('Input', () => {
    it('should render correctly', () => {
        let wrapper = shallow(<CustomInput name="email" className="myInput"/>, formContext);

        expect(wrapper.is('.myInput')).toBe(true);
        expect(formContext.context._reactForm.attach).toBeCalledWith(wrapper.instance());
    });

    it('should unmount correctly', () => {
        let wrapper = shallow(<CustomInput name="email" className="myInput"/>, formContext);
        const instance = wrapper.instance();
        wrapper.unmount();
        expect(formContext.context._reactForm.detach).toBeCalledWith(instance);
    });

    it('should register all given dependencies', () => {
        let wrapper = shallow(<CustomInput name="email" dependencies={['email2']}/>, formContext);

        expect(wrapper.instance().dependencies).toEqual(['email2']);
    });

    it('should register all validationRule dependencies', () => {
        let wrapper = shallow(<CustomInput name="email" dependencies={['email2']}
                                           validations={{
                                               equalsField: 'email3',
                                               equalsFields: ['email4', 'email5']
                                           }}/>, formContext);

        expect(wrapper.instance().dependencies).toEqual(['email2', 'email3', 'email4', 'email5']);
    });

    it('should fail when registering a dependency with the same name', () => {
        let wrapper = shallow(<CustomInput name="email"/>, formContext);

        expect(wrapper.instance().addDependency.bind(null, 'email')).toThrow('An input cannot have itself as an dependency. Check your validation rules.');
    });
});
<commit_msg>added test for receiving props and changing state<commit_after>import React from 'react';
import {shallow} from 'enzyme';
import Input from '../src/Input';

@Input
class CustomInput extends React.Component {
}

let formContext = {
    context: {
        _reactForm: {
            attach: jest.fn(),
            detach: jest.fn()
        }
    }
};

describe('Input', () => {
    it('should render correctly', () => {
        let wrapper = shallow(<CustomInput name="email" className="myInput"/>, formContext);

        expect(wrapper.is('.myInput')).toBe(true);
        expect(formContext.context._reactForm.attach).toBeCalledWith(wrapper.instance());
    });

    it('should receive the right props & state', () => {
        let wrapper = shallow(<CustomInput name="email" className="myInput" value="myValue"/>, formContext);

        const instance = wrapper.instance();
        expect(formContext.context._reactForm.attach).toBeCalledWith(instance);
        expect(instance.getName()).toBe('email');
        expect(instance.hasName('abc')).toBe(false);
        expect(instance.hasName('email')).toBe(true);
        expect(instance.isRequired()).toBe(false);
        expect(instance.isPristine()).toBe(true);
        expect(instance.isValid()).toBe(false);
        expect(instance.getValue()).toBe('myValue');

        wrapper.setProps({validations: {isRequired: true}});
        expect(instance.isRequired()).toBe(true);
    });

    it('should unmount correctly', () => {
        let wrapper = shallow(<CustomInput name="email" className="myInput"/>, formContext);
        const instance = wrapper.instance();
        wrapper.unmount();
        expect(formContext.context._reactForm.detach).toBeCalledWith(instance);
    });

    it('should register all given dependencies', () => {
        let wrapper = shallow(<CustomInput name="email" dependencies={['email2']}/>, formContext);

        expect(wrapper.instance().dependencies).toEqual(['email2']);
    });

    it('should register all validationRule dependencies', () => {
        let wrapper = shallow(<CustomInput name="email" dependencies={['email2']}
                                           validations={{
                                               equalsField: 'email3',
                                               equalsFields: ['email4', 'email5']
                                           }}/>, formContext);

        expect(wrapper.instance().dependencies).toEqual(['email2', 'email3', 'email4', 'email5']);
    });

    it('should fail when registering a dependency with the same name', () => {
        let wrapper = shallow(<CustomInput name="email"/>, formContext);

        expect(wrapper.instance().addDependency.bind(null, 'email')).toThrow('An input cannot have itself as an dependency. Check your validation rules.');
    });
});
<|endoftext|>


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

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

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

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

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


<commit_before>'use strict'

var test = require('tape')
var hapi = require('hapi')
var boom = require('boom')
var semver = require('semver')
var proxyquire = require('proxyquire')

var hapiVersion = semver.major(require('hapi/package.json').version)

test('options', function (t) {
  t.plan(2)

  var server = Server()
  var plugin = proxyquire('./', {
    raven: {
      config: function testConfig (dsn, options) {
        t.equal(dsn, 'dsn')
        t.deepEqual(options, {foo: 'bar'})
      }
    }
  })

  register(server, plugin, {
    dsn: 'dsn',
    client: {foo: 'bar'}
  })
})

test('request-error', function (t) {
  t.plan(11)

  var server = Server()
  var plugin = proxyquire('./', {
    raven: {
      config: function () {},
      captureException: function testCapture (err, data) {
        t.equal(err.message, 'unexpected')
        t.ok(data.extra)
        t.equal(typeof data.extra.timestamp, 'number')
        t.equal(typeof data.extra.id, 'string')
        t.equal(data.request.method, 'get')
        t.ok(/^http:\/\/.+:0\/$/.test(data.request.url))
        t.deepEqual(data.request.query_string, {})
        t.ok(data.request.headers['user-agent'])
        t.deepEqual(data.request.cookies, {})
        t.equal(data.extra.remoteAddress, hapiVersion === 8 ? '' : '127.0.0.1')
      }
    }
  })

  register(server, plugin, {})

  server.inject('/', function (response) {
    t.equal(response.statusCode, 500)
  })
})

test('boom error', function (t) {
  t.plan(1)

  var server = Server()
  var plugin = proxyquire('./', {
    raven: {
      config: function () {},
      captureException: t.fail
    }
  })

  register(server, plugin, {})

  server.inject('/boom', function (response) {
    t.equal(response.statusCode, 403)
  })
})

test('tags', function (t) {
  t.plan(3)

  var server = Server()
  var plugin = proxyquire('./', {
    raven: {
      config: function () {},
      captureException: function testCapture (err, data) {
        t.ok(err)
        t.deepEqual(data.tags, ['beep'])
      }
    }
  })

  register(server, plugin, {tags: ['beep']})

  server.inject('/', function (response) {
    t.equal(response.statusCode, 500)
  })
})

function Server () {
  var server = new hapi.Server()
  server.connection()

  server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
      reply(new Error('unexpected'))
    }
  })

  server.route({
    method: 'GET',
    path: '/boom',
    handler: function (request, reply) {
      reply(boom.forbidden())
    }
  })

  return server
}

function register (server, plugin, options) {
  server.register({
    register: plugin,
    options: options || {
      dsn: 'dsn'
    }
  }, function (err) {
    if (err) throw err
  })
}
<commit_msg>test: add conditional url test for hapi@8<commit_after>'use strict'

var test = require('tape')
var hapi = require('hapi')
var boom = require('boom')
var semver = require('semver')
var proxyquire = require('proxyquire')

var hapiVersion = semver.major(require('hapi/package.json').version)

test('options', function (t) {
  t.plan(2)

  var server = Server()
  var plugin = proxyquire('./', {
    raven: {
      config: function testConfig (dsn, options) {
        t.equal(dsn, 'dsn')
        t.deepEqual(options, {foo: 'bar'})
      }
    }
  })

  register(server, plugin, {
    dsn: 'dsn',
    client: {foo: 'bar'}
  })
})

test('request-error', function (t) {
  t.plan(11)

  var server = Server()
  var plugin = proxyquire('./', {
    raven: {
      config: function () {},
      captureException: function testCapture (err, data) {
        t.equal(err.message, 'unexpected')
        t.ok(data.extra)
        t.equal(typeof data.extra.timestamp, 'number')
        t.equal(typeof data.extra.id, 'string')
        t.equal(data.request.method, 'get')

        if (hapiVersion === 8) {
          t.ok(/^http:\/\/.+\/$/.test(data.request.url))
        } else {
          t.ok(/^http:\/\/.+:0\/$/.test(data.request.url))
        }

        t.deepEqual(data.request.query_string, {})
        t.ok(data.request.headers['user-agent'])
        t.deepEqual(data.request.cookies, {})
        t.equal(data.extra.remoteAddress, hapiVersion === 8 ? '' : '127.0.0.1')
      }
    }
  })

  register(server, plugin, {})

  server.inject('/', function (response) {
    t.equal(response.statusCode, 500)
  })
})

test('boom error', function (t) {
  t.plan(1)

  var server = Server()
  var plugin = proxyquire('./', {
    raven: {
      config: function () {},
      captureException: t.fail
    }
  })

  register(server, plugin, {})

  server.inject('/boom', function (response) {
    t.equal(response.statusCode, 403)
  })
})

test('tags', function (t) {
  t.plan(3)

  var server = Server()
  var plugin = proxyquire('./', {
    raven: {
      config: function () {},
      captureException: function testCapture (err, data) {
        t.ok(err)
        t.deepEqual(data.tags, ['beep'])
      }
    }
  })

  register(server, plugin, {tags: ['beep']})

  server.inject('/', function (response) {
    t.equal(response.statusCode, 500)
  })
})

function Server () {
  var server = new hapi.Server()
  server.connection()

  server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
      reply(new Error('unexpected'))
    }
  })

  server.route({
    method: 'GET',
    path: '/boom',
    handler: function (request, reply) {
      reply(boom.forbidden())
    }
  })

  return server
}

function register (server, plugin, options) {
  server.register({
    register: plugin,
    options: options || {
      dsn: 'dsn'
    }
  }, function (err) {
    if (err) throw err
  })
}
<|endoftext|>


<commit_before>var test = require('tape')
var deepEqual = require('./')

test('primitives', function(t) {
  t.ok(deepEqual(1, 1))
  t.ok(deepEqual('a', 'a'))
  t.ok(deepEqual(undefined, undefined))
  t.ok(deepEqual(null, null))
  t.ok(deepEqual(true, true))

  t.notOk(deepEqual('5', 5))
  t.notOk(deepEqual('Infinity', Infinity))
  t.notOk(deepEqual([1, 2, 3], '1,2,3'))

  t.end()
})

test('arrays', function(t) {
  t.ok(deepEqual([1, 2, 3], [1, 2, 3]))
  t.ok(deepEqual(['a'], ['a']))
  t.ok(deepEqual([NaN], [NaN]))
  t.ok(deepEqual([], []))
  t.ok(deepEqual([{}], [{}]))
  t.ok(deepEqual([{a: 1, b: 2}], [{a: 1, b: 2}]))

  t.notOk(deepEqual([1, 2, 3, 4], [1, 2, 3]))
  t.notOk(deepEqual([''], ['', '']))
  t.notOk(deepEqual([1], [1, 1]))
  t.notOk(deepEqual([1], {'0': 1}))

  t.end()
})

test('objects', function(t) {
  t.ok(deepEqual({}, {}))
  t.ok(deepEqual({a: NaN}, {a: NaN}))
  t.ok(deepEqual({a: 1, b: 2}, {a: 1, b: 2}))
  t.ok(deepEqual({a: [], b: [1, 2, 3]}, {a: [], b: [1, 2, 3]}))

  t.ok(deepEqual(
      {
          '1': {
              '2': {
                  '3': 4
                , '5': [{}, {'hi': true, 'bye': {}}]
              }
          }
      }
    , {
          '1': {
              '2': {
                  '3': 4
                , '5': [{}, {'hi': true, 'bye': {}}]
              }
          }
      }
    )
  )

  t.notOk(deepEqual({a: NaN}, {b: NaN}))
  t.notOk(deepEqual({a: 1, b: 2}, {a: 1, b: 2, c: 1}))

  t.notOk(deepEqual(
      {
          '1': {
              '2': {
                  '3': 4
                , '5': [{}, {'hi': true, 'bye': {}}]
              }
          }
      }
    , {
          '1': {
              '2': {
                  '3': 4
                , '5': [{}, {'hi': true, 'bye': []}]
              }
          }
      }
    )
  )

  t.end()
})

test('arguments', function(t) {
  function makeArguments() {
    return arguments
  }

  t.ok(deepEqual(makeArguments(1, 2, 3), makeArguments(1, 2, 3)))
  t.ok(deepEqual(makeArguments('a'), makeArguments('a')))
  t.ok(deepEqual(makeArguments({}), makeArguments({})))

  t.notOk(deepEqual(makeArguments(1, 2, 3), [1, 2, 3]))
  t.notOk(deepEqual(makeArguments('a'), ['a']))

  t.end()
})

test('regexp', function(t) {
  t.ok(deepEqual(/abc/, /abc/))

  t.notOk(deepEqual(/abc/, /abcd/))
  t.notOk(deepEqual(/abc/, {}))
  t.notOk(deepEqual(/abc/, ['a', 'b', 'c']))
  t.notOk(deepEqual(/abc/, ['abc']))
  t.notOk(deepEqual(/abc/, 'abc'))

  t.end()
})

test('date', function(t) {
  var d = new Date

  t.ok(deepEqual(d, new Date(d.getTime())))

  t.notOk(deepEqual(d, new Date(d.getTime() + 1)))
  t.notOk(deepEqual(d, {}))

  t.end()
})

test('buffers', function(t) {
  t.ok(deepEqual(new Buffer('abc'), new Buffer('abc')))

  t.notOk(deepEqual(new Buffer('abc'), new Buffer('abcd')))
  t.notOk(deepEqual(new Buffer('a'), [97]))
  t.notOk(deepEqual(new Buffer('abc'), 'abc'))
  t.notOk(deepEqual(new Buffer('abc'), ['abc']))
  t.notOk(deepEqual(new Buffer('abc'), ['a', 'b', 'c']))
  t.notOk(deepEqual(new Buffer('abc'), {}))

  t.end()
})
<commit_msg>Add tests<commit_after>var test = require('tape')
var deepEqual = require('./')

test('primitives', function(t) {
  t.ok(deepEqual(1, 1))
  t.ok(deepEqual('a', 'a'))
  t.ok(deepEqual(undefined, undefined))
  t.ok(deepEqual(null, null))
  t.ok(deepEqual(true, true))
  t.ok(deepEqual(NaN, NaN))

  t.notOk(deepEqual('5', 5))
  t.notOk(deepEqual('Infinity', Infinity))
  t.notOk(deepEqual([1, 2, 3], '1,2,3'))

  t.end()
})

test('arrays', function(t) {
  t.ok(deepEqual([1, 2, 3], [1, 2, 3]))
  t.ok(deepEqual(['a'], ['a']))
  t.ok(deepEqual([NaN], [NaN]))
  t.ok(deepEqual([Math], [Math]))
  t.ok(deepEqual([5, NaN, 9], [5, NaN, 9]))
  t.ok(deepEqual([], []))
  t.ok(deepEqual([{}], [{}]))
  t.ok(deepEqual([[]], [[]]))
  t.ok(deepEqual([[], []], [[], []]))
  t.ok(deepEqual([{a: 1, b: 2}], [{a: 1, b: 2}]))

  t.notOk(deepEqual([1, 2, 3, undefined], [1, 2, 3]))
  t.notOk(deepEqual([1, 2, 3, 4], [1, 2, 3]))
  t.notOk(deepEqual([''], ['', '']))
  t.notOk(deepEqual([1], [1, 1]))
  t.notOk(deepEqual([1], {'0': 1}))

  t.end()
})

test('objects', function(t) {
  t.ok(deepEqual({}, {}))
  t.ok(deepEqual({a: NaN}, {a: NaN}))
  t.ok(deepEqual({a: 1, b: 2}, {a: 1, b: 2}))
  t.ok(deepEqual({a: [], b: [1, 2, 3]}, {a: [], b: [1, 2, 3]}))

  t.ok(deepEqual(
      {
          '1': {
              '2': {
                  '3': 4
                , '5': [{}, {'hi': true, 'bye': {}}]
              }
          }
      }
    , {
          '1': {
              '2': {
                  '3': 4
                , '5': [{}, {'hi': true, 'bye': {}}]
              }
          }
      }
    )
  )

  t.notOk(deepEqual({a: NaN}, {b: NaN}))
  t.notOk(deepEqual({a: 1, b: 2}, {a: 1, b: 2, c: 1}))

  t.notOk(deepEqual(
      {
          '1': {
              '2': {
                  '3': 4
                , '5': [{}, {'hi': true, 'bye': {}}]
              }
          }
      }
    , {
          '1': {
              '2': {
                  '3': 4
                , '5': [{}, {'hi': true, 'bye': []}]
              }
          }
      }
    )
  )

  t.end()
})

test('arguments', function(t) {
  function makeArguments() {
    return arguments
  }

  t.ok(deepEqual(makeArguments(1, 2, 3), makeArguments(1, 2, 3)))
  t.ok(deepEqual(makeArguments('a'), makeArguments('a')))
  t.ok(deepEqual(makeArguments({}), makeArguments({})))

  t.notOk(deepEqual(makeArguments(1, 2, 3), [1, 2, 3]))
  t.notOk(deepEqual(makeArguments('a'), ['a']))

  t.end()
})

test('regexp', function(t) {
  t.ok(deepEqual(/abc/, /abc/))

  t.notOk(deepEqual(/abc/, /abcd/))
  t.notOk(deepEqual(/abc/, {}))
  t.notOk(deepEqual(/abc/, ['a', 'b', 'c']))
  t.notOk(deepEqual(/abc/, ['abc']))
  t.notOk(deepEqual(/abc/, 'abc'))

  t.end()
})

test('date', function(t) {
  var d = new Date
  var dTime = d.getTime()

  t.ok(deepEqual(new Date(1), new Date(1)))
  t.ok(deepEqual(d, new Date(dTime)))

  t.notOk(deepEqual(d, new Date(1)))
  t.notOk(deepEqual(d, new Date(dTime + 1)))
  t.notOk(deepEqual(d, { getTime: d.getTime.bind(d) }))
  t.notOk(deepEqual(d,
    {
      getTime: function() {
        return dTime
      }
  }))

  t.end()
})

test('buffers', function(t) {
  t.ok(deepEqual(new Buffer('abc'), new Buffer('abc')))

  t.notOk(deepEqual(new Buffer('abc'), new Buffer('abcd')))
  t.notOk(deepEqual(new Buffer('a'), [97]))
  t.notOk(deepEqual(new Buffer('abc'), 'abc'))
  t.notOk(deepEqual(new Buffer('abc'), ['abc']))
  t.notOk(deepEqual(new Buffer('abc'), ['a', 'b', 'c']))
  t.notOk(deepEqual(new Buffer('abc'), {}))

  t.end()
})

test('handles deep equality of arrays', function(assert) {
  var arr1 = [1, 2, 3];
  var arr2 = [1, 2, 3];
  var arr3 = [1, 2, 3];
  var arr4 = [1, 2, 3];
  arr3[6] = 6;

  assert.ok(deepEqual(arr1, [1, 2, 3]))
  assert.ok(deepEqual(arr1, arr1))
  assert.ok(deepEqual(arr1, arr2))
  assert.ok(deepEqual(arr1.concat([9, 16]), [1, 2, 3, 9, 16]))
  assert.ok(deepEqual([], []))

  assert.notOk(deepEqual(arr1, [1, 2, 3, 4]))
  assert.notOk(deepEqual(arr1, [3, 2, 1]))

  assert.notOk(deepEqual(arr3, arr4))
  arr4[6] = 6;
  assert.ok(deepEqual(arr3, arr4))

  assert.end()
})

test('handles deep equality of objects', function(assert) {
  var obj1 = {
    boolProp: true,
    stringProp: 'abc',
    arrProp: [1, 2, 3],
    undefProp: undefined,
    nullProp: null
  };

  var obj2 = {
    undefProp: undefined,
    stringProp: 'abc',
    arrProp: [1, 2, 3],
    boolProp: true,
    nullProp: null
  }

  var objWithMore = {
    boolProp: true,
    boolProp2: true,
    stringProp: 'abc',
    arrProp: [1, 2, 3],
    undefProp: undefined,
    nullProp: null
  }

  var objWithLess = {
    stringProp: 'abc',
    arrProp: [1, 2, 3],
    undefProp: undefined,
    nullProp: null
  }

  assert.ok(deepEqual(obj1, obj2))
  assert.ok(deepEqual({}, {}))

  assert.notOk(deepEqual(obj1, objWithLess))
  assert.notOk(deepEqual(obj1, objWithMore))

  assert.end()
})<|endoftext|>


<commit_before>/* global it */

var assert = require('assert')
var gutil = require('gulp-util')
var postcss = require('.')

it('should transform css with multiple processors', function (cb) {

  var stream = postcss(
    [ doubler, doubler ]
  , { map: false }  // omit source map for the test
  )

  stream.on('data', function (file) {
    var result = file.contents.toString('utf8')
    var target = 'a { color: black; color: black; color: black; color: black }'
    assert.equal( result, target )
    cb()
  })

  stream.write(new gutil.File({
    contents: new Buffer('a { color: black }')
  }))

  stream.end()

})

it('should correctly wrap postcss errors', function (cb) {

  var stream = postcss([ doubler ])

  stream.on('error', function (err) {
    assert.ok(err instanceof gutil.PluginError)
    assert.equal(err.plugin, 'gulp-postcss')
    cb()
  })

  stream.write(new gutil.File({
    contents: new Buffer('a {\n  a b {}\n}')
  }))

  stream.end()

})

it ('should throw error if processors are not provided', function (cb) {
  assert.throws( function () { postcss() }, gutil.PluginError )
  assert.throws( function () { postcss('') }, gutil.PluginError )
  assert.throws( function () { postcss({}) }, gutil.PluginError )
  cb()
})

function doubler (css) {
  css.eachDecl(function (decl) {
    decl.parent.prepend(decl.clone())
  })
}
<commit_msg>Fix test on travis<commit_after>/* global it */

var assert = require('assert')
var gutil = require('gulp-util')
var postcss = require('./index')

it('should transform css with multiple processors', function (cb) {

  var stream = postcss(
    [ doubler, doubler ]
  , { map: false }  // omit source map for the test
  )

  stream.on('data', function (file) {
    var result = file.contents.toString('utf8')
    var target = 'a { color: black; color: black; color: black; color: black }'
    assert.equal( result, target )
    cb()
  })

  stream.write(new gutil.File({
    contents: new Buffer('a { color: black }')
  }))

  stream.end()

})

it('should correctly wrap postcss errors', function (cb) {

  var stream = postcss([ doubler ])

  stream.on('error', function (err) {
    assert.ok(err instanceof gutil.PluginError)
    assert.equal(err.plugin, 'gulp-postcss')
    cb()
  })

  stream.write(new gutil.File({
    contents: new Buffer('a {\n  a b {}\n}')
  }))

  stream.end()

})

it ('should throw error if processors are not provided', function (cb) {
  assert.throws( function () { postcss() }, gutil.PluginError )
  assert.throws( function () { postcss('') }, gutil.PluginError )
  assert.throws( function () { postcss({}) }, gutil.PluginError )
  cb()
})

function doubler (css) {
  css.eachDecl(function (decl) {
    decl.parent.prepend(decl.clone())
  })
}
<|endoftext|>


<commit_before>import os from 'os';
import {serial as test} from 'ava';
import importFresh from 'import-fresh';

const currentNodeVersion = process.versions.node;

test.beforeEach(() => {
	Object.defineProperty(process, 'platform', {
		value: 'linux'
	});

	Object.defineProperty(process.versions, 'node', {
		value: currentNodeVersion
	});

	process.stdout.isTTY = true;
	process.argv = [];
	process.env = {};
});

// FIXME
test.failing('return true if `FORCE_COLOR` is in env', t => {
	process.stdout.isTTY = false;
	process.env.FORCE_COLOR = true;
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 1);
});

test('return true if `FORCE_COLOR` is in env, but honor 256', t => {
	process.argv = ['--color=256'];
	process.env.FORCE_COLOR = true;
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);
});

test('return true if `FORCE_COLOR` is in env, but honor 256 #2', t => {
	process.argv = ['--color=256'];
	process.env.FORCE_COLOR = '1';
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);
});

test('return false if `FORCE_COLOR` is in env and is 0', t => {
	process.env.FORCE_COLOR = '0';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false if not TTY', t => {
	process.stdout.isTTY = false;
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false if --no-color flag is used', t => {
	process.env = {TERM: 'xterm-256color'};
	process.argv = ['--no-color'];
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false if --no-colors flag is used', t => {
	process.env = {TERM: 'xterm-256color'};
	process.argv = ['--no-colors'];
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return true if --color flag is used', t => {
	process.argv = ['--color'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if --colors flag is used', t => {
	process.argv = ['--colors'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `COLORTERM` is in env', t => {
	process.env.COLORTERM = true;
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=true` flag', t => {
	process.argv = ['--color=true'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=always` flag', t => {
	process.argv = ['--color=always'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=false` flag', t => {
	process.env = {TERM: 'xterm-256color'};
	process.argv = ['--color=false'];
	const result = importFresh('.');
	t.false(result.stdout);
});

test('support `--color=256` flag', t => {
	process.argv = ['--color=256'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('level should be 2 if `--color=256` flag is used', t => {
	process.argv = ['--color=256'];
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
	t.true(result.stdout.has256);
});

test('support `--color=16m` flag', t => {
	process.argv = ['--color=16m'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=full` flag', t => {
	process.argv = ['--color=full'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=truecolor` flag', t => {
	process.argv = ['--color=truecolor'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('level should be 3 if `--color=16m` flag is used', t => {
	process.argv = ['--color=16m'];
	const result = importFresh('.');
	t.is(result.stdout.level, 3);
	t.true(result.stdout.has256);
	t.true(result.stdout.has16m);
});

test('ignore post-terminator flags', t => {
	process.argv = ['--color', '--', '--no-color'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('allow tests of the properties on false', t => {
	process.env = {TERM: 'xterm-256color'};
	process.argv = ['--no-color'];
	const result = importFresh('.');
	t.is(result.stdout.hasBasic, undefined);
	t.is(result.stdout.has256, undefined);
	t.is(result.stdout.has16m, undefined);
	t.false(result.stdout.level > 0);
});

test('return false if `CI` is in env', t => {
	process.env.CI = 'AppVeyor';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return true if `TRAVIS` is in env', t => {
	process.env = {CI: 'Travis', TRAVIS: '1'};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `CIRCLECI` is in env', t => {
	process.env = {CI: true, CIRCLECI: true};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `APPVEYOR` is in env', t => {
	process.env = {CI: true, APPVEYOR: true};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `GITLAB_CI` is in env', t => {
	process.env = {CI: true, GITLAB_CI: true};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `BUILDKITE` is in env', t => {
	process.env = {CI: true, BUILDKITE: true};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if Codeship is in env', t => {
	process.env = {CI: true, CI_NAME: 'codeship'};
	const result = importFresh('.');
	t.truthy(result);
});

test('return false if `TEAMCITY_VERSION` is in env and is < 9.1', t => {
	process.env.TEAMCITY_VERSION = '9.0.5 (build 32523)';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return level 1 if `TEAMCITY_VERSION` is in env and is >= 9.1', t => {
	process.env.TEAMCITY_VERSION = '9.1.0 (build 32523)';
	const result = importFresh('.');
	t.is(result.stdout.level, 1);
});

test('support rxvt', t => {
	process.env = {TERM: 'rxvt'};
	const result = importFresh('.');
	t.is(result.stdout.level, 1);
});

test('prefer level 2/xterm over COLORTERM', t => {
	process.env = {COLORTERM: '1', TERM: 'xterm-256color'};
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('support screen-256color', t => {
	process.env = {TERM: 'screen-256color'};
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('support putty-256color', t => {
	process.env = {TERM: 'putty-256color'};
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('level should be 3 when using iTerm 3.0', t => {
	Object.defineProperty(process, 'platform', {
		value: 'darwin'
	});
	process.env = {
		TERM_PROGRAM: 'iTerm.app',
		TERM_PROGRAM_VERSION: '3.0.10'
	};
	const result = importFresh('.');
	t.is(result.stdout.level, 3);
});

test('level should be 2 when using iTerm 2.9', t => {
	Object.defineProperty(process, 'platform', {
		value: 'darwin'
	});
	process.env = {
		TERM_PROGRAM: 'iTerm.app',
		TERM_PROGRAM_VERSION: '2.9.3'
	};
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('return level 1 if on Windows earlier than 10 build 10586', t => {
	Object.defineProperty(process, 'platform', {
		value: 'win32'
	});
	Object.defineProperty(process.versions, 'node', {
		value: '8.0.0'
	});
	os.release = () => '10.0.10240';
	const result = importFresh('.');
	t.is(result.stdout.level, 1);
});

test('return level 2 if on Windows 10 build 10586 or later', t => {
	Object.defineProperty(process, 'platform', {
		value: 'win32'
	});
	Object.defineProperty(process.versions, 'node', {
		value: '8.0.0'
	});
	os.release = () => '10.0.10586';
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('return level 3 if on Windows 10 build 14931 or later', t => {
	Object.defineProperty(process, 'platform', {
		value: 'win32'
	});
	Object.defineProperty(process.versions, 'node', {
		value: '8.0.0'
	});
	os.release = () => '10.0.14931';
	const result = importFresh('.');
	t.is(result.stdout.level, 3);
});

test('return level 2 when FORCE_COLOR is set when not TTY in xterm256', t => {
	process.stdout.isTTY = false;
	process.env.FORCE_COLOR = true;
	process.env.TERM = 'xterm-256color';
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);
});

test('supports setting a color level using FORCE_COLOR', t => {
	let result;
	process.env.FORCE_COLOR = '1';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 1);

	process.env.FORCE_COLOR = '2';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);

	process.env.FORCE_COLOR = '3';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 3);

	process.env.FORCE_COLOR = '0';
	result = importFresh('.');
	t.false(result.stdout);
});

test('FORCE_COLOR maxes out at a value of 3', t => {
	process.env.FORCE_COLOR = '4';
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 3);
});

test('FORCE_COLOR works when set via command line (all values are strings)', t => {
	let result;
	process.env.FORCE_COLOR = 'true';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 1);

	process.stdout.isTTY = false;
	process.env.FORCE_COLOR = 'true';
	process.env.TERM = 'xterm-256color';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);

	process.env.FORCE_COLOR = 'false';
	result = importFresh('.');
	t.false(result.stdout);
});

test('return false when `TERM` is set to dumb', t => {
	process.env.TERM = 'dumb';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false when `TERM` is set to dumb when `TERM_PROGRAM` is set', t => {
	process.env.TERM = 'dumb';
	process.env.TERM_PROGRAM = 'Apple_Terminal';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false when `TERM` is set to dumb when run on Windows', t => {
	Object.defineProperty(process, 'platform', {
		value: 'win32'
	});
	Object.defineProperty(process.versions, 'node', {
		value: '10.13.0'
	});
	os.release = () => '10.0.14931';
	process.env.TERM = 'dumb';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return level 1 when `TERM` is set to dumb when `FORCE_COLOR` is set', t => {
	process.env.FORCE_COLOR = '1';
	process.env.TERM = 'dumb';
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 1);
});

test('ignore flags when sniffFlags=false', t => {
	process.argv = ['--color=256'];
	process.env.TERM = 'dumb';
	const result = importFresh('.');

	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);

	const sniffResult = result.supportsColor(process.stdout, {sniffFlags: true});
	t.truthy(sniffResult);
	t.is(sniffResult.level, 2);

	const nosniffResult = result.supportsColor(process.stdout, {sniffFlags: false});
	t.falsy(nosniffResult);
});
<commit_msg>Fix tests<commit_after>import os from 'os';
import tty from 'tty';
import {serial as test} from 'ava';
import importFresh from 'import-fresh';

const currentNodeVersion = process.versions.node;

test.beforeEach(() => {
	Object.defineProperty(process, 'platform', {
		value: 'linux'
	});

	Object.defineProperty(process.versions, 'node', {
		value: currentNodeVersion
	});

	process.stdout.isTTY = true;
	process.argv = [];
	process.env = {};
	tty.isatty = () => true;
});

// FIXME
test.failing('return true if `FORCE_COLOR` is in env', t => {
	process.stdout.isTTY = false;
	process.env.FORCE_COLOR = true;
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 1);
});

test('return true if `FORCE_COLOR` is in env, but honor 256', t => {
	process.argv = ['--color=256'];
	process.env.FORCE_COLOR = true;
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);
});

test('return true if `FORCE_COLOR` is in env, but honor 256 #2', t => {
	process.argv = ['--color=256'];
	process.env.FORCE_COLOR = '1';
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);
});

test('return false if `FORCE_COLOR` is in env and is 0', t => {
	process.env.FORCE_COLOR = '0';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false if not TTY', t => {
	process.stdout.isTTY = false;
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false if --no-color flag is used', t => {
	process.env = {TERM: 'xterm-256color'};
	process.argv = ['--no-color'];
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false if --no-colors flag is used', t => {
	process.env = {TERM: 'xterm-256color'};
	process.argv = ['--no-colors'];
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return true if --color flag is used', t => {
	process.argv = ['--color'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if --colors flag is used', t => {
	process.argv = ['--colors'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `COLORTERM` is in env', t => {
	process.env.COLORTERM = true;
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=true` flag', t => {
	process.argv = ['--color=true'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=always` flag', t => {
	process.argv = ['--color=always'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=false` flag', t => {
	process.env = {TERM: 'xterm-256color'};
	process.argv = ['--color=false'];
	const result = importFresh('.');
	t.false(result.stdout);
});

test('support `--color=256` flag', t => {
	process.argv = ['--color=256'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('level should be 2 if `--color=256` flag is used', t => {
	process.argv = ['--color=256'];
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
	t.true(result.stdout.has256);
});

test('support `--color=16m` flag', t => {
	process.argv = ['--color=16m'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=full` flag', t => {
	process.argv = ['--color=full'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('support `--color=truecolor` flag', t => {
	process.argv = ['--color=truecolor'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('level should be 3 if `--color=16m` flag is used', t => {
	process.argv = ['--color=16m'];
	const result = importFresh('.');
	t.is(result.stdout.level, 3);
	t.true(result.stdout.has256);
	t.true(result.stdout.has16m);
});

test('ignore post-terminator flags', t => {
	process.argv = ['--color', '--', '--no-color'];
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('allow tests of the properties on false', t => {
	process.env = {TERM: 'xterm-256color'};
	process.argv = ['--no-color'];
	const result = importFresh('.');
	t.is(result.stdout.hasBasic, undefined);
	t.is(result.stdout.has256, undefined);
	t.is(result.stdout.has16m, undefined);
	t.false(result.stdout.level > 0);
});

test('return false if `CI` is in env', t => {
	process.env.CI = 'AppVeyor';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return true if `TRAVIS` is in env', t => {
	process.env = {CI: 'Travis', TRAVIS: '1'};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `CIRCLECI` is in env', t => {
	process.env = {CI: true, CIRCLECI: true};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `APPVEYOR` is in env', t => {
	process.env = {CI: true, APPVEYOR: true};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `GITLAB_CI` is in env', t => {
	process.env = {CI: true, GITLAB_CI: true};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if `BUILDKITE` is in env', t => {
	process.env = {CI: true, BUILDKITE: true};
	const result = importFresh('.');
	t.truthy(result.stdout);
});

test('return true if Codeship is in env', t => {
	process.env = {CI: true, CI_NAME: 'codeship'};
	const result = importFresh('.');
	t.truthy(result);
});

test('return false if `TEAMCITY_VERSION` is in env and is < 9.1', t => {
	process.env.TEAMCITY_VERSION = '9.0.5 (build 32523)';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return level 1 if `TEAMCITY_VERSION` is in env and is >= 9.1', t => {
	process.env.TEAMCITY_VERSION = '9.1.0 (build 32523)';
	const result = importFresh('.');
	t.is(result.stdout.level, 1);
});

test('support rxvt', t => {
	process.env = {TERM: 'rxvt'};
	const result = importFresh('.');
	t.is(result.stdout.level, 1);
});

test('prefer level 2/xterm over COLORTERM', t => {
	process.env = {COLORTERM: '1', TERM: 'xterm-256color'};
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('support screen-256color', t => {
	process.env = {TERM: 'screen-256color'};
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('support putty-256color', t => {
	process.env = {TERM: 'putty-256color'};
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('level should be 3 when using iTerm 3.0', t => {
	Object.defineProperty(process, 'platform', {
		value: 'darwin'
	});
	process.env = {
		TERM_PROGRAM: 'iTerm.app',
		TERM_PROGRAM_VERSION: '3.0.10'
	};
	const result = importFresh('.');
	t.is(result.stdout.level, 3);
});

test('level should be 2 when using iTerm 2.9', t => {
	Object.defineProperty(process, 'platform', {
		value: 'darwin'
	});
	process.env = {
		TERM_PROGRAM: 'iTerm.app',
		TERM_PROGRAM_VERSION: '2.9.3'
	};
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('return level 1 if on Windows earlier than 10 build 10586', t => {
	Object.defineProperty(process, 'platform', {
		value: 'win32'
	});
	Object.defineProperty(process.versions, 'node', {
		value: '8.0.0'
	});
	os.release = () => '10.0.10240';
	const result = importFresh('.');
	t.is(result.stdout.level, 1);
});

test('return level 2 if on Windows 10 build 10586 or later', t => {
	Object.defineProperty(process, 'platform', {
		value: 'win32'
	});
	Object.defineProperty(process.versions, 'node', {
		value: '8.0.0'
	});
	os.release = () => '10.0.10586';
	const result = importFresh('.');
	t.is(result.stdout.level, 2);
});

test('return level 3 if on Windows 10 build 14931 or later', t => {
	Object.defineProperty(process, 'platform', {
		value: 'win32'
	});
	Object.defineProperty(process.versions, 'node', {
		value: '8.0.0'
	});
	os.release = () => '10.0.14931';
	const result = importFresh('.');
	t.is(result.stdout.level, 3);
});

test('return level 2 when FORCE_COLOR is set when not TTY in xterm256', t => {
	process.stdout.isTTY = false;
	process.env.FORCE_COLOR = true;
	process.env.TERM = 'xterm-256color';
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);
});

test('supports setting a color level using FORCE_COLOR', t => {
	let result;
	process.env.FORCE_COLOR = '1';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 1);

	process.env.FORCE_COLOR = '2';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);

	process.env.FORCE_COLOR = '3';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 3);

	process.env.FORCE_COLOR = '0';
	result = importFresh('.');
	t.false(result.stdout);
});

test('FORCE_COLOR maxes out at a value of 3', t => {
	process.env.FORCE_COLOR = '4';
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 3);
});

test('FORCE_COLOR works when set via command line (all values are strings)', t => {
	let result;
	process.env.FORCE_COLOR = 'true';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 1);

	process.stdout.isTTY = false;
	process.env.FORCE_COLOR = 'true';
	process.env.TERM = 'xterm-256color';
	result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);

	process.env.FORCE_COLOR = 'false';
	result = importFresh('.');
	t.false(result.stdout);
});

test('return false when `TERM` is set to dumb', t => {
	process.env.TERM = 'dumb';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false when `TERM` is set to dumb when `TERM_PROGRAM` is set', t => {
	process.env.TERM = 'dumb';
	process.env.TERM_PROGRAM = 'Apple_Terminal';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return false when `TERM` is set to dumb when run on Windows', t => {
	Object.defineProperty(process, 'platform', {
		value: 'win32'
	});
	Object.defineProperty(process.versions, 'node', {
		value: '10.13.0'
	});
	os.release = () => '10.0.14931';
	process.env.TERM = 'dumb';
	const result = importFresh('.');
	t.false(result.stdout);
});

test('return level 1 when `TERM` is set to dumb when `FORCE_COLOR` is set', t => {
	process.env.FORCE_COLOR = '1';
	process.env.TERM = 'dumb';
	const result = importFresh('.');
	t.truthy(result.stdout);
	t.is(result.stdout.level, 1);
});

test('ignore flags when sniffFlags=false', t => {
	process.argv = ['--color=256'];
	process.env.TERM = 'dumb';
	const result = importFresh('.');

	t.truthy(result.stdout);
	t.is(result.stdout.level, 2);

	const sniffResult = result.supportsColor(process.stdout, {sniffFlags: true});
	t.truthy(sniffResult);
	t.is(sniffResult.level, 2);

	const nosniffResult = result.supportsColor(process.stdout, {sniffFlags: false});
	t.falsy(nosniffResult);
});
<|endoftext|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-6-14 18:17:56<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|>