<commit_before>var
  Broker = require('../service/Broker'),
  HttpProxy = require('../service/HttpProxy'),
  Context = require('../core/Context'),
  fs = require('fs'),
  path = require('path'),
  _ = require('lodash');

/**
 * KuzzleProxy constructor
 *
 * @param {ProxyBackendHandler} BackendHandler
 * @param {String} applicationName
 * @constructor
 */
function KuzzleProxy (BackendHandler, applicationName) {
  /** @type {Object} */
  this.config = this.getRCConfig(applicationName);

  /** @type {Context} */
  this.context = new Context(BackendHandler, this.config.backendMode);

  /** @type {Broker} */
  this.broker = new Broker();

  /** @type {HttpProxy} */
  this.httpProxy = new HttpProxy();

  /** @type {Boolean} */
  this.isDummy = false;
}

/**
 * Returns RC configuration
 *
 * @returns {Object}
 */
KuzzleProxy.prototype.getRCConfig = function (applicationName) {
  if (applicationName === undefined) {
    applicationName = 'proxy';
  }

  return require('rc')(applicationName, {
    protocolPlugins: {},
    backendOptions: {},
    backendMode: 'standard',
    httpPort: 7511,
    backendTimeout: 10000
  });
};

/**
 * @param {String} rootFolder
 * Reads configuration files and initializes plugins
 */
KuzzleProxy.prototype.initPlugins = function (rootFolder) {
  var pluginsConfiguration = this.readPluginsConfiguration(rootFolder);

  _.forEach(pluginsConfiguration, (pluginConfiguration, pluginName) => {
    var
      plugin;

    if (pluginConfiguration.activated) {
      console.log(`Initializing plugin protocol ${pluginName}`);
      try {
        plugin = new (this.requirePluginPackage(rootFolder, pluginName))();
        plugin.init(pluginConfiguration, this.context, this.isDummy);

        this.context.pluginStore.add(plugin);
      } catch (error) {
        console.error(`Initialization of plugin ${pluginName} has failed; Reason :`, error);
      }
    }
  });

  if (this.context.pluginStore.count() === 0) {
    throw new Error('No plugin has been initialized properly. Shutting down.');
  }
};

/**
 * Intializes the broker
 */
KuzzleProxy.prototype.initBroker = function () {

  this.context.setBroker(this.broker);
  this.broker.init(this.context, this.config.backendOptions, this.config.backendTimeout);
};

/**
 * Initializes the httpProxy
 */
KuzzleProxy.prototype.initHttpProxy = function () {
  this.httpProxy.init(this.config.backendMode, this.context, this.config.httpPort);
};

/**
 * Updates plugins configuration in Kuzzle database
 *
 * @param {String} rootFolder
 * @returns {Object}
 */
KuzzleProxy.prototype.readPluginsConfiguration = function (rootFolder) {
  var
    pluginsConfiguration = {},
    currentConfig,
    plugins = this.config.protocolPlugins,
    activatedPlugins;

  try {
    currentConfig = this.loadCurrentConfig(rootFolder);
  }
  catch (error) {
    throw error;
  }

  if (Object.keys(plugins).length === 0) {
    throw new Error('No plugin configuration provided. Shutting down.');
  }

  Object.keys(plugins).forEach((pluginName) => {
    pluginsConfiguration[pluginName] = this.readOnePluginConfiguration(currentConfig, pluginName);
  });

  activatedPlugins = Object
    .keys(pluginsConfiguration)
    .map(pluginName => pluginsConfiguration[pluginName])
    .filter(pluginConfig => pluginConfig.activated);

  if (activatedPlugins.length === 0) {
    throw new Error('No plugin has been activated in configuration. Shutting down.');
  }

  return pluginsConfiguration;
};

/**
 * Interprets the package.json file of a plugin package to extract the configuration
 *
 * @param {String} rootFolder
 * @param currentConfig
 * @param pluginName
 * @returns {*}
 */
KuzzleProxy.prototype.readOnePluginConfiguration = function (rootFolder, currentConfig, pluginName) {
  var
    pluginPackage,
    pluginConfiguration = currentConfig[pluginName] || {};

  try {
    pluginPackage = this.requirePluginConfig(rootFolder, pluginName);

    if (pluginPackage.pluginInfo && pluginPackage.pluginInfo.defaultConfig) {
      pluginConfiguration = _.extend(pluginConfiguration, pluginPackage.pluginInfo.defaultConfig);
    }
  } catch (error) {
    console.error(`There is a problem with plugin ${pluginName}; Reason : ${error}`);
  }

  if (typeof pluginConfiguration.activated === 'undefined') {
    pluginConfiguration.activated = true;
  }

  return pluginConfiguration;
};

/**
 * Requires the npm package of the plugin
 *
 * @param {String} rootFolder
 * @param name
 */
KuzzleProxy.prototype.requirePluginPackage = function (rootFolder, name) {
  return require(this.getPathPlugin(rootFolder, name));
};

/**
 * Requires the npm package.json file of the plugin
 *
 * @param {String} rootFolder
 * @param {String} pluginName
 * @returns {{pluginInfo: {defaultConfig: *}}}
 */
KuzzleProxy.prototype.requirePluginConfig = function (rootFolder, pluginName) {
  return require(path.join(this.getPathPlugin(rootFolder, pluginName), 'package.json'));
};

/**
 * Return the real plugin path
 *
 * @param {String} rootFolder
 * @param pluginName
 * @returns {String}
 */
KuzzleProxy.prototype.getPathPlugin = function (rootFolder, pluginName) {
  var pluginConfig = this.config.protocolPlugins[pluginName];

  if (pluginConfig.path) {
    return pluginConfig.path;
  }

  return path.join(rootFolder, 'node_modules', pluginName);
};

/**
 * Loads current plugin config
 *
 * @param {String} rootFolder
 * @returns {Object}
 */
KuzzleProxy.prototype.loadCurrentConfig = function (rootFolder) {
  var jsonPluginsConfigPath = path.join(rootFolder, 'pluginsConfig.json');

  if (fs.existsSync(jsonPluginsConfigPath)) {
    return JSON.parse(fs.readFileSync(jsonPluginsConfigPath));
  }

  return {};
};

module.exports = KuzzleProxy;
<commit_msg>Make rootFolder configurable everywhere in order to implement LB properly on top of proxy<commit_after>var
  Broker = require('../service/Broker'),
  HttpProxy = require('../service/HttpProxy'),
  Context = require('../core/Context'),
  fs = require('fs'),
  path = require('path'),
  _ = require('lodash');

/**
 * KuzzleProxy constructor
 *
 * @param {ProxyBackendHandler} BackendHandler
 * @param {String} applicationName
 * @constructor
 */
function KuzzleProxy (BackendHandler, applicationName) {
  /** @type {Object} */
  this.config = this.getRCConfig(applicationName);

  /** @type {Context} */
  this.context = new Context(BackendHandler, this.config.backendMode);

  /** @type {Broker} */
  this.broker = new Broker();

  /** @type {HttpProxy} */
  this.httpProxy = new HttpProxy();

  /** @type {Boolean} */
  this.isDummy = false;
}

/**
 * Returns RC configuration
 *
 * @returns {Object}
 */
KuzzleProxy.prototype.getRCConfig = function (applicationName) {
  if (applicationName === undefined) {
    applicationName = 'proxy';
  }

  return require('rc')(applicationName, {
    protocolPlugins: {},
    backendOptions: {},
    backendMode: 'standard',
    httpPort: 7511,
    backendTimeout: 10000
  });
};

/**
 * @param {String} rootFolder
 * Reads configuration files and initializes plugins
 */
KuzzleProxy.prototype.initPlugins = function (rootFolder) {
  var pluginsConfiguration = this.readPluginsConfiguration(rootFolder);

  _.forEach(pluginsConfiguration, (pluginConfiguration, pluginName) => {
    var
      plugin;

    if (pluginConfiguration.activated) {
      console.log(`Initializing plugin protocol ${pluginName}`);
      try {
        plugin = new (this.requirePluginPackage(rootFolder, pluginName))();
        plugin.init(pluginConfiguration, this.context, this.isDummy);

        this.context.pluginStore.add(plugin);
      } catch (error) {
        console.error(`Initialization of plugin ${pluginName} has failed; Reason :`, error);
      }
    }
  });

  if (this.context.pluginStore.count() === 0) {
    throw new Error('No plugin has been initialized properly. Shutting down.');
  }
};

/**
 * Intializes the broker
 */
KuzzleProxy.prototype.initBroker = function () {

  this.context.setBroker(this.broker);
  this.broker.init(this.context, this.config.backendOptions, this.config.backendTimeout);
};

/**
 * Initializes the httpProxy
 */
KuzzleProxy.prototype.initHttpProxy = function () {
  this.httpProxy.init(this.config.backendMode, this.context, this.config.httpPort);
};

/**
 * Updates plugins configuration in Kuzzle database
 *
 * @param {String} rootFolder
 * @returns {Object}
 */
KuzzleProxy.prototype.readPluginsConfiguration = function (rootFolder) {
  var
    pluginsConfiguration = {},
    currentConfig,
    plugins = this.config.protocolPlugins,
    activatedPlugins;

  try {
    currentConfig = this.loadCurrentConfig(rootFolder);
  }
  catch (error) {
    throw error;
  }

  if (Object.keys(plugins).length === 0) {
    throw new Error('No plugin configuration provided. Shutting down.');
  }

  Object.keys(plugins).forEach((pluginName) => {
    pluginsConfiguration[pluginName] = this.readOnePluginConfiguration(rootFolder, currentConfig, pluginName);
  });

  activatedPlugins = Object
    .keys(pluginsConfiguration)
    .map(pluginName => pluginsConfiguration[pluginName])
    .filter(pluginConfig => pluginConfig.activated);

  if (activatedPlugins.length === 0) {
    throw new Error('No plugin has been activated in configuration. Shutting down.');
  }

  return pluginsConfiguration;
};

/**
 * Interprets the package.json file of a plugin package to extract the configuration
 *
 * @param {String} rootFolder
 * @param currentConfig
 * @param pluginName
 * @returns {*}
 */
KuzzleProxy.prototype.readOnePluginConfiguration = function (rootFolder, currentConfig, pluginName) {
  var
    pluginPackage,
    pluginConfiguration = currentConfig[pluginName] || {};

  try {
    pluginPackage = this.requirePluginConfig(rootFolder, pluginName);

    if (pluginPackage.pluginInfo && pluginPackage.pluginInfo.defaultConfig) {
      pluginConfiguration = _.extend(pluginConfiguration, pluginPackage.pluginInfo.defaultConfig);
    }
  } catch (error) {
    console.error(`There is a problem with plugin ${pluginName}; Reason : ${error}`);
  }

  if (typeof pluginConfiguration.activated === 'undefined') {
    pluginConfiguration.activated = true;
  }

  return pluginConfiguration;
};

/**
 * Requires the npm package of the plugin
 *
 * @param {String} rootFolder
 * @param name
 */
KuzzleProxy.prototype.requirePluginPackage = function (rootFolder, name) {
  return require(this.getPathPlugin(rootFolder, name));
};

/**
 * Requires the npm package.json file of the plugin
 *
 * @param {String} rootFolder
 * @param {String} pluginName
 * @returns {{pluginInfo: {defaultConfig: *}}}
 */
KuzzleProxy.prototype.requirePluginConfig = function (rootFolder, pluginName) {
  return require(path.join(this.getPathPlugin(rootFolder, pluginName), 'package.json'));
};

/**
 * Return the real plugin path
 *
 * @param {String} rootFolder
 * @param pluginName
 * @returns {String}
 */
KuzzleProxy.prototype.getPathPlugin = function (rootFolder, pluginName) {
  var pluginConfig = this.config.protocolPlugins[pluginName];

  if (pluginConfig.path) {
    return pluginConfig.path;
  }

  return path.join(rootFolder, 'node_modules', pluginName);
};

/**
 * Loads current plugin config
 *
 * @param {String} rootFolder
 * @returns {Object}
 */
KuzzleProxy.prototype.loadCurrentConfig = function (rootFolder) {
  var jsonPluginsConfigPath = path.join(rootFolder, 'pluginsConfig.json');

  if (fs.existsSync(jsonPluginsConfigPath)) {
    return JSON.parse(fs.readFileSync(jsonPluginsConfigPath));
  }

  return {};
};

module.exports = KuzzleProxy;
<|endoftext|>


<commit_before>var util = require('util');
var GEvents1 = require('./gevents.js');
var GEvents2 = require('./gevents.js');

GEvents1.on('bla', function() { console.log('bla', arguments); });

setInterval(function() {

  if(!(process.pid % 2)) {
    GEvents2.emit('bla', { some: 'data' }, 'bla', 'yadda');
  } else {
    GEvents2.globalEmit('bla', { some: 'data2' });
  }

}, 2000);
<commit_msg>minor naming convention fix<commit_after>var util = require('util');
var gEvents1 = require('./index.js');
var gEvents2 = require('./index.js');

gEvents1.on('bla', function() { console.log('bla', arguments); });

setInterval(function() {

  if(!(process.pid % 2)) {
    gEvents2.emit('bla', { some: 'data' }, 'bla', 'yadda');
  } else {
    gEvents2.globalEmit('bla', { some: 'data2' });
  }

}, 2000);
<|endoftext|>


<commit_before>import test from 'ava'
import prettifyHtml from './'

test('zero-out initial indentation', t => {
  const INPUT = `        <div>Indented Text</div>`
  const EXPECTED = '
Indented Text
'
  t.is(prettifyHtml(INPUT), EXPECTED)
})
test('siblings at top-level are consistently indended', t => {
  const INPUT = `

First

Second

Third

  `
  const EXPECTED = [
    '
First
',
    '
Second
',
    '
Third
',
  ].join('\n')

  t.is(prettifyHtml(INPUT), EXPECTED)
})
test('elements containing only text are trimmed/inlined', t => {
  const INPUT = `

   A bunch
    of text

    inside this element

  `
  const EXPECTED = `<div> A bunch of text inside this element </div>`
  t.is(prettifyHtml(INPUT), EXPECTED)
})

test('innerHTML of code/pre blocks is not altered', t => {
  const INPUT = `
    jQuery('selector').on('event', () => {
      // Comment
      window.alert('an alert');
    })
`

  t.is(prettifyHtml(INPUT), INPUT)
})

test.skip('prettify-html makes the html pretty', t => {
  const INPUT = `

Enrichment

          Turn any email or domain into a full person or company profile to qualify leads.

        Sign Up

  `

  const EXPECTED = `

			Enrichment

				Turn any email or domain into a full person or company profile to qualify leads.

			Sign Up

`

	const results = prettifyHtml(INPUT)

	t.is(results, EXPECTED)
})
<commit_msg>Added another test for code/pre which contain other tags<commit_after>import test from 'ava'
import prettifyHtml from './'

test('zero-out initial indentation', t => {
  const INPUT = `        <div>Indented Text</div>`
  const EXPECTED = '
Indented Text
'
  t.is(prettifyHtml(INPUT), EXPECTED)
})
test('siblings at top-level are consistently indended', t => {
  const INPUT = `

First

Second

Third

  `
  const EXPECTED = [
    '
First
',
    '
Second
',
    '
Third
',
  ].join('\n')

  t.is(prettifyHtml(INPUT), EXPECTED)
})
test('elements containing only text are trimmed/inlined', t => {
  const INPUT = `

   A bunch
    of text

    inside this element

  `
  const EXPECTED = `<div> A bunch of text inside this element </div>`
  t.is(prettifyHtml(INPUT), EXPECTED)
})

test('innerHTML of code/pre blocks is not altered', t => {
  const INPUT = `
    jQuery('selector').on('event', () => {
      // Comment
      window.alert('an alert');
    })
`

  t.is(prettifyHtml(INPUT), INPUT)
})
test('code/pre elements containing other XML tags are not altered', t => {
  const INPUT = `
    Example code containing tags
  `
  t.is(prettifyHtml(INPUT), INPUT)
})

test('prettify-html makes the html pretty', t => {
  const INPUT = `

Enrichment

          Turn any email or domain into a full person or company profile to qualify leads.

        Sign Up

  `

  const EXPECTED = `

Enrichment

 Turn any email or domain into a full person or company profile to qualify leads.

      Sign Up

`

	const results = prettifyHtml(INPUT)

	t.is(results, EXPECTED)
})
<|endoftext|>


<commit_before>/* jshint node: true */
/* jshint jquery: true */
/* jshint sub: true */
/* global window,document, $,alert,history */

var ___ = require('./spacetimeline');

//var timelineCapacity = moment.duration(40, 'seconds');
console.log('----');
//var ___a = ___(timelineCapacity);
var ___a = ___();

___a.compute(function()
{
  console.log('a: ' + ___a.value(___('NOW')));
});

var interval = setInterval(function()
{
  ___a.appear(___('NOW').toString());
}, 1000);
<commit_msg>commit<commit_after>/* jshint node: true */
/* jshint jquery: true */
/* jshint sub: true */
/* global window,document, $,alert,history */

"use strict";
// -- stdlib --
var pure = function(a)
{
  return function(_)
  {
    return a;
  };
};
// pure :: a -> IO a
var bind = function(m)
{
  return function(f)
  {
    return function(_)
    {
      return f(m())();
    };
  };
};
// bind :: IO a -> (a -> IO b) -> IO b
var exec = function(m)
{
  return m();
};
// exec :: IO a -> a
var wrap = function(f)
{
  return function(a)
  {
    return function(_)
    {
      return f(a);
    };
  };
};
// -- runtime --
Object.defineProperty(global, "world",
{
  set: exec
});

// wrap :: (a -> b) -> (a -> IO b)
var log = wrap(console.log.bind(console));

var ___ = require('./spacetimeline');

//var timelineCapacity = moment.duration(40, 'seconds');
world = log('----');
//var ___a = ___(timelineCapacity);
var ___a = ___();

world = wrap(___a.compute(function()
{
  world = log('a: ' + ___a.value(___('NOW')));
}));

var interval = setInterval(function()
{
  world = wrap(___a.appear(___('NOW').toString()));
}, 1000);
<|endoftext|>


<commit_before>/* global it */
'use strict';
var assert = require('assert');
var gutil = require('gulp-util');
var render = require('./');

it('should render valid React components to string', function (cb) {
  var stream = render('string');
  stream.on('data', function (file) {
    var pattern = /

some<\/span> : <\/span>prop<\/span><\/li><\/ul>/;
    assert(pattern.test(file.contents.toString()));
    cb();
  });

  stream.write(new gutil.File({
    base: __dirname,
    path: __dirname + '/fixtures/validComponent.jsx'
  }));
});

it('should render valid React components to static markup', function (cb) {
  var stream = render('markup');
  stream.on('data', function (file) {
    var pattern = /

some : prop<\/li><\/ul>/;
    assert(pattern.test(file.contents.toString()));
    cb();
  });

  stream.write(new gutil.File({
    base: __dirname,
    path: __dirname + '/fixtures/validComponent.jsx'
  }));
});

it('should render provided props', function (cb) {
  var stream = render('markup', {
    props: {
      a: 'prop',
      b: 'thing',
      c: 'stuff'
    }
  });
  stream.on('data', function (file) {
    var pattern = /

a : prop<\/li>
b : thing<\/li>
c : stuff<\/li>
some : prop<\/li><\/ul>/;
    assert(pattern.test(file.contents.toString()));
    cb();
  });

  stream.write(new gutil.File({
    base: __dirname,
    path: __dirname + '/fixtures/validComponent.jsx'
  }));
});

it('should render when given js', function (cb) {
    var stream = render('markup');
    stream.on('data', function (file) {
      var pattern = /

some : prop<\/li><\/ul>/;
      assert(pattern.test(file.contents.toString()));
      cb();
    });

    stream.write(new gutil.File({
      base: __dirname,
      path: __dirname + '/fixtures/anotherValidComponent.js'
    }));
});

it('should have an error if `type` is not `string` or `markup`', function (cb) {
  assert.throws(render, gutil.PluginError);
  cb();
});

it('should emit an error for invalid React components', function (cb) {
  var stream = render('string');
  stream.on('error', function () {
    cb();
  });

  stream.write(new gutil.File({
    base: __dirname,
    path: __dirname + '/fixtures/invalidComponent.jsx'
  }));
});
<commit_msg>fixed test.js to support passing props directly instead of within the opts object<commit_after>/* global it */
'use strict';
var assert = require('assert');
var gutil = require('gulp-util');
var render = require('./');

it('should render valid React components to string', function (cb) {
  var stream = render('string');
  stream.on('data', function (file) {
    var pattern = /

some<\/span> : <\/span>prop<\/span><\/li><\/ul>/;
    assert(pattern.test(file.contents.toString()));
    cb();
  });

  stream.write(new gutil.File({
    base: __dirname,
    path: __dirname + '/fixtures/validComponent.jsx'
  }));
});

it('should render valid React components to static markup', function (cb) {
  var stream = render('markup');
  stream.on('data', function (file) {
    var pattern = /

some : prop<\/li><\/ul>/;
    assert(pattern.test(file.contents.toString()));
    cb();
  });

  stream.write(new gutil.File({
    base: __dirname,
    path: __dirname + '/fixtures/validComponent.jsx'
  }));
});

it('should render provided props', function (cb) {
  var stream = render('markup', {
    a: 'prop',
    b: 'thing',
    c: 'stuff'
  });
  stream.on('data', function (file) {
    var pattern = /

a : prop<\/li>
b : thing<\/li>
c : stuff<\/li>
some : prop<\/li><\/ul>/;
    assert(pattern.test(file.contents.toString()));
    cb();
  });

  stream.write(new gutil.File({
    base: __dirname,
    path: __dirname + '/fixtures/validComponent.jsx'
  }));
});

it('should render when given js', function (cb) {
    var stream = render('markup');
    stream.on('data', function (file) {
      var pattern = /

some : prop<\/li><\/ul>/;
      assert(pattern.test(file.contents.toString()));
      cb();
    });

    stream.write(new gutil.File({
      base: __dirname,
      path: __dirname + '/fixtures/anotherValidComponent.js'
    }));
});

it('should have an error if `type` is not `string` or `markup`', function (cb) {
  assert.throws(render, gutil.PluginError);
  cb();
});

it('should emit an error for invalid React components', function (cb) {
  var stream = render('string');
  stream.on('error', function () {
    cb();
  });

  stream.write(new gutil.File({
    base: __dirname,
    path: __dirname + '/fixtures/invalidComponent.jsx'
  }));
});
<|endoftext|>


<commit_before>const idents = require('./idents');
const acorn = require('acorn/dist/acorn');
const assert = require('assert');

// collect parses the AST of the JavaScript source code and returns an array of the names of each Identifier AST node.
const collect = (source) => {
  const ast = acorn.parse(source);
  return idents.all(ast).map((id) => id.name);
};

describe('Identifiers', () => {

  it('lists identifiers in JS file', (done) => {
    const src = `
      var a={b: 3};
      var c = a.b[d];
      function f(w, x, y) {
        return z - q ? r : s;
      }
    `;
    assert.deepEqual(
      collect(src),
      ['a', 'c', 'a', 'b', 'd', 'f', 'w', 'x', 'y', 'z', 'q', 'r', 's']
    );
    done();
  });

  it('does not list null anonymous function names as identifiers', (done) => {
    const src = `
      var a = function() {};
    `;
    assert.deepEqual(collect(src), ['a']);
    done();
  });
});
<commit_msg>thorough testbed<commit_after>const idents = require('./idents');
const acorn = require('acorn/dist/acorn');
const assert = require('assert');

// collect parses the AST of the JavaScript source code and returns an array of the names of each Identifier AST node.
const collect = (source) => {
  const ast = acorn.parse(source);
  return idents.all(ast).map((id) => id.name);
};

describe('collects', () => {

  it('parenthesis', () => {
    assert.deepEqual(collect(`(a)`), ['a']);
  });

  describe('operators', () => {

    it('logical NOT', () => {
      assert.deepEqual(collect(`!a`), ['a']);
    });
    it('logical AND', () => {
      assert.deepEqual(collect(`a && b`), ['a', 'b']);
    });
    it('logical OR', () => {
      assert.deepEqual(collect(`a || b`), ['a', 'b']);
    });
    it('addition', () => {
      assert.deepEqual(collect(`a + b`), ['a', 'b']);
    });
    it('subtraction', () => {
      assert.deepEqual(collect(`a - b`), ['a', 'b']);
    });
    it('multiplication', () => {
      assert.deepEqual(collect(`a * b`), ['a', 'b']);
    });
    it('division', () => {
      assert.deepEqual(collect(`a / b`), ['a', 'b']);
    });
    it('remainder', () => {
      assert.deepEqual(collect(`a % b`), ['a', 'b']);
    });
    it('exponentiation', () => {
      assert.deepEqual(collect(`a ** b`), ['a', 'b']);
    });

    it('left shift', () => {
      assert.deepEqual(collect(`a << b`), ['a', 'b']);
    });

    it('right shift', () => {
      assert.deepEqual(collect(`a >> b`), ['a', 'b']);
    });

    it('unsigned right shift', () => {
      assert.deepEqual(collect(`a >>> b`), ['a', 'b']);
    });

    it('bitwise AND', () => {
      assert.deepEqual(collect(`a & b`), ['a', 'b']);
    });

    it('bitwise XOR', () => {
      assert.deepEqual(collect(`a ^ b`), ['a', 'b']);
    });

    it('bitwise OR', () => {
      assert.deepEqual(collect(`a | b`), ['a', 'b']);
    });

  })

  describe.skip('assignments', () => {

    it('addition', () => {
      assert.deepEqual(collect(`a += b`), ['a', 'b']);
    });
    it('subtraction', () => {
      assert.deepEqual(collect(`a -= b`), ['a', 'b']);
    });
    it('multiplication', () => {
      assert.deepEqual(collect(`a *= b`), ['a', 'b']);
    });
    it('division', () => {
      assert.deepEqual(collect(`a /= b`), ['a', 'b']);
    });
    it('remainder', () => {
      assert.deepEqual(collect(`a %= b`), ['a', 'b']);
    });
    it('exponentiation', () => {
      assert.deepEqual(collect(`a **= b`), ['a', 'b']);
    });

    it('left shift', () => {
      assert.deepEqual(collect(`a <<= b`), ['a', 'b']);
    });

    it('right shift', () => {
      assert.deepEqual(collect(`a >>= b`), ['a', 'b']);
    });

    it('unsigned right shift', () => {
      assert.deepEqual(collect(`a >>>= b`), ['a', 'b']);
    });

    it('bitwise AND', () => {
      assert.deepEqual(collect(`a &= b`), ['a', 'b']);
    });

    it('bitwise XOR', () => {
      assert.deepEqual(collect(`a ^= b`), ['a', 'b']);
    });

    it('bitwise OR', () => {
      assert.deepEqual(collect(`a |= b`), ['a', 'b']);
    });

  });

  describe('declarations', () => {

    it('var', () => {
      assert.deepEqual(collect(`var a = 1`), ['a']);
      assert.deepEqual(collect(`var a = 1, b = 2`), ['a', 'b']);
    });

    it('const', () => {
      assert.deepEqual(collect(`const a = 1`), ['a']);
      assert.deepEqual(collect(`const a = 1, b = 2`), ['a', 'b']);
    });

    it('let', () => {
      assert.deepEqual(collect(`let a = 1`), ['a']);
      assert.deepEqual(collect(`let a = 1, b = 2`), ['a', 'b']);
    });

  });

  it('conditional expression', () => {
    assert.deepEqual(collect(`a ? b : c`), ['a', 'b', 'c']);
  });

  it('template string', () => {
    assert.deepEqual(collect('`${a}b${c}`'), ['a', 'c']);
  });

  it('object literals values', () => {
    assert.deepEqual(collect(`{a: b}`), ['b']);
    assert.deepEqual(collect(`{a: b + c}`), ['b', 'c']);
  });

  it('array values', () => {
    assert.deepEqual(collect(`[a, b]`), ['a', 'b']);
    assert.deepEqual(collect(`[a + b, c]`), ['a', 'b', 'c']);
  });

  it('member expressions', () => {
    assert.deepEqual(collect(`a[b] = 1`), ['a', 'b']);
    assert.deepEqual(collect(`a[0] = 1`), ['a']);
  });

  describe('functions', () => {

    it('declaration', () => {
      assert.deepEqual(collect(`function foo () {};`), ['foo']);
    });

    it('parameters', () => {
      assert.deepEqual(collect(`
        (function (foo, bar) {});
      `), ['foo', 'bar']);
    });

    it('inside function body', () => {
      assert.deepEqual(collect(`
        (function () {1 + a; b;})
      `), ['a', 'b']);
    });

  });

  describe('loops', () => {

    it('inside while loop', () => {
      assert.deepEqual(collect(`
        while (true) {
          1 + a; b;
        }
      `), ['a', 'b']);
    });

    it('inside for loop', () => {
      assert.deepEqual(collect(`
        for (let i = 0; i < 1; i++) {
          1 + a; b;
        }
      `), ['i', 'i', 'i', 'a', 'b']);
    });

    it('inside for…of loop', () => {
      assert.deepEqual(collect(`
        for (let key of arr) {
          1 + a; b;
        }
      `), ['key', 'arr', 'a', 'b']);
    });

    it('inside for…in loop', () => {
      assert.deepEqual(collect(`
        for (let key in obj) {
          1 + a; b;
        }
      `), ['key', 'obj', 'a', 'b']);
    });

  });

  it('inside block', () => {
    assert.deepEqual(collect(`{1 + a; b;}`), ['a', 'b']);
  });

  it('object literal', () => {
    assert.deepEqual(collect(`o = {}`), ['o']);
    assert.deepEqual(collect(`o = {a: b}`), ['b', 'o']);
    assert.deepEqual(collect(`o = {a: b, c: d}`), ['b', 'd', 'o']);
    assert.deepEqual(collect(`o = {a: b, c: {d: e}}`), ['b', 'e', 'o']);
  });

  it('array literal', () => {
    assert.deepEqual(collect(`o = []`), ['o']);
    assert.deepEqual(collect(`o = [a]`), ['a', 'o']);
    assert.deepEqual(collect(`o = [a, 1, b]`), ['a', 'b', 'o']);
    assert.deepEqual(collect(`o = [a, 1, [b, 2]]`), ['a', 'b', 'o']);
  });

});

describe('ignores', () => {

  it('literals', () => {
    assert.deepEqual(collect(`1`), []);
    assert.deepEqual(collect(`'a'`), []);
    assert.deepEqual(collect(`"a"`), []);
    assert.deepEqual(collect('`a`'), []);
    assert.deepEqual(collect(/a/g), []);
  });

  it('object keys', () => {
    assert.deepEqual(collect(`{a: 1}`), []);
  });

});

it.skip('kitchen sink', () => {
  const src = `
    const a= {b: 3, c: [d]};
    let b = a.b[c];
    var c = function d (e, f, g) {
      return h - i ? j : k;
    };
    for (let l of m) n(l);
  `;
  assert.deepEqual(
    collect(src),
    ['todo']
  );
  done();
});
<|endoftext|>


<commit_before>var Hex = require('./hex.js'),
    ASN1 = require('./asn1.js'),
    tests;

tests = [
    // http://luca.ntop.org/Teaching/Appunti/asn1.html
    // actually reports the string as "011011100101110111"
    ['03 04 06 6e 5d c0', '(18 bit)\n111011101001110110', 'DER encoding'],
    ['03 04 06 6e 5d e0', '(18 bit)\n111011101001110110', 'padded with "100000"'],
    ['03 81 04 06 6e 5d c0', '(18 bit)\n111011101001110110', 'long form of length octets'],
    ['23 09 03 03 00 6e 5d 03 02 06 c0', '(18 bit)\n111011101001110110', 'constructed encoding: "0110111001011101" + "11"'],
    // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379076(v=vs.85).aspx
    ['30820319308202820201003023310F300D0603550403130654657374434E3110300E060355040A1307546573744F726730819F300D06092A864886F70D010101050003818D00308189028181008FE2412A08E851A88CB3E853E7D54950B3278A2BCBEAB54273EA0257CC6533EE882061A11756C12418E3A808D3BED931F3370B94B8CC43080B7024F79CB18D5DD66D82D0540984F89F970175059C89D4D5C91EC913D72A6B309119D6D442E0C49D7C9271E1B22F5C8DEEF0F1171ED25F315BB19CBC2055BF3A37424575DC90650203010001A08201B4301A060A2B0601040182370D0203310C160A362E302E353336312E323042060A2B0601040182370D0201313430321E260043006500720074006900660069006300610074006500540065006D0070006C0061007400651E080055007300650072305706092B0601040182371514314A30480201090C237669636833642E6A646F6D6373632E6E74746573742E6D6963726F736F66742E636F6D0C154A444F4D4353435C61646D696E6973747261746F720C07636572747265713074060A2B0601040182370D0202316630640201011E5C004D006900630072006F0073006F0066007400200045006E00680061006E006300650064002000430072007900700074006F0067007200610070006800690063002000500072006F00760069006400650072002000760031002E003003010030818206092A864886F70D01090E31753073301706092B0601040182371402040A1E08005500730065007230290603551D2504223020060A2B0601040182370A030406082B0601050507030406082B06010505070302300E0603551D0F0101FF0404030205A0301D0603551D0E041604143C0F73DAF8EF41D83AEABE922A5D2C966A7B9454300D06092A864886F70D01010505000381810047EB995ADF9E700DFBA73132C15F5C24C2E0BFC624AF15660EB86A2EAB2BC4971FE3CBDC63A525ECC7B428616636A1311BBFDDD0FCBF1794901DE55EC7115EC9559FEBA33E14C799A6CBBAA1460F39D444C4C84B760E205D6DA9349ED4D58742EB2426511490B40F065E5288327A9520A0FDF7E57D60DD72689BF57B058F6D1E',
        '(3 elem)', 'PKCS#10 request'],
    // Int10
    ['060C69C7C79AB78084C289F9870D', '2.25.84478768945400492475277', 'Big OID arc'],
    ['02102FA176B36EE9F049F444B40099661945', '(126 bit) 63312083136615639753586560173617846597', 'Big integer (126 bit)'],
    ['028181008953097086EE6147C5F4D5FFAF1B498A3D11EC5518E964DC52126B2614F743883F64CA51377ABB530DFD20464A48BD67CD27E7B29AEC685C5D10825E605C056E4AB8EEA460FA27E55AA62C498B02D7247A249838A12ECDF37C6011CF4F0EDEA9CEE687C1CB4A51C6AE62B2EFDB000723A01C99D6C23F834880BA8B42D5414E6F',
        '(1024 bit) 96432446964907009840023644401994013457468837455140331578268642517697945390319089463541388080569398374873228752921897678940332050406994011437231634303608704223145390228074087922901239478374991949372306413157758278029522534299413919735715864599284769202556071242381348472464716517735026291259010477833523908207',
        'Big integer (1024 bit)'],
];

tests.forEach(function (t) {
    var input = t[0],
        expected = t[1],
        comment = t[2],
        result = null;
    try {
        result = ASN1.decode(Hex.decode(input)).content();
        //TODO: check structure, not only first level content
    } catch (e) {
        result = 'Exception:\n' + e;
    }
    if (result == expected)
        console.log('\x1B[1m\x1B[32mOK \x1B[39m\x1B[22m ' + comment);
    else
        console.log('\x1B[1m\x1B[31mERR\x1B[39m\x1B[22m ' + comment + '\n' + result);
});
<commit_msg>node shebang.<commit_after>#!/usr/bin/env node
/*jshint node: true, strict: true, globalstrict: true, es5: true, indent: 4, immed: true, undef: true, unused: true */
'use strict';

var Hex = require('./hex.js'),
    ASN1 = require('./asn1.js'),
    tests;

tests = [
    // http://luca.ntop.org/Teaching/Appunti/asn1.html
    // actually reports the string as "011011100101110111"
    ['03 04 06 6e 5d c0', '(18 bit)\n111011101001110110', 'DER encoding'],
    ['03 04 06 6e 5d e0', '(18 bit)\n111011101001110110', 'padded with "100000"'],
    ['03 81 04 06 6e 5d c0', '(18 bit)\n111011101001110110', 'long form of length octets'],
    ['23 09 03 03 00 6e 5d 03 02 06 c0', '(18 bit)\n111011101001110110', 'constructed encoding: "0110111001011101" + "11"'],
    // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379076(v=vs.85).aspx
    ['30820319308202820201003023310F300D0603550403130654657374434E3110300E060355040A1307546573744F726730819F300D06092A864886F70D010101050003818D00308189028181008FE2412A08E851A88CB3E853E7D54950B3278A2BCBEAB54273EA0257CC6533EE882061A11756C12418E3A808D3BED931F3370B94B8CC43080B7024F79CB18D5DD66D82D0540984F89F970175059C89D4D5C91EC913D72A6B309119D6D442E0C49D7C9271E1B22F5C8DEEF0F1171ED25F315BB19CBC2055BF3A37424575DC90650203010001A08201B4301A060A2B0601040182370D0203310C160A362E302E353336312E323042060A2B0601040182370D0201313430321E260043006500720074006900660069006300610074006500540065006D0070006C0061007400651E080055007300650072305706092B0601040182371514314A30480201090C237669636833642E6A646F6D6373632E6E74746573742E6D6963726F736F66742E636F6D0C154A444F4D4353435C61646D696E6973747261746F720C07636572747265713074060A2B0601040182370D0202316630640201011E5C004D006900630072006F0073006F0066007400200045006E00680061006E006300650064002000430072007900700074006F0067007200610070006800690063002000500072006F00760069006400650072002000760031002E003003010030818206092A864886F70D01090E31753073301706092B0601040182371402040A1E08005500730065007230290603551D2504223020060A2B0601040182370A030406082B0601050507030406082B06010505070302300E0603551D0F0101FF0404030205A0301D0603551D0E041604143C0F73DAF8EF41D83AEABE922A5D2C966A7B9454300D06092A864886F70D01010505000381810047EB995ADF9E700DFBA73132C15F5C24C2E0BFC624AF15660EB86A2EAB2BC4971FE3CBDC63A525ECC7B428616636A1311BBFDDD0FCBF1794901DE55EC7115EC9559FEBA33E14C799A6CBBAA1460F39D444C4C84B760E205D6DA9349ED4D58742EB2426511490B40F065E5288327A9520A0FDF7E57D60DD72689BF57B058F6D1E',
        '(3 elem)', 'PKCS#10 request'],
    // Int10
    ['060C69C7C79AB78084C289F9870D', '2.25.84478768945400492475277', 'Big OID arc'],
    ['02102FA176B36EE9F049F444B40099661945', '(126 bit) 63312083136615639753586560173617846597', 'Big integer (126 bit)'],
    ['028181008953097086EE6147C5F4D5FFAF1B498A3D11EC5518E964DC52126B2614F743883F64CA51377ABB530DFD20464A48BD67CD27E7B29AEC685C5D10825E605C056E4AB8EEA460FA27E55AA62C498B02D7247A249838A12ECDF37C6011CF4F0EDEA9CEE687C1CB4A51C6AE62B2EFDB000723A01C99D6C23F834880BA8B42D5414E6F',
        '(1024 bit) 96432446964907009840023644401994013457468837455140331578268642517697945390319089463541388080569398374873228752921897678940332050406994011437231634303608704223145390228074087922901239478374991949372306413157758278029522534299413919735715864599284769202556071242381348472464716517735026291259010477833523908207',
        'Big integer (1024 bit)'],
];

tests.forEach(function (t) {
    var input = t[0],
        expected = t[1],
        comment = t[2],
        result = null;
    try {
        result = ASN1.decode(Hex.decode(input)).content();
        //TODO: check structure, not only first level content
    } catch (e) {
        result = 'Exception:\n' + e;
    }
    if (result == expected)
        console.log('\x1B[1m\x1B[32mOK \x1B[39m\x1B[22m ' + comment);
    else
        console.log('\x1B[1m\x1B[31mERR\x1B[39m\x1B[22m ' + comment + '\n' + result);
});
<|endoftext|>


<commit_before>var connect = require('connect');
var server = connect.createServer( connect.profiler(), connect.cookieParser(), connect.static( __dirname ), HttpHandler);

var io = require('socket.io').listen(server);
io.configure('production', function(){

	io.enable('browser client minification');
	io.enable('browser client etag');
	io.set('log level', 1);
  	io.set('transports', [
   		'flashsocket'
  		, 'htmlfile'
  		, 'xhr-polling'
  		, 'jsonp-polling'
  	]);
});

server.listen(process.env.PORT);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

function HttpHandler(req,res){

	if(req.url != '/notificationservice.asmx2' )
		res.end('not today');

	if (req.method === 'GET') {
        var search = url.parse(req.url).search;
        if (search && search.toLowerCase() === '?wsdl') {
            //res.setHeader("Content-Type", "application/xml");
            //res.write(self.wsdl.toXML());
            res.write('hello GET');
        }
        res.end();
    }
    else if (req.method === 'POST') {
        var chunks = [];
        req.on('data', function(chunk) {
            chunks.push(chunk);
        })
        req.on('end', function() {
            var xml = chunks.join(''), result;
            try {
                result = result;
            }
            catch (err) {
                result = err.stack;
            }
            console.log(result);
            res.write(result);
            res.end();
        });
    }
    else {
        res.end();
    }
}

<commit_msg>get the right file<commit_after>var connect = require('connect');
var server = connect.createServer( connect.profiler(), connect.cookieParser(), connect.static( __dirname ), HttpHandler);

var io = require('socket.io').listen(server);
io.configure('production', function(){

	io.enable('browser client minification');
	io.enable('browser client etag');
	io.set('log level', 1);
  	io.set('transports', [
   		'flashsocket'
  		, 'htmlfile'
  		, 'xhr-polling'
  		, 'jsonp-polling'
  	]);
});

server.listen(process.env.PORT);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

function HttpHandler(req,res){

	if(req.url != '/notificationservice.asmx' )
		res.end('not today');

	if (req.method === 'GET') {
        var search = url.parse(req.url).search;
        if (search && search.toLowerCase() === '?wsdl') {
            //res.setHeader("Content-Type", "application/xml");
            //res.write(self.wsdl.toXML());
            res.write('hello GET');
        }
        res.end();
    }
    else if (req.method === 'POST') {
        var chunks = [];
        req.on('data', function(chunk) {
            chunks.push(chunk);
        })
        req.on('end', function() {
            var xml = chunks.join(''), result;
            try {
                result = result;
            }
            catch (err) {
                result = err.stack;
            }
            console.log(result);
            res.write(result);
            res.end();
        });
    }
    else {
        res.end();
    }
}

<|endoftext|>


<commit_before>'use strict';

require('test-setup');

var EventEmitter = require('events').EventEmitter;
var eavesdrop    = require('./');

/* globals describe:false, it:false, beforeEach:false, expect:false, sinon:false */

describe('eavesdrop', function () {

  var source, target;
  beforeEach(function () {
    source = new EventEmitter();
    target = new EventEmitter();
  });

  describe('Registering listeners', function () {

    it('must specify 1+ events', function () {
      expect(eavesdrop.bind(source, target)).to.throw(/event/);
    });

    it('can register a single events', function () {
      eavesdrop.call(source, target, 'name');
      expect(target.listeners()).to.have.length(1);
    });

    it('can register an array of events', function () {
      eavesdrop.call(source, target, ['name1', 'name2']);
      expect(target.listeners()).to.have.length(2);
    });

    it('can register variadic events', function () {
      eavesdrop.call(source, target, 'name1', 'name2');
      expect(target.listeners()).to.have.length(2);
    });

    it('returns the source for chaining', function () {
      expect(eavesdrop.call(source, target, 'name')).to.equal(source);
    });

  });

  describe('Eavesdropping', function () {

    it('emits all eavesdropped target events on the source', function () {
      var spy = sinon.spy();
      eavesdrop.call(source, target, 'name');
      source.on('name', spy);
      target.emit('name', 'a1', 'a2');
      expect(spy).to.have.been.calledWith('a1', 'a2');
    });

  });

});<commit_msg>swap target/source semantics<commit_after>'use strict';

require('test-setup');

var EventEmitter = require('events').EventEmitter;
var eavesdrop    = require('./');

/* globals describe:false, it:false, beforeEach:false, expect:false, sinon:false */

describe('eavesdrop', function () {

  var source, target;
  beforeEach(function () {
    source = new EventEmitter();
    target = new EventEmitter();
  });

  describe('Registering listeners', function () {

    it('must specify 1+ events', function () {
      expect(eavesdrop.bind(target, source)).to.throw(/events/);
    });

    it('can register a single event', function () {
      eavesdrop.call(target, source, 'name');
      expect(source.listeners('name')).to.have.length(1);
    });

    it('can register an array of events', function () {
      eavesdrop.call(target, source, ['name1', 'name2']);
      expect(source.listeners('name')).to.have.length(2);
    });

    it('can register variadic events', function () {
      eavesdrop.call(target, source, 'name1', 'name2');
      expect(source.listeners('name')).to.have.length(2);
    });

    it('returns the target for chaining', function () {
      expect(eavesdrop.call(target, source, 'name')).to.equal(target);
    });

  });

  describe('Eavesdropping', function () {

    it('emits all eavesdropped source events on the target', function () {
      var spy = sinon.spy();
      eavesdrop.call(target, source, 'name');
      target.on('name', spy);
      source.emit('name', 'a1');
      source.emit('name', 'a1', 'a2', 'a3', 'a4');
      expect(spy).to.have.been.calledWith('a1', 'a2');
      expect(spy).to.have.been.calledWith('a1', 'a2', 'a3', 'a4');
      expect(spy).to.have.been.alwaysCalledOn(target);
    });

  });

});<|endoftext|>


<commit_before>define([
    'tools/tool'
], function(Tool) {

    var helloWorld = Tool.extend({
        init: function(context, options) {
          //this._super("Testing");
        }
    });

    return helloWorld;

    var newVizabi = function(core, options) {

        var helloWorld = Tool.extend({
            init: function(context, options) {
              console.log("HELLO WORLD!!!");
            }
        });

        return helloWorld;

        /* Initialization part */

        helloWorld.name = 'hello-world';
        helloWorld.getSVG().classed('hello-world', true);

        // Default state
        helloWorld.state = {
            show: {
                'world': {

                }
            },
            time: '1980',
            yaxis: {
                indicator: 'gdp'
            }
        };

        helloWorld.widgets = {}

        var parent = helloWorld.start;
        helloWorld.start(function() {
            return this;
        });

        helloWorld.start();

        return helloWorld;
    };

    return newVizabi;
});
<commit_msg>Hello world extends tool<commit_after>define([
    'underscore',
    'tools/tool'
], function(_, Tool) {

    var helloWorld = Tool.extend({
        init: function(context, options) {
            this.name = 'hello-world';
            this.placeholder = options.placeholder;
            this.state = _.extend({
                show: {
                    'world': {

                    }
                },
                time: '1980',
                yaxis: {
                    indicator: 'gdp'
                }
            }, options.state);

            this._super(options);
        }
    });

    return helloWorld;
});<|endoftext|>


<commit_before>import register from './module/register';

const test = require('tape-catch');
const repeat = require('repeat-element');

test('Registers the <parametric-svg> element', (is) => {
  is.plan(5);

  const registerElement = (
    name, {prototype, extends: extendsArg = null}
  ) => {
    is.pass(
      'taking a custom implementation of `document`'
    );

    is.equal(
      name,
      'parametric-svg',
      'under the name <parametric-svg>'
    );

    is.equal(
      extendsArg,
      null,
      'as a standard HTML element – no bells and whistles'
    );

    is.equal(
      typeof prototype.createdCallback,
      'function',
      'attaching stuff to the createdCallback…'
    );

    is.deepEqual(
      [
        prototype.attachedCallback,
        prototype.detachedCallback,
        prototype.atributeChangedCallback,
      ],
      repeat(undefined, 3),
      '…and to no other lifecycle callback'
    );
  };

  register({document: {registerElement}});
});

'Updates the first SVG inside ASAP';

'Doesn’t touch any other SVG';
<commit_msg>Add two specs<commit_after>import register from './module/register';

const test = require('tape-catch');
const repeat = require('repeat-element');

test('Registers the <parametric-svg> element', (is) => {
  is.plan(5);

  const registerElement = (
    name, {prototype, extends: extendsArg = null}
  ) => {
    is.pass(
      'taking a custom implementation of `document`'
    );

    is.equal(
      name,
      'parametric-svg',
      'under the name <parametric-svg>'
    );

    is.equal(
      extendsArg,
      null,
      'as a standard HTML element – no bells and whistles'
    );

    is.equal(
      typeof prototype.createdCallback,
      'function',
      'attaching stuff to the createdCallback…'
    );

    is.deepEqual(
      [
        prototype.attachedCallback,
        prototype.detachedCallback,
        prototype.atributeChangedCallback,
      ],
      repeat(undefined, 3),
      '…and to no other lifecycle callback'
    );
  };

  register({document: {registerElement}});
});

// Register the thing on the actual `document`. That’s what `index.js` does.
register({});

test('Works in a DOM structure created in one go', (is) => {
  is.plan(1);

  const parser = new DOMParser;
  const parametricSvg = parser.parseFromString(
`<!DOCTYPE html>
<parametric-svg>
  <svg>
    <rect parametric:x="50" />
  </svg>
</parametric-svg>
`,
    'text/html'
  );
  const rect = parametricSvg.documentElement.querySelector('rect');

  is.equal(
    rect.getAttribute('x'),
    '10',
    'synchronously'
  );
});

test('Works in a DOM structure built up programatically', (is) => {
  is.plan(2);

  const parametricSvg = document.createElement('parametric-svg');
  const svg = document.createElement('svg');
  const circle = document.createElement('circle');
  svg.appendChild(circle);
  parametricSvg.appendChild(svg);

  circle.setAttribute('r', '5');
  circle.setAttribute('parametric:r', '2 * (3 + 5)');

  is.equal(
    circle.getAttribute('r'),
    '5',
    'updates asynchronously'
  );

  requestAnimationFrame(() => {
    is.equal(
      circle.getAttribute('r'),
      String(2 * (3 + 5)),
      'within a single animation frame'
    );
  });
});

'Only affects the first child SVG';

'Only affects a direct child SVG';
<|endoftext|>


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

// Setup
// $ EUROPEANA_KEY=abc123 npm test
var apikey = process.env.EUROPEANA_APIKEY || null;
var timeout = process.env.EUROPEANA_TIMEOUT || 5000;

var europeana = app (apikey, timeout);

dotest.add ('Module', function (test) {
  test ()
    .isFunction ('fail', 'exports', app)
    .isFunction ('fail', 'module', europeana)
    .done ();
});

dotest.add ('search', function (test) {
  var props = {
    query: 'who:"laurent de la hyre"'
  };

  europeana ('search', props, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isArray ('fail', 'data.items', data && data.items)
      .isNotEmpty ('warn', 'data.items', data && data.items)
      .done ();
  });
});

dotest.add ('record', function (test) {
  var record = '9200365/BibliographicResource_1000055039444';
  var props = {
    profile: 'params'
  };

  europeana ('record/' + record, props, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isObject ('fail', 'data.object', data && data.object)
      .isNotEmpty ('warn', 'data.object', data && data.object)
      .done ();
  });
});

dotest.add ('translateQuery', function (test) {
  var props = {
    languageCodes: 'nl,en,hu',
    term: 'painting'
  };

  europeana ('translateQuery', props, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isArray ('warn', 'data.translations', data && data.translations)
      .done ();
  });
});

dotest.add ('providers normal', function (test) {
  europeana ('providers', function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isArray ('warn', 'data.items', data && data.items)
      .done ();
  });
});

dotest.add ('providers params', function (test) {
  var params = {
    pagesize: 3
  };

  europeana ('providers', params, function (err, data) {
    var items = data && data.items;

    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isArray ('fail', 'data.items', items)
      .isExactly ('warn', 'data.items.length', items && items.length, 3)
      .done ();
  });
});

dotest.add ('Error: API error', function (test) {
  europeana ('record/-', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .isNumber ('fail', 'err.code', err && err.code)
      .isString ('fail', 'err.error', err && err.error)
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: request failed', function (test) {
  var tmp = app (apikey, 1);

  tmp ('providers', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'request failed')
      .isError ('fail', 'err.error', err && err.error)
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: apikey missing', function (test) {
  var tmp = app ();

  tmp ('providers', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'apikey missing')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

/*
// Suggestions in unavailable
// http://labs.europeana.eu/api/suggestions
dotest.add ('suggestions', function (test) {
  var props = {
    query: 'laurent de la hyre',
    rows: 10
  };

  app ('suggestions', props, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .done ();
  });
});
*/

// Start the tests
dotest.run ();
<commit_msg>Test(main): Convert syntax to ES6<commit_after>const dotest = require ('dotest');
const app = require ('./');

// Setup
// $ EUROPEANA_KEY=abc123 npm test
const apikey = process.env.EUROPEANA_APIKEY || null;
const timeout = process.env.EUROPEANA_TIMEOUT || 5000;

const europeana = app (apikey, timeout);

dotest.add ('Module', test => {
  test()
    .isFunction ('fail', 'exports', app)
    .isFunction ('fail', 'module', europeana)
    .done();
});

dotest.add ('search', test => {
  const props = {
    query: 'who:"laurent de la hyre"'
  };

  europeana ('search', props, (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isArray ('fail', 'data.items', data && data.items)
      .isNotEmpty ('warn', 'data.items', data && data.items)
      .done();
  });
});

dotest.add ('record', test => {
  const record = '9200365/BibliographicResource_1000055039444';
  const props = {
    profile: 'params'
  };

  europeana ('record/' + record, props, (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isObject ('fail', 'data.object', data && data.object)
      .isNotEmpty ('warn', 'data.object', data && data.object)
      .done();
  });
});

dotest.add ('translateQuery', test => {
  const props = {
    languageCodes: 'nl,en,hu',
    term: 'painting'
  };

  europeana ('translateQuery', props, (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isArray ('warn', 'data.translations', data && data.translations)
      .done();
  });
});

dotest.add ('providers normal', test => {
  europeana ('providers', (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isArray ('warn', 'data.items', data && data.items)
      .done();
  });
});

dotest.add ('providers params', test => {
  const params = {
    pagesize: 3
  };

  europeana ('providers', params, (err, data) => {
    const items = data && data.items;

    test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isExactly ('fail', 'data.success', data && data.success, true)
      .isArray ('fail', 'data.items', items)
      .isExactly ('warn', 'data.items.length', items && items.length, 3)
      .done();
  });
});

dotest.add ('Error: API error', test => {
  europeana ('record/-', (err, data) => {
    test()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .isNumber ('fail', 'err.code', err && err.code)
      .isString ('fail', 'err.error', err && err.error)
      .isUndefined ('fail', 'data', data)
      .done();
  });
});

dotest.add ('Error: request failed', test => {
  const tmp = app (apikey, 1);

  tmp ('providers', (err, data) => {
    test()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'request failed')
      .isError ('fail', 'err.error', err && err.error)
      .isUndefined ('fail', 'data', data)
      .done();
  });
});

dotest.add ('Error: apikey missing', test => {
  const tmp = app();

  tmp ('providers', (err, data) => {
    test()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'apikey missing')
      .isUndefined ('fail', 'data', data)
      .done();
  });
});

/*
// Suggestions is unavailable
// http://labs.europeana.eu/api/suggestions
dotest.add ('suggestions', test => {
  const props = {
    query: 'laurent de la hyre',
    rows: 10
  };

  app ('suggestions', props, (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .done();
  });
});
*/

// Start the tests
dotest.run();
<|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-3 09:40:50<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

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

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


<commit_before>'use strict'
const R = require('ramda')

let ex = {
    set: (env) => process.env.NODE_ENV = env,
    get: () => process.env.NODE_ENV
}

const modes = { dev: Symbol('development'), prod: Symbol('production') }
const env = () => process.env.NODE_ENV === 'production' ? modes.production : modes.dev
const platforms = ['darwin', 'linux', 'win32']
const capitalize = R.compose(
    R.join(''),
    R.juxt([R.compose(R.toUpper, R.head), R.tail])
)

Object.keys(modes).forEach((k) => ex[k] = () => R.equals(env(), modes[k]))
R.forEach((k) => ex[k] = R.always(R.equals(process.platform, k)), platforms)
R.forEach((logic) =>
    R.forEach(([m, p]) => ex[m] = (v) => R[logic](ex[p], R.is(Function, v) ? v : R.always(v))(R.F)
        , R.map((p) => [R.concat(logic, capitalize(p)), p], platforms)),
    ['unless', 'when'])
module.exports = ex
<commit_msg>Fix production env<commit_after>'use strict'
const R = require('ramda')

let ex = {
    set: (env) => process.env.NODE_ENV = env,
    get: () => process.env.NODE_ENV
}

const modes = { dev: Symbol('development'), prod: Symbol('production') }
const env = () => process.env.NODE_ENV === 'production' ? modes.prod : modes.dev
const platforms = ['darwin', 'linux', 'win32']
const capitalize = R.compose(
    R.join(''),
    R.juxt([R.compose(R.toUpper, R.head), R.tail])
)

Object.keys(modes).forEach((k) => ex[k] = () => R.equals(env(), modes[k]))
R.forEach((k) => ex[k] = R.always(R.equals(process.platform, k)), platforms)
R.forEach((logic) =>
    R.forEach(([m, p]) => ex[m] = (v) => R[logic](ex[p], R.is(Function, v) ? v : R.always(v))(R.F)
        , R.map((p) => [R.concat(logic, capitalize(p)), p], platforms)),
    ['unless', 'when'])
module.exports = ex
<|endoftext|>


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

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

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

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

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


<commit_before>'use strict';

var inherits = require('util').inherits;
var mockfs = require('mock-fs');
var fs = require('fs');
var Builder = require('broccoli').Builder;
var Filter = require('./filter.js');

describe('Filter', function() {
  var builder;

  beforeEach(function() {
    builder = void 0;
  });

  afterEach(function(done) {
    done();
    if (builder === void 0) return done();
    //builder.cleanup().then(done, done);
  });

  function read(relativePath, encoding) {
    encoding = encoding === void 0 ? 'utf8' : encoding;
    return fs.readFileSync(relativePath, encoding);
  }

  it('should throw if called as a function', function() {
    expect(function() {
      return Filter();
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');
  });

  it('should throw if called on object which does not a child class of Filter',
      function() {
    expect(function() {
      return Filter.call({});
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');

    expect(function() {
      return Filter.call([]);
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');

    expect(function() {
      return Filter.call(global);
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');
  });

  it('should throw if base Filter class is new-ed', function() {
    expect(function() {
      return new Filter();
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');
  });

  function ReplaceFilter(inputTree, options) {
    if (!this) return new ReplaceFilter(inputTree, options);
    options = options || {};
    Filter.call(this, options);
    this._glob = options.glob;
    this._search = options.search;
    this._replacement = options.replace;
  }

  ReplaceFilter.prototype.canProcessFile = function(relativePath) {
    if (this._glob === void 0) {
      return Filter.prototype.canProcessFile.call(this, relativePath);
    }
    return minimatch(relativePath, this._glob);
  };

  ReplaceFilter.prototype.processString = function(contents, relativePath) {
    return contents.replace(this._search, this._replacement)
  };

  inherits(ReplaceFilter, Filter);

  it('should processString only when canProcessFile returns true',
      function(done) {
    var disk = {
      'dir/README.md': mockfs.file({contents: 'Nicest dogs in need of homes',
                                    mtime: new Date(1000)}),
      'dir/foo.js': mockfs.file({contents: 'Nicest dogs in need of homes',
                                 mtime: new Date(1000)})
    };
    mockfs(disk);
    var awk = ReplaceFilter('.', {
      glob: '*.md',
      search: 'dogs',
      replace: 'cats'
    });

    builder = new Builder(awk);

    builder.
        build().
        then(function() {
      expect(read(tree.outputPath + '/dir/README.md')).
          toBe('Nicest cats in need of homes');
      expect(read(tree.outputPath + '/dir/foo.js')).
          toBe('Nicest dogs in need of homes');
      done();
    }, done);
  });

  it('should cache status of canProcessFile', function(done) {
    var disk = {
      'dir/README.md': mockfs.file({contents: 'Nicest dogs in need of homes',
                                    mtime: new Date(1000)}),
      'dir/foo.js': mockfs.file({contents: 'Nicest dogs in need of homes',
                                 mtime: new Date(1000)})
    };
    mockfs(disk);

    var awk = ReplaceFilter('.', {
      glob: '*.md',
      search: 'dogs',
      replace: 'cats'
    });
    spyOn(awk, 'canProcessFile').and.callThrough();

    builder = new Builder(awk);

    builder.
        build().
        then(function() {
          expect(read(tree.outputPath + '/dir/README.md')).
              toBe('Nicest cats in need of homes');
          expect(read(tree.outputPath + '/dir/foo.js')).
              toBe('Nicest dogs in need of homes');
          expect(awk.canProcessFile.calls.count()).toBe(2);
          disk['dir/CONTRIBUTING.md'] = mockfs.file({
              contents: 'All dogs go to heaven!', mtime: new Date(1000)});
          mockfs(disk);
          builder.build().
              then(function() {
                expect(read(tree.outputPath + '/dir/README.md')).
                    toBe('Nicest cats in need of homes');
                expect(read(tree.outputPath + '/dir/foo.js')).
                    toBe('Nicest dogs in need of homes');
                expect(read(tree.outputPath + '/dir/CONTRIBUTING.md')).
                    toBe('All cats go to heaven!');
                expect(awk.canProcessFile.calls.count()).toBe(3);
              }, done);
        }, done);
  });
});
<commit_msg>test(filter): make that last test a bit beefier<commit_after>'use strict';

var inherits = require('util').inherits;
var mockfs = require('mock-fs');
var fs = require('fs');
var Builder = require('broccoli').Builder;
var Filter = require('./filter.js');

describe('Filter', function() {
  var builder;

  beforeEach(function() {
    builder = void 0;
  });

  afterEach(function(done) {
    done();
    if (builder === void 0) return done();
    //builder.cleanup().then(done, done);
  });

  function read(relativePath, encoding) {
    encoding = encoding === void 0 ? 'utf8' : encoding;
    return fs.readFileSync(relativePath, encoding);
  }

  it('should throw if called as a function', function() {
    expect(function() {
      return Filter();
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');
  });

  it('should throw if called on object which does not a child class of Filter',
      function() {
    expect(function() {
      return Filter.call({});
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');

    expect(function() {
      return Filter.call([]);
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');

    expect(function() {
      return Filter.call(global);
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');
  });

  it('should throw if base Filter class is new-ed', function() {
    expect(function() {
      return new Filter();
    }).toThrowError(
        TypeError, 'Filter is an abstract class and must be sub-classed');
  });

  function ReplaceFilter(inputTree, options) {
    if (!this) return new ReplaceFilter(inputTree, options);
    options = options || {};
    Filter.call(this, options);
    this._glob = options.glob;
    this._search = options.search;
    this._replacement = options.replace;
  }

  ReplaceFilter.prototype.canProcessFile = function(relativePath) {
    if (this._glob === void 0) {
      return Filter.prototype.canProcessFile.call(this, relativePath);
    }
    return minimatch(relativePath, this._glob);
  };

  ReplaceFilter.prototype.processString = function(contents, relativePath) {
    return contents.replace(this._search, this._replacement)
  };

  inherits(ReplaceFilter, Filter);

  it('should processString only when canProcessFile returns true',
      function(done) {
    var disk = {
      'dir/README.md': mockfs.file({contents: 'Nicest dogs in need of homes',
                                    mtime: new Date(1000)}),
      'dir/foo.js': mockfs.file({contents: 'Nicest dogs in need of homes',
                                 mtime: new Date(1000)})
    };
    mockfs(disk);
    var awk = ReplaceFilter('.', {
      glob: '*.md',
      search: 'dogs',
      replace: 'cats'
    });

    builder = new Builder(awk);

    builder.
        build().
        then(function() {
      expect(read(tree.outputPath + '/dir/README.md')).
          toBe('Nicest cats in need of homes');
      expect(read(tree.outputPath + '/dir/foo.js')).
          toBe('Nicest dogs in need of homes');
      done();
    }, done);
  });

  it('should cache status of canProcessFile', function(done) {
    var disk = {
      'dir/README.md': mockfs.file({contents: 'Nicest dogs in need of homes',
                                    mtime: new Date(1000)}),
      'dir/foo.js': mockfs.file({contents: 'Nicest dogs in need of homes',
                                 mtime: new Date(1000)})
    };
    mockfs(disk);

    var awk = ReplaceFilter('.', {
      glob: '*.md',
      search: 'dogs',
      replace: 'cats'
    });
    spyOn(awk, 'canProcessFile').and.callThrough();

    builder = new Builder(awk);

    builder.build().then(round1, done);

    function round1() {
      expect(read(tree.outputPath + '/dir/README.md')).
          toBe('Nicest cats in need of homes');
      expect(read(tree.outputPath + '/dir/foo.js')).
          toBe('Nicest dogs in need of homes');
      expect(awk.canProcessFile.calls.count()).toBe(2);
      disk['dir/CONTRIBUTING.md'] = mockfs.file({
          contents: 'All dogs go to heaven!', mtime: new Date(1000)});
      mockfs(disk);
      builder.build().then(round2, done);
    }

    function round2() {
      expect(read(tree.outputPath + '/dir/README.md')).
          toBe('Nicest cats in need of homes');
      expect(read(tree.outputPath + '/dir/foo.js')).
          toBe('Nicest dogs in need of homes');
      expect(read(tree.outputPath + '/dir/CONTRIBUTING.md')).
          toBe('All cats go to heaven!');
      expect(awk.canProcessFile.calls.count()).toBe(3);
      mockfs(disk);
      builder.build().then(round3, done);
    }

    function round3() {
      expect(awk.canProcessFile.calls.count()).toBe(3);
      done();
    }
  });
});
<|endoftext|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-12-4 01:55: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>var builder = require("./gyp-builder").createBuilder( "test", false );

// Write the gyp file to disk
// With no arguments, this creates the file in the current working directory
builder.writeGypFile();<commit_msg>Delete the basic test (which didn't work anyway)<commit_after><|endoftext|>


<commit_before>import tapeCss_ from './module';

const test = require('tape-catch');
const clone = require('clone');
const {freeze} = Object;
const {jsdom} = require('jsdom');

const tape = require('tape');

test('Doesn’t modify the `tape` instance', (is) => {
  const tapeClone = clone(tape);
  freeze(tapeClone.Test);
  freeze(tapeClone);

  is.doesNotThrow(
    () => tapeCss_(tapeClone),
    'doesn’t attempt to change any property'
  );

  is.end();
});

test('Doesn’t change the `tape` API', (is) => {
  const localTape = tape.createHarness({exit: false});
  const localTapeCss = tapeCss_(localTape);

  const tapStream = localTape.createStream({objectMode: true});

  is.plan(13);

  localTapeCss('1', (localIs) => {
    is.fail('`tape.only` works as before');
    localIs.end();
  });

  localTapeCss.only('2', (localIs) => {
    localIs.pass();
    localIs.ok(true);
    localIs.notOk(false);
    localIs.equal(1, 1);
    localIs.deepEqual([1], [1]);
    localIs.throws(() => { throw new Error('whatever'); });

    localIs.comment('Yeeaah!');
    localIs.skip('Whooah!');

    localIs.fail();
    localIs.ok(false);
    localIs.deepEqual([1], [2]);

    localIs.end();
  });

  const registerStreams = [
    ({type}) => is.equal(
      type, 'test',
      '`tape` works as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['pass', true],
      '`t.pass` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['ok', true],
      '`t.ok` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['notOk', true],
      '`t.notOk` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['equal', true],
      '`t.equal` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['deepEqual', true],
      '`t.deepEqual` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['throws', true],
      '`t.throws` succeeds as before'
    ),

    (data) => is.equal(
      data,
      'Yeeaah!',
      '`t.comment` outputs as before'
    ),

    ({operator, skip}) => is.deepEqual(
      [operator, skip],
      ['skip', true],
      '`t.skip` skips as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['fail', false],
      '`t.fail` fails as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['ok', false],
      '`t.ok` fails as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['deepEqual', false],
      '`t.deepEqual` fails as before'
    ),

    ({type}) => is.deepEqual(
      type,
      'end',
      '`t.end` ends as before'
    ),
  ].reduceRight(
    (callback, assertion) => () => tapStream.once('data', (data) => {
      assertion(data);
      callback();
    }),
    () => {}
  );

  registerStreams();
});

const doc = (typeof window !== 'undefined' && window.window === window ?
  window.document :
  jsdom('<!DOCTYPE html>').defaultView.document
);

test('Adds and removes DOM', (is) => {
  const blindTape = tape.createHarness({exit: false});
  const tapeCss = tapeCss_(blindTape);
  blindTape.createStream({objectMode: true});
    // No need to test the output of `tapeCss` unless our tests fail.

  is.plan(7);

  const span = doc.createElement('span');

  tapeCss('Whatever', {
    dom: span,
    document: doc,
  }, (localIs) => {
    is.equal(
      span.parentNode,
      doc.body,
      'inserts a single element to the <body>'
    );

    localIs.end();

    is.notOk(
      doc.body.contains(span),
      'removes the single element from the <body>'
    );
  });

  const tree = doc.createDocumentFragment();
  const button = doc.createElement('button');
  const p = doc.createElement('p');
  const div = doc.createElement('div');

  tree.appendChild(button);
  p.appendChild(div);
  tree.appendChild(p);

  tapeCss('Whatever', {
    dom: tree,
    document: doc,
  }, (localIs) => {
    is.ok(
      doc.body.contains(button) &&
      doc.body.contains(p) &&
      doc.body.contains(div),
      'inserts a whole DOM tree to the <body>'
    );

    is.equal(
      button.parentNode,
      doc.body,
      'puts every element of the tree directly in the <body>'
    );

    is.equal(
      div.parentNode,
      p,
      'keeps the internal DOM structure'
    );

    localIs.end();

    is.notOk(
      doc.body.contains(button) ||
      doc.body.contains(p) ||
      doc.body.contains(div),
      'removes the whole tree from the <body> after the test'
    );

    is.equal(
      div.parentNode,
      p,
      'doesn’t screw up the DOM structure while at it'
    );
  });
});

test('Adds and removes styles', (is) => {
  const blindTape = tape.createHarness({exit: false});
  const tapeCss = tapeCss_(blindTape);
  blindTape.createStream({objectMode: true});
    // No need to test the output of `tapeCss` unless our tests fail.

  is.plan(2);

  const styles = 'span {font-size: 99px}';

  tapeCss('Whatever', {
    styles,
    document: doc,
  }, (localIs) => {
    const styleElements = doc.head.getElementsByTagName('style');
    const styleElement = styleElements[styleElements.length - 1];

    is.equal(
      styleElement && styleElement.textContent,
      styles,
      'inserts our styles into the <head>'
    );

    localIs.end();

    is.notOk(
      doc.head.contains(styleElement),
      'removes them after the test'
    );
  });
});

test.skip('`test.only` works as they say in the ads', (is) => {
  is.end();
});
<commit_msg>Specify `test.only`<commit_after>import tapeCss_ from './module';

const test = require('tape-catch');
const clone = require('clone');
const {freeze} = Object;
const {jsdom} = require('jsdom');

const tape = require('tape');

test('Doesn’t modify the `tape` instance', (is) => {
  const tapeClone = clone(tape);
  freeze(tapeClone.Test);
  freeze(tapeClone);

  is.doesNotThrow(
    () => tapeCss_(tapeClone),
    'doesn’t attempt to change any property'
  );

  is.end();
});

test('Doesn’t change the `tape` API', (is) => {
  const localTape = tape.createHarness({exit: false});
  const localTapeCss = tapeCss_(localTape);

  const tapStream = localTape.createStream({objectMode: true});

  is.plan(13);

  localTapeCss('1', (localIs) => {
    is.fail('`tape.only` works as before');
    localIs.end();
  });

  localTapeCss.only('2', (localIs) => {
    localIs.pass();
    localIs.ok(true);
    localIs.notOk(false);
    localIs.equal(1, 1);
    localIs.deepEqual([1], [1]);
    localIs.throws(() => { throw new Error('whatever'); });

    localIs.comment('Yeeaah!');
    localIs.skip('Whooah!');

    localIs.fail();
    localIs.ok(false);
    localIs.deepEqual([1], [2]);

    localIs.end();
  });

  const registerStreams = [
    ({type}) => is.equal(
      type, 'test',
      '`tape` works as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['pass', true],
      '`t.pass` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['ok', true],
      '`t.ok` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['notOk', true],
      '`t.notOk` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['equal', true],
      '`t.equal` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['deepEqual', true],
      '`t.deepEqual` succeeds as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['throws', true],
      '`t.throws` succeeds as before'
    ),

    (data) => is.equal(
      data,
      'Yeeaah!',
      '`t.comment` outputs as before'
    ),

    ({operator, skip}) => is.deepEqual(
      [operator, skip],
      ['skip', true],
      '`t.skip` skips as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['fail', false],
      '`t.fail` fails as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['ok', false],
      '`t.ok` fails as before'
    ),

    ({operator, ok}) => is.deepEqual(
      [operator, ok],
      ['deepEqual', false],
      '`t.deepEqual` fails as before'
    ),

    ({type}) => is.deepEqual(
      type,
      'end',
      '`t.end` ends as before'
    ),
  ].reduceRight(
    (callback, assertion) => () => tapStream.once('data', (data) => {
      assertion(data);
      callback();
    }),
    () => {}
  );

  registerStreams();
});

const doc = (typeof window !== 'undefined' && window.window === window ?
  window.document :
  jsdom('<!DOCTYPE html>').defaultView.document
);

test('Adds and removes DOM', (is) => {
  const blindTape = tape.createHarness({exit: false});
  const tapeCss = tapeCss_(blindTape);
  blindTape.createStream({objectMode: true});
    // No need to test the output of `tapeCss` unless our tests fail.

  is.plan(7);

  const span = doc.createElement('span');

  tapeCss('Whatever', {
    dom: span,
    document: doc,
  }, (localIs) => {
    is.equal(
      span.parentNode,
      doc.body,
      'inserts a single element to the <body>'
    );

    localIs.end();

    is.notOk(
      doc.body.contains(span),
      'removes the single element from the <body>'
    );
  });

  const tree = doc.createDocumentFragment();
  const button = doc.createElement('button');
  const p = doc.createElement('p');
  const div = doc.createElement('div');

  tree.appendChild(button);
  p.appendChild(div);
  tree.appendChild(p);

  tapeCss('Whatever', {
    dom: tree,
    document: doc,
  }, (localIs) => {
    is.ok(
      doc.body.contains(button) &&
      doc.body.contains(p) &&
      doc.body.contains(div),
      'inserts a whole DOM tree to the <body>'
    );

    is.equal(
      button.parentNode,
      doc.body,
      'puts every element of the tree directly in the <body>'
    );

    is.equal(
      div.parentNode,
      p,
      'keeps the internal DOM structure'
    );

    localIs.end();

    is.notOk(
      doc.body.contains(button) ||
      doc.body.contains(p) ||
      doc.body.contains(div),
      'removes the whole tree from the <body> after the test'
    );

    is.equal(
      div.parentNode,
      p,
      'doesn’t screw up the DOM structure while at it'
    );
  });
});

test('Adds and removes styles', (is) => {
  const blindTape = tape.createHarness({exit: false});
  const tapeCss = tapeCss_(blindTape);
  blindTape.createStream({objectMode: true});
    // No need to test the output of `tapeCss` unless our tests fail.

  is.plan(2);

  const styles = 'span {font-size: 99px}';

  tapeCss('Whatever', {
    styles,
    document: doc,
  }, (localIs) => {
    const styleElements = doc.head.getElementsByTagName('style');
    const styleElement = styleElements[styleElements.length - 1];

    is.equal(
      styleElement && styleElement.textContent,
      styles,
      'inserts our styles into the <head>'
    );

    localIs.end();

    is.notOk(
      doc.head.contains(styleElement),
      'removes them after the test'
    );
  });
});

test('`test.only` works as they say in the ads', (is) => {
  const blindTape = tape.createHarness({exit: false});
  const tapeCss = tapeCss_(blindTape);
  blindTape.createStream({objectMode: true});
    // No need to test the output of `tapeCss` unless our tests fail.

  is.plan(4);

  const styles = 'span {font-size: 73px}';
  const span = doc.createElement('span');

  tapeCss('Shouldn’t run', () => {
    is.fail(
      'test before `test.only` doesn’t run'
    );
  });

  tapeCss.only('Whatever', {
    styles,
    dom: span,
    document: doc,
  }, (localIs) => {
    const styleElements = doc.head.getElementsByTagName('style');
    const styleElement = styleElements[styleElements.length - 1];

    is.equal(
      styleElement && styleElement.textContent,
      styles,
      'inserts our styles into the <head>'
    );

    is.equal(
      span.parentNode,
      doc.body,
      'inserts our DOM to the <body>'
    );

    localIs.end();

    is.ok(
      doc.head.contains(styleElement),
      'doesn’t remove styles after the test'
    );

    is.ok(
      doc.body.contains(span),
      'doesn’t remove the DOM after the test'
    );

    is.end();
  });

  tapeCss('Shouldn’t run', () => {
    is.fail(
      'test after `test.only` doesn’t run'
    );
  });
});
<|endoftext|>