<commit_before>/*
Name:           cloudsight - test.js
Source & docs:  https://github.com/fvdm/nodejs-cloudsight
Feedback:       https://github.com/fvdm/nodejs-cloudsight/issues
License:        Unlicense (public domain)
*/

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

var cloudsight;
var cache = {
  token: null
};

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

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

cloudsight = app (config);

// module basics
dotest.add ('Module', function () {
  dotest.test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', cloudsight)
    .done ();
});

// upload image without status polling
dotest.add ('.request - upload without polling', function () {
  var image = {
    image: path.join (dir, 'test_image.png'),
    locale: 'nl-NL'
  };

  cloudsight.request (image, false, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isString ('warn', 'data.url', data && data.url)
      .done ();
  });
});

// upload image with status polling
dotest.add ('.request - upload with polling', function () {
  var image = {
    image: path.join (dir, 'test_image.png'),
    locale: 'nl-NL'
  };

  cloudsight.request (image, true, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.status', data && data.status, 'completed')
      .done ();
  });
});

// send image from url without status polling
dotest.add ('.request - url without polling', function () {
  var image = {
    remote_image_url: 'https://frankl.in/u/test_image.png',
    locale: 'nl-NL'
  };

  cloudsight.request (image, false, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isString ('warn', 'data.url', data && data.url)
      .done ();
  });
});

// send image from url with status polling
dotest.add ('.request - url with polling', function () {
  var image = {
    remote_image_url: 'https://frankl.in/u/test_image.png',
    locale: 'nl-NL'
  };

  cloudsight.request (image, true, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.status', data && data.status, 'completed')
      .done ();
  });
});

// get image status
dotest.add ('.response', function () {
  cloudsight.response (cache.token, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.token', data && data.token, cache.token)
      .done ();
  });
});

// Start the tests
dotest.run ();
<commit_msg>Test: added .request and .response to interface test<commit_after>/*
Name:           cloudsight - test.js
Source & docs:  https://github.com/fvdm/nodejs-cloudsight
Feedback:       https://github.com/fvdm/nodejs-cloudsight/issues
License:        Unlicense (public domain)
*/

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

var cloudsight;
var cache = {
  token: null
};

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

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

cloudsight = app (config);

// module basics
dotest.add ('Module', function () {
  dotest.test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', cloudsight)
    .isFunction ('fail', '.request', cloudsight && cloudsight.request)
    .isFunction ('fail', '.response', cloudsight && cloudsight.response)
    .done ();
});

// upload image without status polling
dotest.add ('.request - upload without polling', function () {
  var image = {
    image: path.join (dir, 'test_image.png'),
    locale: 'nl-NL'
  };

  cloudsight.request (image, false, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isString ('warn', 'data.url', data && data.url)
      .done ();
  });
});

// upload image with status polling
dotest.add ('.request - upload with polling', function () {
  var image = {
    image: path.join (dir, 'test_image.png'),
    locale: 'nl-NL'
  };

  cloudsight.request (image, true, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.status', data && data.status, 'completed')
      .done ();
  });
});

// send image from url without status polling
dotest.add ('.request - url without polling', function () {
  var image = {
    remote_image_url: 'https://frankl.in/u/test_image.png',
    locale: 'nl-NL'
  };

  cloudsight.request (image, false, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isString ('warn', 'data.url', data && data.url)
      .done ();
  });
});

// send image from url with status polling
dotest.add ('.request - url with polling', function () {
  var image = {
    remote_image_url: 'https://frankl.in/u/test_image.png',
    locale: 'nl-NL'
  };

  cloudsight.request (image, true, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.status', data && data.status, 'completed')
      .done ();
  });
});

// get image status
dotest.add ('.response', function () {
  cloudsight.response (cache.token, function (err, data) {
    cache.token = data && data.token;
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.token', data && data.token, cache.token)
      .done ();
  });
});

// Start the tests
dotest.run ();
<|endoftext|>


<commit_before>'use strict';

var tape = require('tape');
var sinon = require('sinon');
var SandboxedModule = require('sandboxed-module');

SandboxedModule.registerBuiltInSourceTransformer('istanbul');

var parseGenericStub = sinon.stub().returns('parse-generic-return-value');
var toisuBody = SandboxedModule.require('../', {
  requires: {
    './lib/parseGeneric': parseGenericStub,
    body: 'text-body',
    'body/json': 'json-body',
    'body/form': 'form-body',
    'body/any': 'any-body'
  }
});

// Must be called at the end of each test which calls a middleware function.
function reset() {
  parseGenericStub.reset();
}

tape('toisuBody', function (t) {
  t.test('is an object', function (t) {
    t.equal(typeof toisuBody, 'object', 'is an object');
    t.ok(toisuBody, 'is not null');
    t.end();
  });

  t.test('has text, json, form, and any methods', function (t) {
    t.deepEqual(Object.keys(toisuBody).sort(), ['any', 'form', 'json', 'text'], 'correct property names');
    t.equal(typeof toisuBody.text, 'function', 'text is a method');
    t.equal(typeof toisuBody.json, 'function', 'json is a method');
    t.equal(typeof toisuBody.form, 'function', 'form is a method');
    t.equal(typeof toisuBody.any, 'function', 'any is a method');
    t.end();
  });

  t.test('the text method', function (t) {
    t.test('returns a function', function (t) {
      t.equal(typeof toisuBody.text('options'), 'function', 'is a function');
      t.end();
    });

    t.test('the returned function passes req, res, options, the textBody function and the context', function (t) {
      var middleware = toisuBody.text('options');

      middleware.call('the-context', 'req', 'res');

      t.equal(parseGenericStub.callCount, 1, 'calls parseGeneric once');
      t.deepEqual(parseGenericStub.args[0], ['req', 'res', 'options', 'text-body', 'the-context']);
      t.end();
      reset();
    });

    t.test('returns the return value of parseGeneric', function (t) {
      var middleware = toisuBody.text('options');
      var returnValue = middleware.call('the-context', 'req', 'res');

      t.equal(returnValue, 'parse-generic-return-value');
      t.end();
      reset();
    });
  });

  t.test('the json method', function (t) {
    t.test('returns a function', function (t) {
      t.equal(typeof toisuBody.json('options'), 'function', 'is a function');
      t.end();
    });

    t.test('the returned function passes req, res, options, the jsonBody function and the context', function (t) {
      var middleware = toisuBody.json('options');

      middleware.call('the-context', 'req', 'res');

      t.equal(parseGenericStub.callCount, 1, 'calls parseGeneric once');
      t.deepEqual(parseGenericStub.args[0], ['req', 'res', 'options', 'json-body', 'the-context']);
      t.end();
      reset();
    });

    t.test('returns the return value of parseGeneric', function (t) {
      var middleware = toisuBody.json('options');
      var returnValue = middleware.call('the-context', 'req', 'res');

      t.equal(returnValue, 'parse-generic-return-value');
      t.end();
      reset();
    });
  });

  t.test('the form method', function (t) {
    t.test('returns a function', function (t) {
      t.equal(typeof toisuBody.form('options'), 'function', 'is a function');
      t.end();
    });

    t.test('the returned function passes req, res, options, the formBody function and the context', function (t) {
      var middleware = toisuBody.form('options');

      middleware.call('the-context', 'req', 'res');

      t.equal(parseGenericStub.callCount, 1, 'calls parseGeneric once');
      t.deepEqual(parseGenericStub.args[0], ['req', 'res', 'options', 'form-body', 'the-context']);
      t.end();
      reset();
    });

    t.test('returns the return value of parseGeneric', function (t) {
      var middleware = toisuBody.form('options');
      var returnValue = middleware.call('the-context', 'req', 'res');

      t.equal(returnValue, 'parse-generic-return-value');
      t.end();
      reset();
    });
  });

  t.test('the any method', function (t) {
    t.test('returns a function', function (t) {
      t.equal(typeof toisuBody.any('options'), 'function', 'is a function');
      t.end();
    });

    t.test('the returned function passes req, res, options, the anyBody function and the context', function (t) {
      var middleware = toisuBody.any('options');

      middleware.call('the-context', 'req', 'res');

      t.equal(parseGenericStub.callCount, 1, 'calls parseGeneric once');
      t.deepEqual(parseGenericStub.args[0], ['req', 'res', 'options', 'any-body', 'the-context']);
      t.end();
      reset();
    });

    t.test('returns the return value of parseGeneric', function (t) {
      var middleware = toisuBody.any('options');
      var returnValue = middleware.call('the-context', 'req', 'res');

      t.equal(returnValue, 'parse-generic-return-value');
      t.end();
      reset();
    });
  });
});
<commit_msg>Fix tests.<commit_after>'use strict';

var tape = require('tape');
var sinon = require('sinon');
var SandboxedModule = require('sandboxed-module');

SandboxedModule.registerBuiltInSourceTransformer('istanbul');

var parseGenericStub = sinon.stub().returns('parse-generic-return-value');
var toisuBody = SandboxedModule.require('../', {
  requires: {
    './lib/parseGeneric': parseGenericStub,
    body: 'text-body',
    'body/json': 'json-body',
    'body/form': 'form-body',
    'body/any': 'any-body'
  }
});

// Must be called at the end of each test which calls a middleware function.
function reset() {
  parseGenericStub.reset();
}

tape('toisuBody', function (t) {
  t.test('is an object', function (t) {
    t.equal(typeof toisuBody, 'object', 'is an object');
    t.ok(toisuBody, 'is not null');
    t.end();
  });

  t.test('has text, json, form, and any methods', function (t) {
    t.deepEqual(Object.keys(toisuBody).sort(), ['any', 'form', 'json', 'text'], 'correct property names');
    t.equal(typeof toisuBody.text, 'function', 'text is a method');
    t.equal(typeof toisuBody.json, 'function', 'json is a method');
    t.equal(typeof toisuBody.form, 'function', 'form is a method');
    t.equal(typeof toisuBody.any, 'function', 'any is a method');
    t.end();
  });

  t.test('the text method', function (t) {
    t.test('returns a function', function (t) {
      t.equal(typeof toisuBody.text('options'), 'function', 'is a function');
      t.end();
    });

    t.test('the returned function passes req, res, options, the textBody function and the context', function (t) {
      var middleware = toisuBody.text('options');

      middleware.call('the-context', 'req', 'res');

      t.equal(parseGenericStub.callCount, 1, 'calls parseGeneric once');
      t.deepEqual(parseGenericStub.args[0], ['req', 'res', 'options', 'text-body', 'the-context']);
      t.end();
      reset();
    });
  });

  t.test('the json method', function (t) {
    t.test('returns a function', function (t) {
      t.equal(typeof toisuBody.json('options'), 'function', 'is a function');
      t.end();
    });

    t.test('the returned function passes req, res, options, the jsonBody function and the context', function (t) {
      var middleware = toisuBody.json('options');

      middleware.call('the-context', 'req', 'res');

      t.equal(parseGenericStub.callCount, 1, 'calls parseGeneric once');
      t.deepEqual(parseGenericStub.args[0], ['req', 'res', 'options', 'json-body', 'the-context']);
      t.end();
      reset();
    });
  });

  t.test('the form method', function (t) {
    t.test('returns a function', function (t) {
      t.equal(typeof toisuBody.form('options'), 'function', 'is a function');
      t.end();
    });

    t.test('the returned function passes req, res, options, the formBody function and the context', function (t) {
      var middleware = toisuBody.form('options');

      middleware.call('the-context', 'req', 'res');

      t.equal(parseGenericStub.callCount, 1, 'calls parseGeneric once');
      t.deepEqual(parseGenericStub.args[0], ['req', 'res', 'options', 'form-body', 'the-context']);
      t.end();
      reset();
    });
  });

  t.test('the any method', function (t) {
    t.test('returns a function', function (t) {
      t.equal(typeof toisuBody.any('options'), 'function', 'is a function');
      t.end();
    });

    t.test('the returned function passes req, res, options, the anyBody function and the context', function (t) {
      var middleware = toisuBody.any('options');

      middleware.call('the-context', 'req', 'res');

      t.equal(parseGenericStub.callCount, 1, 'calls parseGeneric once');
      t.deepEqual(parseGenericStub.args[0], ['req', 'res', 'options', 'any-body', 'the-context']);
      t.end();
      reset();
    });
  });
});
<|endoftext|>


<commit_before>/*
  Title: PostgreSQL JSON Data-Type

  An example of using PostgreSQL's JSON data-type.
  In this example we create a single table that can handle multiple types of different media and it's metadata.

  This example uses the promise API preferred in 2.0 and above.
*/

var Sequelize = require(__dirname + "/../../index")
  , config    = require(__dirname + "/../../test/config/config")
  , sequelize = new Sequelize(config.postgres.database, config.postgres.username, config.postgres.password, {
    dialect: 'postgres',
    logging: false
  });

var Content = sequelize.define('Content', {
    title: { type: Sequelize.STRING },
    type: { type: Sequelize.STRING }, // ENUM('Movie', 'Episode', 'Music Video') },
    metadata: { type: Sequelize.JSON }
  })
  , movie = Content.build({
    title: 'Grave of the Fireflies',
    type: 'Movie',
    metadata: {
      director: 'Isao Takahata',
      language: 'Japanese',
      year: 1988
    }
  })
  , episode = Content.build({
    title: 'Chapter 3',
    metadata: {
      season: 1,
      episode: 3,
      language: 'English',
      seriesTitle: 'House of Cards',
      genres: ['Drama', 'Political thriller']
    }
  });

sequelize.sync({ force: true })
  .then(function() {
    return sequelize.Promise.all([
      movie.save(),
      episode.save()
      ]);
  })
  .then(function() {
    console.log('=====================================');
    console.log('Searching for any content in Japanese');
    console.log('-------------------------------------');
    return Content.find({ where: "metadata->>'language' = 'Japanese'" })
      .then(function(content) {
        console.log('Result:', content.dataValues);
        console.log('=====================================');
      })
  })
  .then(function() {
    console.log('=====================================');
    console.log('Searching for any content in English');
    console.log('-------------------------------------');
    return Content.find({ where: "metadata->>'language' = 'English'" })
      .then(function(content) {
        console.log('Result:', content.dataValues);
        console.log('=====================================');
      })
  })
  .error(function(error) {
    console.log(error)
  });<commit_msg>Updated example<commit_after>/*
  Title: PostgreSQL JSON Data-Type

  An example of using PostgreSQL's JSON data-type.
  In this example we create a single table that can handle multiple types of different media and it's metadata.

  This example uses the promise API preferred in 2.0 and above.
*/

var Sequelize = require(__dirname + "/../../index")
  , config    = require(__dirname + "/../../test/config/config")
  , sequelize = new Sequelize(config.postgres.database, config.postgres.username, config.postgres.password, {
    dialect: 'postgres',
    logging: false
  });

var Content = sequelize.define('Content', {
    title: { type: Sequelize.STRING },
    type: { type: Sequelize.STRING }, // ENUM('Movie', 'Episode', 'Music Video') },
    metadata: { type: Sequelize.JSON }
  })
  , movie = Content.build({
    title: 'Grave of the Fireflies',
    type: 'Movie',
    metadata: {
      director: 'Isao Takahata',
      language: 'Japanese',
      year: 1988
    }
  })
  , episode = Content.build({
    title: 'Chapter 3',
    metadata: {
      season: 1,
      episode: 3,
      language: 'English',
      seriesTitle: 'House of Cards',
      genres: ['Drama', 'Political thriller']
    }
  });

sequelize.sync({ force: true })
  .then(function() {
    return sequelize.Promise.all([
      movie.save(),
      episode.save()
      ]);
  })
  .then(function() {
    console.log('=====================================');
    console.log('Searching for any content in Japanese');
    console.log('-------------------------------------');

    return Content.find({ where: Sequelize.json({ metadata: { language: 'Japanese' } }) })
      .then(function(content) {
        console.log('Result:', content.dataValues);
        console.log('=====================================');
      })
  })
  .then(function() {
    console.log('=====================================');
    console.log('Searching for any content in English');
    console.log('-------------------------------------');

    return Content.find({ where: "metadata->>'language' = 'English'" })
      .then(function(content) {
        console.log('Result:', content.dataValues);
        console.log('=====================================');
      })
  })
  .error(function(error) {
    console.log(error)
  });<|endoftext|>


<commit_before>/*!
 * hex-color-regex <https://github.com/regexps/hex-color-regex>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

/* jshint asi:true */

'use strict'

var test = require('assertit')
var hexColorRegex = require('./index')

var sixDigits = {
  pass: [
    '#afebe3',
    '#AFEBE3',
    '#3cb371',
    '#3CB371',
    '#556b2f',
    '#556B2F',
    '#708090',
    '#7b68ee',
    '#7B68EE',
    '#eeeeee',
    '#ffffff',
    '#123fff}',
    '#111111'
  ],
  fail: [
    'afebe3',
    'AFEBE3',
    '3cb371',
    'ABC371',
    '556b2f',
    '5A6B2F',
    '708090',
    '7b68ee',
    '7B68EE',
    'eeeeee',
    'ffffff',
    '111111',
    'afebef',
    '3c537f',
    '556B2f',
    '708135',
    'EE3EF1',
    '7f68ZY',
    '#7f68ZY',
    '#7z68ZY',
    '#GR68',
    '#Z68',
    '#666EFR'
  ]
}

var threeDigits = {
  pass: [
    '#afe',
    '#AF3',
    '#3cb',
    '#3CB',
    '#b2f',
    '#5B2',
    '#708',
    '#68e',
    '#7AF',
    '#777',
    '#FFF',
    '#fff',
    '#f3f}',
    '#111'
  ],
  fail: [
    'fff',
    '4zy',
    '4g1',
    '111',
    'Ge3',
    'zY1',
    '#ggg',
    '#4zy',
    '#4g1',
    '#Ge3',
    '#zY1'
  ]
}

test('hex-color-regex:', function () {
  test('in no strict mode', function () {
    test('six digit hex', function () {
      test('should be `true`', function () {
        sixDigits.pass.forEach(function (hex) {
          test('when `' + hex + '` value', function () {
            test.equal(hexColorRegex().test(hex), true)
          })
        })
      })
      test('should be `false`', function () {
        sixDigits.fail.forEach(function (hex) {
          test('when `' + hex + '` value', function () {
            test.equal(hexColorRegex().test(hex), false)
          })
        })
      })
    })
    test('three digit hex', function () {
      test('should be `true`', function () {
        threeDigits.pass.forEach(function (hex) {
          test('when `' + hex + '` value', function () {
            test.equal(hexColorRegex().test(hex), true)
          })
        })
      })
      test('should be `false`', function () {
        threeDigits.fail.forEach(function (hex) {
          test('when `' + hex + '` value', function () {
            test.equal(hexColorRegex().test(hex), false)
          })
        })
      })
    })
    test('using regex().exec(hex)', function () {
      sixDigits.pass.forEach(function (hex) {
        var hexed = hex.replace('}', '')
        test('should match `' + hexed + '` when `' + hex + '` hex', function () {
          var actual = hexColorRegex().exec(hex)[0]
          var expected = hexed

          test.equal(actual, expected)
        })
      })
      threeDigits.pass.forEach(function (hex) {
        var hexed = hex.replace('}', '')
        test('should match `' + hexed + '` when `' + hex + '` hex', function () {
          var actual = hexColorRegex().exec(hex)[0]
          var expected = hexed

          test.equal(actual, expected)
        })
      })
    })
  })
  test('in strict mode', function () {
    test('six digit hex `#123fff}` should return false', function () {
      test.equal(hexColorRegex({strict: true}).test('#123fff}'), false)
    })
    test('three digit hex `#f3f}` should return false', function () {
      test.equal(hexColorRegex({strict: true}).test('#f3f}'), false)
    })
  })
})
<commit_msg>add more tests<commit_after>/*!
 * hex-color-regex <https://github.com/regexps/hex-color-regex>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

/* jshint asi:true */

'use strict'

var test = require('assertit')
var hexColorRegex = require('./index')

var sixDigits = {
  pass: [
    '#afebe3',
    '#AFEBE3',
    '#3cb371',
    '#3CB371',
    '#556b2f',
    '#556B2F',
    '#708090',
    '#7b68ee',
    '#7B68EE',
    '#eeeeee',
    '#ffffff',
    '#123fff}',
    '#111111'
  ],
  fail: [
    'afebe3',
    'AFEBE3',
    '3cb371',
    'ABC371',
    '556b2f',
    '5A6B2F',
    '708090',
    '7b68ee',
    '7B68EE',
    'eeeeee',
    'ffffff',
    '111111',
    'afebef',
    '3c537f',
    '556B2f',
    '708135',
    'EE3EF1',
    '7f68ZY',
    '#7f68ZY',
    '#7z68ZY',
    '#GR68',
    '#Z68',
    '#666EFR'
  ]
}

var threeDigits = {
  pass: [
    '#afe',
    '#AF3',
    '#3cb',
    '#3CB',
    '#b2f',
    '#5B2',
    '#708',
    '#68e',
    '#7AF',
    '#777',
    '#FFF',
    '#fff',
    '#f3f}',
    '#111'
  ],
  fail: [
    'fff',
    '4zy',
    '4g1',
    '111',
    'Ge3',
    'zY1',
    '#ggg',
    '#4zy',
    '#4g1',
    '#Ge3',
    '#zY1'
  ]
}

test('hex-color-regex:', function () {
  test('in no strict mode', function () {
    test('six digit hex', function () {
      test('should be `true`', function () {
        sixDigits.pass.forEach(function (hex) {
          test('when `' + hex + '` value', function () {
            test.equal(hexColorRegex().test(hex), true)
          })
        })
        test('when `foo #ae3f4c bar` value', function () {
          test.equal(hexColorRegex().test('foo #ae3f4c bar'), true)
        })
      })
      test('should be `false`', function () {
        sixDigits.fail.forEach(function (hex) {
          test('when `' + hex + '` value', function () {
            test.equal(hexColorRegex().test(hex), false)
          })
        })
      })
    })
    test('three digit hex', function () {
      test('should be `true`', function () {
        threeDigits.pass.forEach(function (hex) {
          test('when `' + hex + '` value', function () {
            test.equal(hexColorRegex().test(hex), true)
          })
        })
        test('when `foo #e4f bar` value', function () {
          test.equal(hexColorRegex().test('foo #e4f bar'), true)
        })
      })
      test('should be `false`', function () {
        threeDigits.fail.forEach(function (hex) {
          test('when `' + hex + '` value', function () {
            test.equal(hexColorRegex().test(hex), false)
          })
        })
      })
    })
    test('using regex().exec(hex)', function () {
      sixDigits.pass.forEach(function (hex) {
        var hexed = hex.replace('}', '')
        test('should match `' + hexed + '` when `' + hex + '` hex', function () {
          var actual = hexColorRegex().exec(hex)[0]
          var expected = hexed

          test.equal(actual, expected)
        })
      })
      test('should match `#ae3f4c` when `foo #ae3f4c bar` string', function () {
        var actual = hexColorRegex().exec('foo #ae3f4c bar')[0]
        var expected = '#ae3f4c'

        test.equal(actual, expected)
      })
      threeDigits.pass.forEach(function (hex) {
        var hexed = hex.replace('}', '')
        test('should match `' + hexed + '` when `' + hex + '` hex', function () {
          var actual = hexColorRegex().exec(hex)[0]
          var expected = hexed

          test.equal(actual, expected)
        })
      })
      test('should match `#e7f` when `foo #e7f bar` string', function () {
        var actual = hexColorRegex().exec('foo #e7f bar')[0]
        var expected = '#e7f'

        test.equal(actual, expected)
      })
    })
  })
  test('in strict mode', function () {
    test('six digit hex `#123fff}` should return false', function () {
      test.equal(hexColorRegex({strict: true}).test('#123fff}'), false)
    })
    test('string contain six digit hex `foo #ae3f4c bar` return false', function () {
      test.equal(hexColorRegex({strict: true}).test('foo #ae3f4c bar'), false)
    })
    test('three digit hex `#f3f}` should return false', function () {
      test.equal(hexColorRegex({strict: true}).test('#f3f}'), false)
    })
    test('string contain three digit hex `foo #e7f bar` return false', function () {
      test.equal(hexColorRegex({strict: true}).test('foo #e7f bar'), false)
    })
    test('should not match when `foo #ae3f4c bar` string', function () {
      var actual = hexColorRegex({strict: true}).exec('foo #ae3f4c bar')
      var expected = null

      test.equal(actual, expected)
    })
    test('should not match when `foo #e7f bar` string', function () {
      var actual = hexColorRegex({strict: true}).exec('foo #e7f bar')
      var expected = null

      test.equal(actual, expected)
    })
  })
})
<|endoftext|>


<commit_before>import { join } from 'path';

import { transform } from 'babel-core';

import plugin from 'index';

describe('module-resolver', () => {
  function testWithImport(source, output, transformerOpts) {
    const code = `import something from "${source}";`;
    const result = transform(code, transformerOpts);

    expect(result.code).toBe(`import something from "${output}";`);
  }

  describe('root', () => {
    describe('simple root', () => {
      const rootTransformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: [
              './test/testproject/src',
            ],
          }],
        ],
      };

      it('should resolve the file path', () => {
        testWithImport(
          'app',
          './test/testproject/src/app',
          rootTransformerOpts,
        );
      });

      it('should resolve the sub file path', () => {
        testWithImport(
          'components/Root',
          './test/testproject/src/components/Root',
          rootTransformerOpts,
        );
      });

      it('should resolve a sub file path without /index', () => {
        testWithImport(
          'components/Header',
          './test/testproject/src/components/Header',
          rootTransformerOpts,
        );
      });

      it('should resolve the file path while keeping the extension', () => {
        testWithImport(
          'components/Header/header.css',
          './test/testproject/src/components/Header/header.css',
          rootTransformerOpts,
        );
      });

      it('should resolve the file path with an extension that is non-standard in node', () => {
        testWithImport(
          'es6module',
          './test/testproject/src/es6module',
          rootTransformerOpts,
        );
      });

      it('should not resolve the file path with an unknown extension', () => {
        testWithImport(
          'text',
          'text',
          rootTransformerOpts,
        );
      });

      it('should resolve the file path with a filename containing a dot', () => {
        testWithImport(
          'libs/custom.modernizr3',
          './test/testproject/src/libs/custom.modernizr3',
          rootTransformerOpts,
        );
      });

      it('should resolve to a file instead of a directory', () => {
        // When a file and a directory on the same level share the same name,
        // the file has priority according to the Node require mechanism
        testWithImport(
          'constants',
          '../constants',
          {
            ...rootTransformerOpts,
            filename: './test/testproject/src/constants/actions.js',
          },
        );
      });

      it('should not resolve a path outside of the root directory', () => {
        testWithImport(
          'lodash/omit',
          'lodash/omit',
          rootTransformerOpts,
        );
      });

      it('should not try to resolve a local path', () => {
        testWithImport(
          './something',
          './something',
          rootTransformerOpts,
        );
      });
    });

    describe('glob root', () => {
      const globRootTransformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: [
              './test/testproject/src/**',
            ],
          }],
        ],
      };

      it('should resolve the file path right inside the glob', () => {
        testWithImport(
          'app',
          './test/testproject/src/app',
          globRootTransformerOpts,
        );
      });

      it('should resolve the sub file path', () => {
        testWithImport(
          'actions/something',
          './test/testproject/src/actions/something',
          globRootTransformerOpts,
        );
      });

      it('should resolve the sub file path without specifying the directory', () => {
        testWithImport(
          'something',
          './test/testproject/src/actions/something',
          globRootTransformerOpts,
        );
      });

      it('should resolve the deep file', () => {
        testWithImport(
          'SidebarFooterButton',
          './test/testproject/src/components/Sidebar/Footer/SidebarFooterButton',
          globRootTransformerOpts,
        );
      });
    });

    describe('non-standard extensions', () => {
      const rootTransformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: [
              './test/testproject/src',
            ],
            extensions: ['.txt'],
          }],
        ],
      };

      it('should not resolve the file path with an unknown extension', () => {
        testWithImport(
          'app',
          'app',
          rootTransformerOpts,
        );
      });

      it('should resolve the file path with a known defined extension', () => {
        testWithImport(
          'text',
          './test/testproject/src/text',
          rootTransformerOpts,
        );
      });
    });
  });

  describe('alias', () => {
    const aliasTransformerOpts = {
      plugins: [
        [plugin, {
          alias: {
            test: './test/testproject/test',
            libs: './test/testproject/src/libs',
            components: './test/testproject/src/components',
            '~': './test/testproject/src',
            'awesome/components': './test/testproject/src/components',
            abstract: 'npm:concrete',
            underscore: 'lodash',
            prefix: 'prefix/lib',
            '^@namespace/foo-(.+)': 'packages/\\1',
            'styles/.+\\.(css|less|scss)$': 'style-proxy.\\1',
            '^single-backslash': 'pas\\\\sed',
            '^non-existing-match': 'pas\\42sed',
            '^regexp-priority': 'miss',
            'regexp-priority$': 'miss',
            'regexp-priority': 'hit',
          },
        }],
      ],
    };

    describe('with a simple alias', () => {
      it('should alias the file path', () => {
        testWithImport(
          'components',
          './test/testproject/src/components',
          aliasTransformerOpts,
        );
      });

      it('should alias the sub file path', () => {
        testWithImport(
          'test/tools',
          './test/testproject/test/tools',
          aliasTransformerOpts,
        );
      });
    });

    describe('with an alias containing a slash', () => {
      it('should alias the file path', () => {
        testWithImport(
          'awesome/components',
          './test/testproject/src/components',
          aliasTransformerOpts,
        );
      });

      it('should alias the sub file path', () => {
        testWithImport(
          'awesome/components/Header',
          './test/testproject/src/components/Header',
          aliasTransformerOpts,
        );
      });
    });

    it('should alias a path containing a dot in the filename', () => {
      testWithImport(
        'libs/custom.modernizr3',
        './test/testproject/src/libs/custom.modernizr3',
        aliasTransformerOpts,
      );
    });

    it('should alias the path with its extension', () => {
      testWithImport(
        'components/Header/header.css',
        './test/testproject/src/components/Header/header.css',
        aliasTransformerOpts,
      );
    });

    describe('should not alias a unknown path', () => {
      it('when requiring a node module', () => {
        testWithImport(
          'other-lib',
          'other-lib',
          aliasTransformerOpts,
        );
      });

      it('when requiring a specific un-mapped file', () => {
        testWithImport(
          './l/otherLib',
          './l/otherLib',
          aliasTransformerOpts,
        );
      });
    });

    it('(legacy) should support aliasing a node module with "npm:"', () => {
      testWithImport(
        'abstract/thing',
        'concrete/thing',
        aliasTransformerOpts,
      );
    });

    it('should support aliasing a node modules', () => {
      testWithImport(
        'underscore/map',
        'lodash/map',
        aliasTransformerOpts,
      );
    });

    describe('with a regular expression', () => {
      it('should support replacing parts of a path', () => {
        testWithImport(
          '@namespace/foo-bar',
          'packages/bar',
          aliasTransformerOpts,
        );
      });

      it('should support replacing parts of a complex path', () => {
        testWithImport(
          '@namespace/foo-bar/component.js',
          'packages/bar/component.js',
          aliasTransformerOpts,
        );
      });

      describe('should support complex regular expressions', () => {
        ['css', 'less', 'scss'].forEach((extension) => {
          it(`should handle the alias with the ${extension} extension`, () => {
            testWithImport(
              `styles/style.${extension}`,
              `style-proxy.${extension}`,
              aliasTransformerOpts,
            );
          });
        });
      });

      it('should ignore unmatched paths', () => {
        testWithImport(
          'styles/style.js',
          'styles/style.js',
          aliasTransformerOpts,
        );
      });

      it('should transform double backslash into a single one', () => {
        testWithImport(
          'single-backslash',
          // This is a string literal, so in the code it will actually be "pas\\sed"
          'pas\\\\sed',
          aliasTransformerOpts,
        );
      });

      it('should replece missing matches with an empty string', () => {
        testWithImport(
          'non-existing-match',
          'passed',
          aliasTransformerOpts,
        );
      });

      it('should have higher priority than a simple alias', () => {
        testWithImport(
          'regexp-priority',
          'hit',
          aliasTransformerOpts,
        );
      });
    });

    describe('with the plugin applied twice', () => {
      const doubleAliasTransformerOpts = {
        plugins: [
          [plugin, { root: ['.'] }],
          [plugin, {
            alias: {
              '^@namespace/foo-(.+)': 'packages/\\1',
            },
          }],
        ],
      };

      it('should support replacing parts of a path', () => {
        testWithImport(
          '@namespace/foo-bar',
          'packages/bar',
          doubleAliasTransformerOpts,
        );
      });
    });
  });

  describe('with custom cwd', () => {
    describe('custom value', () => {
      const transformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: [
              './testproject/src',
            ],
            alias: {
              test: './testproject/test',
            },
            cwd: join(process.cwd(), 'test'),
          }],
        ],
      };

      it('should resolve the sub file path', () => {
        testWithImport(
          'components/Root',
          './test/testproject/src/components/Root',
          transformerOpts,
        );
      });

      it('should alias the sub file path', () => {
        testWithImport(
          'test/tools',
          './test/testproject/test/tools',
          transformerOpts,
        );
      });
    });
  });

  describe('babelrc', () => {
    const transformerOpts = {
      babelrc: false,
      plugins: [
        [plugin, {
          root: [
            './src',
          ],
          alias: {
            test: './test',
          },
          cwd: 'babelrc',
        }],
      ],
      filename: './test/testproject/src/app.js',
    };

    it('should resolve the sub file path', () => {
      testWithImport(
        'components/Root',
        './components/Root',
        transformerOpts,
      );
    });

    it('should alias the sub file path', () => {
      testWithImport(
        'test/tools',
        '../test/tools',
        transformerOpts,
      );
    });

    describe('unknown filename', () => {
      const unknownFileTransformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: [
              './src',
            ],
            cwd: 'babelrc',
          }],
        ],
      };
      const cachedCwd = process.cwd();
      const babelRcDir = 'test/testproject';

      beforeEach(() => {
        process.chdir(babelRcDir);
      });

      afterEach(() => {
        process.chdir(cachedCwd);
      });

      it('should resolve the sub file path', () => {
        testWithImport(
          'components/Root',
          './src/components/Root',
          unknownFileTransformerOpts,
        );
      });
    });

    describe('missing babelrc in path (uses cwd)', () => {
      jest.mock('find-babel-config', () => ({
        sync: function findBabelConfigSync() {
          return { file: null, config: null };
        },
      }));
      jest.resetModules();
      const pluginWithMock = require.requireActual('../src').default;

      const missingBabelConfigTransformerOpts = {
        babelrc: false,
        plugins: [
          [pluginWithMock, {
            root: [
              '.',
            ],
            cwd: 'babelrc',
          }],
        ],
        filename: './test/testproject/src/app.js',
      };

      it('should resolve the sub file path', () => {
        testWithImport(
          'test/testproject/src/components/Root',
          './components/Root',
          missingBabelConfigTransformerOpts,
        );
      });
    });
  });
});
<commit_msg>Add tests with glob root<commit_after>import { resolve } from 'path';

import { transform } from 'babel-core';

import plugin from 'index';

describe('module-resolver', () => {
  function testWithImport(source, output, transformerOpts) {
    const code = `import something from "${source}";`;
    const result = transform(code, transformerOpts);

    expect(result.code).toBe(`import something from "${output}";`);
  }

  describe('root', () => {
    describe('simple root', () => {
      const rootTransformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: [
              './test/testproject/src',
            ],
          }],
        ],
      };

      it('should resolve the file path', () => {
        testWithImport(
          'app',
          './test/testproject/src/app',
          rootTransformerOpts,
        );
      });

      it('should resolve the sub file path', () => {
        testWithImport(
          'components/Root',
          './test/testproject/src/components/Root',
          rootTransformerOpts,
        );
      });

      it('should resolve a sub file path without /index', () => {
        testWithImport(
          'components/Header',
          './test/testproject/src/components/Header',
          rootTransformerOpts,
        );
      });

      it('should resolve the file path while keeping the extension', () => {
        testWithImport(
          'components/Header/header.css',
          './test/testproject/src/components/Header/header.css',
          rootTransformerOpts,
        );
      });

      it('should resolve the file path with an extension that is non-standard in node', () => {
        testWithImport(
          'es6module',
          './test/testproject/src/es6module',
          rootTransformerOpts,
        );
      });

      it('should not resolve the file path with an unknown extension', () => {
        testWithImport(
          'text',
          'text',
          rootTransformerOpts,
        );
      });

      it('should resolve the file path with a filename containing a dot', () => {
        testWithImport(
          'libs/custom.modernizr3',
          './test/testproject/src/libs/custom.modernizr3',
          rootTransformerOpts,
        );
      });

      it('should resolve to a file instead of a directory', () => {
        // When a file and a directory on the same level share the same name,
        // the file has priority according to the Node require mechanism
        testWithImport(
          'constants',
          '../constants',
          {
            ...rootTransformerOpts,
            filename: './test/testproject/src/constants/actions.js',
          },
        );
      });

      it('should not resolve a path outside of the root directory', () => {
        testWithImport(
          'lodash/omit',
          'lodash/omit',
          rootTransformerOpts,
        );
      });

      it('should not try to resolve a local path', () => {
        testWithImport(
          './something',
          './something',
          rootTransformerOpts,
        );
      });
    });

    describe('glob root', () => {
      const globRootTransformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: [
              './test/testproject/src/**',
            ],
          }],
        ],
      };

      it('should resolve the file path right inside the glob', () => {
        testWithImport(
          'app',
          './test/testproject/src/app',
          globRootTransformerOpts,
        );
      });

      it('should resolve the sub file path', () => {
        testWithImport(
          'actions/something',
          './test/testproject/src/actions/something',
          globRootTransformerOpts,
        );
      });

      it('should resolve the sub file path without specifying the directory', () => {
        testWithImport(
          'something',
          './test/testproject/src/actions/something',
          globRootTransformerOpts,
        );
      });

      it('should resolve the deep file', () => {
        testWithImport(
          'SidebarFooterButton',
          './test/testproject/src/components/Sidebar/Footer/SidebarFooterButton',
          globRootTransformerOpts,
        );
      });
    });

    describe('non-standard extensions', () => {
      const rootTransformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: [
              './test/testproject/src',
            ],
            extensions: ['.txt'],
          }],
        ],
      };

      it('should not resolve the file path with an unknown extension', () => {
        testWithImport(
          'app',
          'app',
          rootTransformerOpts,
        );
      });

      it('should resolve the file path with a known defined extension', () => {
        testWithImport(
          'text',
          './test/testproject/src/text',
          rootTransformerOpts,
        );
      });
    });
  });

  describe('alias', () => {
    const aliasTransformerOpts = {
      plugins: [
        [plugin, {
          alias: {
            test: './test/testproject/test',
            libs: './test/testproject/src/libs',
            components: './test/testproject/src/components',
            '~': './test/testproject/src',
            'awesome/components': './test/testproject/src/components',
            abstract: 'npm:concrete',
            underscore: 'lodash',
            prefix: 'prefix/lib',
            '^@namespace/foo-(.+)': 'packages/\\1',
            'styles/.+\\.(css|less|scss)$': 'style-proxy.\\1',
            '^single-backslash': 'pas\\\\sed',
            '^non-existing-match': 'pas\\42sed',
            '^regexp-priority': 'miss',
            'regexp-priority$': 'miss',
            'regexp-priority': 'hit',
          },
        }],
      ],
    };

    describe('with a simple alias', () => {
      it('should alias the file path', () => {
        testWithImport(
          'components',
          './test/testproject/src/components',
          aliasTransformerOpts,
        );
      });

      it('should alias the sub file path', () => {
        testWithImport(
          'test/tools',
          './test/testproject/test/tools',
          aliasTransformerOpts,
        );
      });
    });

    describe('with an alias containing a slash', () => {
      it('should alias the file path', () => {
        testWithImport(
          'awesome/components',
          './test/testproject/src/components',
          aliasTransformerOpts,
        );
      });

      it('should alias the sub file path', () => {
        testWithImport(
          'awesome/components/Header',
          './test/testproject/src/components/Header',
          aliasTransformerOpts,
        );
      });
    });

    it('should alias a path containing a dot in the filename', () => {
      testWithImport(
        'libs/custom.modernizr3',
        './test/testproject/src/libs/custom.modernizr3',
        aliasTransformerOpts,
      );
    });

    it('should alias the path with its extension', () => {
      testWithImport(
        'components/Header/header.css',
        './test/testproject/src/components/Header/header.css',
        aliasTransformerOpts,
      );
    });

    describe('should not alias a unknown path', () => {
      it('when requiring a node module', () => {
        testWithImport(
          'other-lib',
          'other-lib',
          aliasTransformerOpts,
        );
      });

      it('when requiring a specific un-mapped file', () => {
        testWithImport(
          './l/otherLib',
          './l/otherLib',
          aliasTransformerOpts,
        );
      });
    });

    it('(legacy) should support aliasing a node module with "npm:"', () => {
      testWithImport(
        'abstract/thing',
        'concrete/thing',
        aliasTransformerOpts,
      );
    });

    it('should support aliasing a node modules', () => {
      testWithImport(
        'underscore/map',
        'lodash/map',
        aliasTransformerOpts,
      );
    });

    describe('with a regular expression', () => {
      it('should support replacing parts of a path', () => {
        testWithImport(
          '@namespace/foo-bar',
          'packages/bar',
          aliasTransformerOpts,
        );
      });

      it('should support replacing parts of a complex path', () => {
        testWithImport(
          '@namespace/foo-bar/component.js',
          'packages/bar/component.js',
          aliasTransformerOpts,
        );
      });

      describe('should support complex regular expressions', () => {
        ['css', 'less', 'scss'].forEach((extension) => {
          it(`should handle the alias with the ${extension} extension`, () => {
            testWithImport(
              `styles/style.${extension}`,
              `style-proxy.${extension}`,
              aliasTransformerOpts,
            );
          });
        });
      });

      it('should ignore unmatched paths', () => {
        testWithImport(
          'styles/style.js',
          'styles/style.js',
          aliasTransformerOpts,
        );
      });

      it('should transform double backslash into a single one', () => {
        testWithImport(
          'single-backslash',
          // This is a string literal, so in the code it will actually be "pas\\sed"
          'pas\\\\sed',
          aliasTransformerOpts,
        );
      });

      it('should replece missing matches with an empty string', () => {
        testWithImport(
          'non-existing-match',
          'passed',
          aliasTransformerOpts,
        );
      });

      it('should have higher priority than a simple alias', () => {
        testWithImport(
          'regexp-priority',
          'hit',
          aliasTransformerOpts,
        );
      });
    });

    describe('with the plugin applied twice', () => {
      const doubleAliasTransformerOpts = {
        plugins: [
          [plugin, { root: ['.'] }],
          [plugin, {
            alias: {
              '^@namespace/foo-(.+)': 'packages/\\1',
            },
          }],
        ],
      };

      it('should support replacing parts of a path', () => {
        testWithImport(
          '@namespace/foo-bar',
          'packages/bar',
          doubleAliasTransformerOpts,
        );
      });
    });
  });

  describe('with custom cwd', () => {
    describe('custom value', () => {
      const transformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: ['./testproject/src'],
            alias: {
              test: './testproject/test',
            },
            cwd: resolve('test'),
          }],
        ],
      };

      it('should resolve the sub file path', () => {
        testWithImport(
          'components/Root',
          './test/testproject/src/components/Root',
          transformerOpts,
        );
      });

      it('should alias the sub file path', () => {
        testWithImport(
          'test/tools',
          './test/testproject/test/tools',
          transformerOpts,
        );
      });
    });

    describe('with root', () => {
      const transformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: ['./src'],
            cwd: resolve('test/testproject'),
          }],
        ],
      };

      it('should resolve the sub file path', () => {
        testWithImport(
          'components/Root',
          './test/testproject/src/components/Root',
          transformerOpts,
        );
      });
    });

    describe('with glob root', () => {
      const transformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: ['./src/**'],
            cwd: resolve('test/testproject'),
          }],
        ],
      };

      it('should resolve the sub file path', () => {
        testWithImport(
          'components/Root',
          './test/testproject/src/components/Root',
          transformerOpts,
        );
      });
    });
  });

  describe('babelrc', () => {
    const transformerOpts = {
      babelrc: false,
      plugins: [
        [plugin, {
          root: ['./src'],
          alias: {
            test: './test',
          },
          cwd: 'babelrc',
        }],
      ],
      filename: './test/testproject/src/app.js',
    };

    it('should resolve the sub file path', () => {
      testWithImport(
        'components/Root',
        './components/Root',
        transformerOpts,
      );
    });

    it('should alias the sub file path', () => {
      testWithImport(
        'test/tools',
        '../test/tools',
        transformerOpts,
      );
    });

    describe('unknown filename', () => {
      const unknownFileTransformerOpts = {
        babelrc: false,
        plugins: [
          [plugin, {
            root: [
              './src',
            ],
            cwd: 'babelrc',
          }],
        ],
      };
      const cachedCwd = process.cwd();
      const babelRcDir = 'test/testproject';

      beforeEach(() => {
        process.chdir(babelRcDir);
      });

      afterEach(() => {
        process.chdir(cachedCwd);
      });

      it('should resolve the sub file path', () => {
        testWithImport(
          'components/Root',
          './src/components/Root',
          unknownFileTransformerOpts,
        );
      });
    });

    describe('missing babelrc in path (uses cwd)', () => {
      jest.mock('find-babel-config', () => ({
        sync: function findBabelConfigSync() {
          return { file: null, config: null };
        },
      }));
      jest.resetModules();
      const pluginWithMock = require.requireActual('../src').default;

      const missingBabelConfigTransformerOpts = {
        babelrc: false,
        plugins: [
          [pluginWithMock, {
            root: [
              '.',
            ],
            cwd: 'babelrc',
          }],
        ],
        filename: './test/testproject/src/app.js',
      };

      it('should resolve the sub file path', () => {
        testWithImport(
          'test/testproject/src/components/Root',
          './components/Root',
          missingBabelConfigTransformerOpts,
        );
      });
    });
  });
});
<|endoftext|>


<commit_before>/* Donutio 2.2.0 by Michael Hohlovich */
(function( $ ) {
  $.fn.donutio = function(params) {
    var options = $.extend({
      "multiple": true,
      "color": "#f00",
      "backColor": "#eee",
      "radius": 200,
      "width": 10,
      "padding": 10,
      "type": "donut",
      "active": 0
    }, params);

    var containerSize = (options.radius + options.padding) * 2;
    var dataLength = options.data.length;

    var sum = dataSum(options.data);
    var offsets = getDataPositions(options.data, sum);
    var gap = (360 - offsets.reduce(function(a, b){return a + b})) / dataLength;

    if (options.multiple) {
      for (i = 0; i < dataLength; i++) {
        drawChart(containerSize, gap, options, offsets, i, this);
      };
    } else {
      drawChart(containerSize, gap, options, offsets, options.active, this);
    };

    return this;
  };

  var drawChart = function(containerSize, gap, options, offsets, current, $wrap) {
    var $donutContainer = createContainer(containerSize);

    var svg = createSvgElement("svg");
    svg.setAttribute('width', containerSize);
    svg.setAttribute('height', containerSize);

    var dashoffset = 0,
        newoffset = 0;

    for (j = 0; j < options.data.length; j++) {
      dashoffset = newoffset + gap;
      newoffset = dashoffset + offsets[j];

      var path = createSvgElement("path");
      if (options.type == "donut") {
        path.setAttribute("stroke-width", options.width);
        path.setAttribute("fill", "none");
        if (j == current) {
          path.setAttribute("stroke", options.color);
        } else {
          path.setAttribute("stroke", options.backColor);
        }
      } else {
        path.setAttribute("stroke-width", 0);
        if (j == current) {
          path.setAttribute("fill", options.color);
        } else {
          path.setAttribute("fill", options.backColor);
        }
      }
      path.setAttribute("d", describeArc(options.type, Math.floor(containerSize / 2), Math.floor(containerSize / 2), options.radius, dashoffset, newoffset));
      svg.appendChild(path);
    }

    $donutContainer.append(svg);

    if ("text" in options.data[current]) {
      options.data[current].text.forEach(function(value, index){
        var $text = $("").html(value);
        $donutContainer.append($text);
      });
    };

    $wrap.append($donutContainer);
  };

  var dataSum = function(data) {
    var sum = 0;
    data.forEach(function(obj, index){
      sum += Math.abs(obj.value);
    });
    return sum;
  };

  var getDataPositions = function(data, sum) {
    var offsets = [];
    data.forEach(function(obj, index){
      var percent = Math.floor(Math.abs(obj.value) / sum * 100);
      var offset = Math.ceil(360 / 100 * percent);
      offsets.push(offset);
    });
    return offsets;
  };

  var createContainer = function(size) {
    return $("
").css({"width": size, "height": size});
  };

  var createSvgElement = function(name) {
    var elem = document.createElementNS("http://www.w3.org/2000/svg", name);
    if (name == "svg") {
      elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
    }
    return elem;
  };

  var describeArc = function(type, x, y, radius, startAngle, endAngle){
    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);
    var arcSweep = endAngle - startAngle <= 180 ? "0" : "1";
    var d = [];
    if (type == "donut") {
      d = [
        "M", start.x, start.y,
        "A", radius, radius, 0, arcSweep, 0, end.x, end.y
      ].join(" ");
    } else {
      d = [
        "M", start.x, start.y,
        "A", radius, radius, 0, arcSweep, 0, end.x, end.y,
        "L", x,y,
        "L", start.x, start.y
      ].join(" ");
    }
    return d;
  };

  var polarToCartesian = function(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;
    return {
      x: centerX + (radius * Math.cos(angleInRadians)),
      y: centerY + (radius * Math.sin(angleInRadians))
    };
  };

})(jQuery);
<commit_msg>2.2.0 release<commit_after>/* Donutio 2.2.0 by Michael Hohlovich */
(function($) {
  $.fn.donutio = function(params) {
    var options = $.extend({
      "multiple": true,
      "color": "#f00",
      "backColor": "#eee",
      "radius": 200,
      "width": 10,
      "padding": 10,
      "type": "donut",
      "active": 0
    }, params);

    var containerSize = (options.radius + options.padding) * 2;
    var dataLength = options.data.length;

    var sum = dataSum(options.data);
    var offsets = getDataPositions(options.data, sum);
    var gap = (360 - offsets.reduce(function(a, b){return a + b})) / dataLength;

    if (options.multiple) {
      for (i = 0; i < dataLength; i++) {
        drawChart(containerSize, gap, options, offsets, i, this);
      };
    } else {
      drawChart(containerSize, gap, options, offsets, options.active, this);
    };

    return this;
  };

  var drawChart = function(containerSize, gap, options, offsets, current, $wrap) {
    var $donutContainer = createContainer(containerSize);

    var svg = createSvgElement("svg");
    svg.setAttribute('width', containerSize);
    svg.setAttribute('height', containerSize);

    var dashoffset = 0,
        newoffset = 0;

    for (j = 0; j < options.data.length; j++) {
      dashoffset = newoffset + gap;
      newoffset = dashoffset + offsets[j];

      var path = createSvgElement("path");
      if (options.type == "donut") {
        path.setAttribute("stroke-width", options.width);
        path.setAttribute("fill", "none");
        if (j == current) {
          path.setAttribute("stroke", options.color);
        } else {
          path.setAttribute("stroke", options.backColor);
        }
      } else {
        path.setAttribute("stroke-width", 0);
        if (j == current) {
          path.setAttribute("fill", options.color);
        } else {
          path.setAttribute("fill", options.backColor);
        }
      }
      path.setAttribute("d", describeArc(options.type, Math.floor(containerSize / 2), Math.floor(containerSize / 2), options.radius, dashoffset, newoffset));
      svg.appendChild(path);
    }

    $donutContainer.append(svg);

    if ("text" in options.data[current]) {
      options.data[current].text.forEach(function(value, index){
        var $text = $("").html(value);
        $donutContainer.append($text);
      });
    };

    $wrap.append($donutContainer);
  };

  var dataSum = function(data) {
    var sum = 0;
    data.forEach(function(obj, index){
      sum += Math.abs(obj.value);
    });
    return sum;
  };

  var getDataPositions = function(data, sum) {
    var offsets = [];
    data.forEach(function(obj, index){
      var percent = Math.floor(Math.abs(obj.value) / sum * 100);
      var offset = Math.ceil(360 / 100 * percent);
      offsets.push(offset);
    });
    return offsets;
  };

  var createContainer = function(size) {
    return $("
").css({"width": size, "height": size});
  };

  var createSvgElement = function(name) {
    var elem = document.createElementNS("http://www.w3.org/2000/svg", name);
    if (name == "svg") {
      elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
    }
    return elem;
  };

  var describeArc = function(type, x, y, radius, startAngle, endAngle){
    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);
    var arcSweep = endAngle - startAngle <= 180 ? "0" : "1";
    var d = [];
    if (type == "donut") {
      d = [
        "M", start.x, start.y,
        "A", radius, radius, 0, arcSweep, 0, end.x, end.y
      ].join(" ");
    } else {
      d = [
        "M", start.x, start.y,
        "A", radius, radius, 0, arcSweep, 0, end.x, end.y,
        "L", x,y,
        "L", start.x, start.y
      ].join(" ");
    }
    return d;
  };

  var polarToCartesian = function(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;
    return {
      x: centerX + (radius * Math.cos(angleInRadians)),
      y: centerY + (radius * Math.sin(angleInRadians))
    };
  };

})(jQuery);
<|endoftext|>


<commit_before>
/*!
 * Skeleton.js - CompositeView
 * Copyright(c) 2012 Rubén Norte <rubennorte@gmail.com>
 * MIT Licensed
 */

define([
  '../../view',
  'underscore'
], function(View, _){

  'use strict';

  var CompositeView = View.extend({

    views: {},

    setView: function(selector, view){
      // Remove current subview if exists
      if (this.views[selector])
        this.views[selector].remove();

      this.views[selector] = view;
      this.refresh();
    },

    render: function(){
      var self = this;

      // Detach subviews
      _(this.view).each(function(view){
        view.$el.detach();
      });

      // Render template, delegate events, etc.
      // super.render();
      View.prototype.render.call(this);

      // Append subviews
      _(this.view).each(function(view, selector){
        self.$(selector).append(view.render().el);
      });

      return this;
    },

    remove: function(){
      // Remove sub-views
      _(this.views).each(function(view){
        view.remove();
      });

      // super.remove();
      View.prototype.remove.call(this);
    }

  });

  return CompositeView;

});<commit_msg>Fixed error in composite view rendering.<commit_after>
/*!
 * Skeleton.js - CompositeView
 * Copyright(c) 2012 Rubén Norte <rubennorte@gmail.com>
 * MIT Licensed
 */

define([
  '../../view',
  'underscore'
], function(View, _){

  'use strict';

  var CompositeView = View.extend({

    views: {},

    setView: function(selector, view){
      // Remove current subview if exists
      if (this.views[selector])
        this.views[selector].remove();

      this.views[selector] = view;
      this.refresh();
    },

    render: function(){
      var self = this;

      // Detach subviews
      _(this.views).each(function(view){
        view.$el.detach();
      });

      // Render template, delegate events, etc.
      // super.render();
      View.prototype.render.call(this);

      // Append subviews
      _(this.views).each(function(view, selector){
        self.$(selector).append(view.render().el);
      });

      return this;
    },

    remove: function(){
      // Remove sub-views
      _(this.views).each(function(view){
        view.remove();
      });

      // super.remove();
      View.prototype.remove.call(this);
    }

  });

  return CompositeView;

});<|endoftext|>


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

/**
 * Clones several projects that are known to follow "JavaScript Standard Style" and runs
 * the `standard` style checker to verify that it passes without warnings. This helps
 * ensure we don't accidentally introduce new style rules that cause previously "good"
 * code to start failing with new warnings! (And if we do, then that needs to be a MAJOR
 * VERSION BUMP.)
 */

var cp = require('child_process')
var extend = require('extend.js')
var mkdirp = require('mkdirp')
var path = require('path')
var rimraf = require('rimraf')
var series = require('run-series')

var TMP = path.join(__dirname, 'tmp')
var STANDARD = path.join(__dirname, 'bin', 'cmd.js')

var urls = [
  'https://github.com/beatgammit/base64-js.git',
  'https://github.com/feross/bittorrent-dht.git',
  'https://github.com/feross/bittorrent-protocol.git',
  'https://github.com/feross/bittorrent-tracker.git',
  'https://github.com/feross/buffer.git',
  'https://github.com/feross/magnet-uri.git',
  'https://github.com/feross/parse-torrent.git',
  'https://github.com/feross/simple-peer.git',
  'https://github.com/feross/studynotes.git',
  'https://github.com/feross/webtorrent.git',
  'https://github.com/mafintosh/level-temp.git',
  'https://github.com/mafintosh/peerflix.git',
  'https://github.com/mafintosh/what-line-is-this.git'
]

var modules = {}
urls.forEach(function (url) {
  var name = /\/([^.\/]+)\.git$/.exec(url)[1]
  modules[name] = url
})

rimraf.sync(TMP)
mkdirp.sync(TMP)

series(Object.keys(modules).map(function (name) {
  var url = modules[name]
  return function (cb) {
    var args = [ 'clone', url, path.join(TMP, name) ]
    // TODO: Start `git` in a way that works on Windows – PR welcome!
    spawn('git', args, {}, cb)
  }
}), runTests)

function runTests (err) {
  if (err) return error(err)
  series(Object.keys(modules).map(function (name) {
    return function (cb) {
      process.stderr.write(name + ': ')
      var cwd = path.join(TMP, name)
      spawn(STANDARD, ['--verbose'], { cwd: cwd }, function (err) {
        if (err) return cb(err)
        console.error('ok')
        cb(null)
      })
    }
  }), function (err) {
    if (err) return error(err)
  })
}

function spawn (command, args, opts, cb) {
  var child = cp.spawn(command, args, extend({ stdio: 'inherit' }, opts))
  child.on('error', error)
  child.on('close', function (code) {
    if (code !== 0) cb(new Error('non-zero exit code: ' + code))
    else cb(null)
  })
  return child
}

function error (err) {
  console.error(err.stack || err.message || err)
  process.exit(1)
}
<commit_msg>change clone to --depth 1<commit_after>#!/usr/bin/env node

/**
 * Clones several projects that are known to follow "JavaScript Standard Style" and runs
 * the `standard` style checker to verify that it passes without warnings. This helps
 * ensure we don't accidentally introduce new style rules that cause previously "good"
 * code to start failing with new warnings! (And if we do, then that needs to be a MAJOR
 * VERSION BUMP.)
 */

var cp = require('child_process')
var extend = require('extend.js')
var mkdirp = require('mkdirp')
var path = require('path')
var rimraf = require('rimraf')
var series = require('run-series')

var TMP = path.join(__dirname, 'tmp')
var STANDARD = path.join(__dirname, 'bin', 'cmd.js')

var urls = [
  'https://github.com/beatgammit/base64-js.git',
  'https://github.com/feross/bittorrent-dht.git',
  'https://github.com/feross/bittorrent-protocol.git',
  'https://github.com/feross/bittorrent-tracker.git',
  'https://github.com/feross/buffer.git',
  'https://github.com/feross/magnet-uri.git',
  'https://github.com/feross/parse-torrent.git',
  'https://github.com/feross/simple-peer.git',
  'https://github.com/feross/studynotes.git',
  'https://github.com/feross/webtorrent.git',
  'https://github.com/mafintosh/level-temp.git',
  'https://github.com/mafintosh/peerflix.git',
  'https://github.com/mafintosh/what-line-is-this.git'
]

var modules = {}
urls.forEach(function (url) {
  var name = /\/([^.\/]+)\.git$/.exec(url)[1]
  modules[name] = url
})

rimraf.sync(TMP)
mkdirp.sync(TMP)

series(Object.keys(modules).map(function (name) {
  var url = modules[name]
  return function (cb) {
    var args = [ 'clone', '--depth', 1, url, path.join(TMP, name) ]
    // TODO: Start `git` in a way that works on Windows – PR welcome!
    spawn('git', args, {}, cb)
  }
}), runTests)

function runTests (err) {
  if (err) return error(err)
  series(Object.keys(modules).map(function (name) {
    return function (cb) {
      process.stderr.write(name + ': ')
      var cwd = path.join(TMP, name)
      spawn(STANDARD, ['--verbose'], { cwd: cwd }, function (err) {
        if (err) return cb(err)
        console.error('ok')
        cb(null)
      })
    }
  }), function (err) {
    if (err) return error(err)
  })
}

function spawn (command, args, opts, cb) {
  var child = cp.spawn(command, args, extend({ stdio: 'inherit' }, opts))
  child.on('error', error)
  child.on('close', function (code) {
    if (code !== 0) cb(new Error('non-zero exit code: ' + code))
    else cb(null)
  })
  return child
}

function error (err) {
  console.error(err.stack || err.message || err)
  process.exit(1)
}
<|endoftext|>