<commit_before>const kleur = require('kleur');
const { EventEmitter } = require('events');

function mockStack (error) {
  error.stack = `    at Object.<anonymous> (/dev/null/test/unit/data.js:6:5)
    at require (internal/helpers.js:22:18)
    at /dev/null/src/example/foo.js:220:27`;
  return error;
}

function makeFailingTestEnd (actualValue) {
  return {
    name: 'Failing',
    suiteName: null,
    fullName: ['Failing'],
    status: 'failed',
    runtime: 0,
    errors: [{
      passed: false,
      actual: actualValue,
      expected: 'expected'
    }],
    assertions: null
  };
}

QUnit.module('TapReporter', hooks => {
  let emitter;
  let last;
  let buffer;

  function log (str) {
    buffer += str + '\n';
    last = str;
  }

  hooks.beforeEach(function () {
    emitter = new EventEmitter();
    last = undefined;
    buffer = '';
    QUnit.reporters.tap.init(emitter, {
      log: log
    });
  });

  QUnit.test('output the TAP header', assert => {
    emitter.emit('runStart', {});

    assert.strictEqual(last, 'TAP version 13');
  });

  QUnit.test('output ok for a passing test', assert => {
    const expected = 'ok 1 name';

    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'passed',
      runtime: 0,
      errors: [],
      assertions: []
    });

    assert.strictEqual(last, expected);
  });

  QUnit.test('output ok for a skipped test', assert => {
    const expected = kleur.yellow('ok 1 # SKIP name');

    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'skipped',
      runtime: 0,
      errors: [],
      assertions: []
    });
    assert.strictEqual(last, expected);
  });

  QUnit.test('output not ok for a todo test', assert => {
    const expected = kleur.cyan('not ok 1 # TODO name');

    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'todo',
      runtime: 0,
      errors: [],
      assertions: []
    });
    assert.strictEqual(last, expected);
  });

  QUnit.test('output not ok for a failing test', assert => {
    const expected = kleur.red('not ok 1 name');

    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'failed',
      runtime: 0,
      errors: [],
      assertions: []
    });
    assert.strictEqual(last, expected);
  });

  QUnit.test('output all errors for a failing test', assert => {
    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'failed',
      runtime: 0,
      errors: [
        mockStack(new Error('first error')),
        mockStack(new Error('second error'))
      ],
      assertions: []
    });

    assert.strictEqual(buffer, `${kleur.red('not ok 1 name')}
  ---
  message: first error
  severity: failed
  stack: |
        at Object.<anonymous> (/dev/null/test/unit/data.js:6:5)
        at require (internal/helpers.js:22:18)
        at /dev/null/src/example/foo.js:220:27
  ...
  ---
  message: second error
  severity: failed
  stack: |
        at Object.<anonymous> (/dev/null/test/unit/data.js:6:5)
        at require (internal/helpers.js:22:18)
        at /dev/null/src/example/foo.js:220:27
  ...
`
    );
  });

  QUnit.test('output global failure (string)', assert => {
    emitter.emit('error', 'Boo');

    assert.strictEqual(buffer, `${kleur.red('not ok 1 global failure')}
  ---
  message: Boo
  severity: failed
  ...
Bail out! Boo
`
    );
  });

  QUnit.test('output global failure (Error)', assert => {
    const err = new ReferenceError('Boo is not defined');
    mockStack(err);
    emitter.emit('error', err);

    assert.strictEqual(buffer, `${kleur.red('not ok 1 global failure')}
  ---
  message: ReferenceError: Boo is not defined
  severity: failed
  stack: |
        at Object.<anonymous> (/dev/null/test/unit/data.js:6:5)
        at require (internal/helpers.js:22:18)
        at /dev/null/src/example/foo.js:220:27
  ...
Bail out! ReferenceError: Boo is not defined
`
    );
  });

  QUnit.test('output expected value of Infinity', assert => {
    emitter.emit('testEnd', {
      name: 'Failing',
      suiteName: null,
      fullName: ['Failing'],
      status: 'failed',
      runtime: 0,
      errors: [{
        passed: false,
        actual: 'actual',
        expected: Infinity
      }],
      assertions: null
    });
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : actual
  expected: Infinity
  ...`
    );
  });

  QUnit.test('output actual value of undefined', assert => {
    emitter.emit('testEnd', makeFailingTestEnd(undefined));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : undefined
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of Infinity', assert => {
    emitter.emit('testEnd', makeFailingTestEnd(Infinity));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : Infinity
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of a string', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('abc'));

    // No redundant quotes
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : abc
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value with one trailing line break', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('abc\n'));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : |
    abc
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value with two trailing line breaks', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('abc\n\n'));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : |+
    abc

  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of a number string', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('2'));

    // Quotes required to disambiguate YAML value
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : "2"
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of boolean string', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('true'));

    // Quotes required to disambiguate YAML value
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : "true"
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of 0', assert => {
    emitter.emit('testEnd', makeFailingTestEnd(0));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : 0
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual assertion value of empty array', assert => {
    emitter.emit('testEnd', makeFailingTestEnd([]));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : []
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value with a cyclical structure', assert => {
    /// Creates an object that has a cyclical reference.
    function createCyclical () {
      const cyclical = { a: 'example' };
      cyclical.cycle = cyclical;
      return cyclical;
    }
    emitter.emit('testEnd', makeFailingTestEnd(createCyclical()));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : {
  "a": "example",
  "cycle": "[Circular]"
}
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value with a subobject cyclical structure', assert => {
    // Creates an object that has a cyclical reference in a subobject.
    function createSubobjectCyclical () {
      const cyclical = { a: 'example', sub: {} };
      cyclical.sub.cycle = cyclical;
      return cyclical;
    }
    emitter.emit('testEnd', makeFailingTestEnd(createSubobjectCyclical()));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : {
  "a": "example",
  "sub": {
    "cycle": "[Circular]"
  }
}
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual assertion value of an acyclical structure', assert => {
    // Creates an object that references another object more
    // than once in an acyclical way.
    function createDuplicateAcyclical () {
      const duplicate = {
        example: 'value'
      };
      return {
        a: duplicate,
        b: duplicate,
        c: 'unique'
      };
    }
    emitter.emit('testEnd', makeFailingTestEnd(createDuplicateAcyclical()));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : {
  "a": {
    "example": "value"
  },
  "b": {
    "example": "value"
  },
  "c": "unique"
}
  expected: expected
  ...`
    );
  });

  QUnit.test('output the total number of tests', assert => {
    emitter.emit('runEnd', {
      testCounts: {
        total: 6,
        passed: 3,
        failed: 2,
        skipped: 1,
        todo: 0
      }
    });

    assert.strictEqual(buffer, `1..6
# pass 3
${kleur.yellow('# skip 1')}
${kleur.cyan('# todo 0')}
${kleur.red('# fail 2')}
`
    );
  });
});
<commit_msg>Test: Add coverage for cyclical array case of TapReporter<commit_after>const kleur = require('kleur');
const { EventEmitter } = require('events');

function mockStack (error) {
  error.stack = `    at Object.<anonymous> (/dev/null/test/unit/data.js:6:5)
    at require (internal/helpers.js:22:18)
    at /dev/null/src/example/foo.js:220:27`;
  return error;
}

function makeFailingTestEnd (actualValue) {
  return {
    name: 'Failing',
    suiteName: null,
    fullName: ['Failing'],
    status: 'failed',
    runtime: 0,
    errors: [{
      passed: false,
      actual: actualValue,
      expected: 'expected'
    }],
    assertions: null
  };
}

QUnit.module('TapReporter', hooks => {
  let emitter;
  let last;
  let buffer;

  function log (str) {
    buffer += str + '\n';
    last = str;
  }

  hooks.beforeEach(function () {
    emitter = new EventEmitter();
    last = undefined;
    buffer = '';
    QUnit.reporters.tap.init(emitter, {
      log: log
    });
  });

  QUnit.test('output the TAP header', assert => {
    emitter.emit('runStart', {});

    assert.strictEqual(last, 'TAP version 13');
  });

  QUnit.test('output ok for a passing test', assert => {
    const expected = 'ok 1 name';

    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'passed',
      runtime: 0,
      errors: [],
      assertions: []
    });

    assert.strictEqual(last, expected);
  });

  QUnit.test('output ok for a skipped test', assert => {
    const expected = kleur.yellow('ok 1 # SKIP name');

    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'skipped',
      runtime: 0,
      errors: [],
      assertions: []
    });
    assert.strictEqual(last, expected);
  });

  QUnit.test('output not ok for a todo test', assert => {
    const expected = kleur.cyan('not ok 1 # TODO name');

    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'todo',
      runtime: 0,
      errors: [],
      assertions: []
    });
    assert.strictEqual(last, expected);
  });

  QUnit.test('output not ok for a failing test', assert => {
    const expected = kleur.red('not ok 1 name');

    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'failed',
      runtime: 0,
      errors: [],
      assertions: []
    });
    assert.strictEqual(last, expected);
  });

  QUnit.test('output all errors for a failing test', assert => {
    emitter.emit('testEnd', {
      name: 'name',
      suiteName: null,
      fullName: ['name'],
      status: 'failed',
      runtime: 0,
      errors: [
        mockStack(new Error('first error')),
        mockStack(new Error('second error'))
      ],
      assertions: []
    });

    assert.strictEqual(buffer, `${kleur.red('not ok 1 name')}
  ---
  message: first error
  severity: failed
  stack: |
        at Object.<anonymous> (/dev/null/test/unit/data.js:6:5)
        at require (internal/helpers.js:22:18)
        at /dev/null/src/example/foo.js:220:27
  ...
  ---
  message: second error
  severity: failed
  stack: |
        at Object.<anonymous> (/dev/null/test/unit/data.js:6:5)
        at require (internal/helpers.js:22:18)
        at /dev/null/src/example/foo.js:220:27
  ...
`
    );
  });

  QUnit.test('output global failure (string)', assert => {
    emitter.emit('error', 'Boo');

    assert.strictEqual(buffer, `${kleur.red('not ok 1 global failure')}
  ---
  message: Boo
  severity: failed
  ...
Bail out! Boo
`
    );
  });

  QUnit.test('output global failure (Error)', assert => {
    const err = new ReferenceError('Boo is not defined');
    mockStack(err);
    emitter.emit('error', err);

    assert.strictEqual(buffer, `${kleur.red('not ok 1 global failure')}
  ---
  message: ReferenceError: Boo is not defined
  severity: failed
  stack: |
        at Object.<anonymous> (/dev/null/test/unit/data.js:6:5)
        at require (internal/helpers.js:22:18)
        at /dev/null/src/example/foo.js:220:27
  ...
Bail out! ReferenceError: Boo is not defined
`
    );
  });

  QUnit.test('output expected value of Infinity', assert => {
    emitter.emit('testEnd', {
      name: 'Failing',
      suiteName: null,
      fullName: ['Failing'],
      status: 'failed',
      runtime: 0,
      errors: [{
        passed: false,
        actual: 'actual',
        expected: Infinity
      }],
      assertions: null
    });
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : actual
  expected: Infinity
  ...`
    );
  });

  QUnit.test('output actual value of undefined', assert => {
    emitter.emit('testEnd', makeFailingTestEnd(undefined));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : undefined
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of Infinity', assert => {
    emitter.emit('testEnd', makeFailingTestEnd(Infinity));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : Infinity
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of a string', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('abc'));

    // No redundant quotes
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : abc
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value with one trailing line break', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('abc\n'));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : |
    abc
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value with two trailing line breaks', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('abc\n\n'));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : |+
    abc

  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of a number string', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('2'));

    // Quotes required to disambiguate YAML value
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : "2"
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of boolean string', assert => {
    emitter.emit('testEnd', makeFailingTestEnd('true'));

    // Quotes required to disambiguate YAML value
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : "true"
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value of 0', assert => {
    emitter.emit('testEnd', makeFailingTestEnd(0));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : 0
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual assertion value of empty array', assert => {
    emitter.emit('testEnd', makeFailingTestEnd([]));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : []
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value with a cyclical structure', assert => {
    /// Creates an object that has a cyclical reference.
    function createCyclical () {
      const cyclical = { a: 'example' };
      cyclical.cycle = cyclical;
      return cyclical;
    }
    emitter.emit('testEnd', makeFailingTestEnd(createCyclical()));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : {
  "a": "example",
  "cycle": "[Circular]"
}
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value with a subobject cyclical structure', assert => {
    // Creates an object that has a cyclical reference in a subobject.
    function createSubobjectCyclical () {
      const cyclical = { a: 'example', sub: {} };
      cyclical.sub.cycle = cyclical;
      return cyclical;
    }
    emitter.emit('testEnd', makeFailingTestEnd(createSubobjectCyclical()));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : {
  "a": "example",
  "sub": {
    "cycle": "[Circular]"
  }
}
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual value with a cyclical array', assert => {
    function createCyclicalArray () {
      const cyclical = { sub: ['example'] };
      cyclical.sub.push(cyclical.sub);
      cyclical.sub.push(cyclical);
      return cyclical;
    }
    emitter.emit('testEnd', makeFailingTestEnd(createCyclicalArray()));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : {
  "sub": [
    "example",
    "[Circular]",
    "[Circular]"
  ]
}
  expected: expected
  ...`
    );
  });

  QUnit.test('output actual assertion value of an acyclical structure', assert => {
    // Creates an object that references another object more
    // than once in an acyclical way.
    function createDuplicateAcyclical () {
      const duplicate = {
        example: 'value'
      };
      return {
        a: duplicate,
        b: duplicate,
        c: 'unique'
      };
    }
    emitter.emit('testEnd', makeFailingTestEnd(createDuplicateAcyclical()));
    assert.strictEqual(last, `  ---
  message: failed
  severity: failed
  actual  : {
  "a": {
    "example": "value"
  },
  "b": {
    "example": "value"
  },
  "c": "unique"
}
  expected: expected
  ...`
    );
  });

  QUnit.test('output the total number of tests', assert => {
    emitter.emit('runEnd', {
      testCounts: {
        total: 6,
        passed: 3,
        failed: 2,
        skipped: 1,
        todo: 0
      }
    });

    assert.strictEqual(buffer, `1..6
# pass 3
${kleur.yellow('# skip 1')}
${kleur.cyan('# todo 0')}
${kleur.red('# fail 2')}
`
    );
  });
});
<|endoftext|>


<commit_before>// Load in child_process and chai
var cp = require('child_process'),
    exec = cp.exec,
    async = require('async'),
    chai = require('chai'),
    expect = chai.expect;

// Outline
// Basic tests
var basicTests = {
  'doubleshot': {
    'reads the `test` directory implicitly': true,
    'allows for usage of `mocha` options': true,
    'allows for explicit directory specification': true,
    'allows for explicity file (and pattern) matching alongside mocha options': true
  }
};

var intermediateTests = {
  'doubleshot': {
    'can be run against a folder not labelled `test` and options exclusively': true,
    'can be run against a .yaml file': true,
    'resets timer for long running tests': true,
    'can chain global hooks': true,
    'can chain local hooks': true
  }
};

// Kitchen sink
var kitchenSink = {
  'doubleshot': {
    'warns user when keys are unused': true,
    'warns user when keys are not found': true,
    'warns user when aliases are not found': true,
    'runs batches in isolation': true,
    'throws errors for invalid values': true,
    'runs global and local `before`, `beforeEach`, `afterEach` and `after` hooks': true,
    'throws errors for aliasing within objects to other objects': true,
    'chains `after` hooks': true
  }
};

// Handle stderr throwbacks
function cleanStdErr(stdout, stderr, cb) {
  // If there were any errors, callback with them
  // console.log(stdout);
  if (stderr) {
    var err = new Error(stderr);
    cb(err);
  } else {
  // Otherwise, callback with stdout
    cb(null, stdout);
  }
}

// Assertions for `dot` reporter
function assertDotSuccess(stdout, cb) {
  expect(stdout).to.contain('complete');
  expect(stdout).to.not.contain('pending');
  expect(stdout).to.not.contain('failed');
  cb(null, stdout);
}

// Assertions for `nyan` reporter
function assertNyanSuccess(stdout, cb) {
  expect(stdout).to.contain('( ^ .^)');
  // '( ^ .^)'; // Success face
  // '( - .-)'; // Pending face
  // '( o .o)'; // Fail face
  cb(null, stdout);
}

// Content
// Basic tests
var path = require('path'),
    doubleshot = 'node ' + path.resolve(__dirname, '../bin/doubleshot');
describe('doubleshot', function () {
  it('reads the `test` directory implicitly', function (done) {
    async.waterfall([
      // Run doubleshot implicitly
      function runDblImplicitly (cb) {
        exec(doubleshot, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('allows for usage of `mocha` options', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' --reporter nyan';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertNyanSuccess
    ], done);
  });

  it('allows for explicit directory specification', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' test';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('allows for explicity file (and pattern) matching alongside mocha options', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' --outline test/doubleshot_outline.js --content test/doubleshot_content.js --reporter nyan';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertNyanSuccess
    ], done);
  });
});

describe('doubleshot', function () {
  it('warns user when keys are unused', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/unused_keys/content.js --outline test/test_files/unused_keys/outline.json';
    exec(cmd, function handleDblUnusedKeys (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals three');
      expect(stderr).to.contain('not used');

      // Callback
      done();
    });
  });

  it('warns user when keys are not found', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/keys_not_found/content.js --outline test/test_files/keys_not_found/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals two');
      expect(stderr).to.match(/not found/);

      // Callback
      done();
    });
  });

  it('warns user when aliases are not found', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/aliases_not_found/content.js --outline test/test_files/keys_not_found/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals too');
      expect(stderr).to.match(/not found/);

      // Callback
      done();
    });
  });

  it('can be run against a folder not labelled `test` and options exclusively', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    var cmd = doubleshot + ' --content spec/content.js --outline spec/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr is empty
      expect(stderr).to.equal('');

      // Go back to original directory
      process.chdir(cwd);

      // Callback
      done();
    });
  });

  it('can be run against a .yaml file', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblYamlTest (cb) {
        var cmd = doubleshot + ' yaml';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('runs batches in isolation', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' isolated_batches';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('does not interfere with shared contexts', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' nested_shared_context';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('throws errors for invalid values', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' invalid_values';
    exec(cmd, function handleDblInvalidValues (err, stdout, stderr) {
      // Assert stderr contains info about failing items
      expect(stderr).to.contain('Value of objects can only be arrays');

      // Callback
      done();
    });
  });

  it('runs global and local `before`, `beforeEach`, `afterEach` and `after` hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' after_etc_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('global beforeAll');
        expect(stdout).to.contain('beforeAll1');
        expect(stdout).to.contain('global beforeEach');
        expect(stdout).to.contain('beforeEach1');
        expect(stdout).to.contain('afterEach1');
        expect(stdout).to.contain('global afterEach');
        expect(stdout).to.contain('afterAll1');
        expect(stdout).to.contain('global afterAll');
        cb();
      }
    ], done);
  });

  it('resets timer for long running tests', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    this.timeout(10000);
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' slow_expansions';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('can chain global hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' complex_global_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('global beforeAll1\nglobal beforeAll2');
        cb();
      }
    ], done);
  });

  it('can chain local hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' complex_local_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('local afterAll1\nlocal afterAll2');
        cb();
      }
    ], done);
  });

  it('throws errors for aliasing within objects to other objects', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' invalid_object_object_alias';
    exec(cmd, function handleDblInvalidValues (err, stdout, stderr) {
      // Assert stderr contains info about failing items
      expect(stderr).to.contain('Aliasing within an object to another object is not allowed');

      // Callback
      done();
    });
  });

  it('chains `after` hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' chained_after_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('chainedAfter afterAll1\nchainedAfter afterAll2');
        cb();
      }
    ], done);
  });

  it('chains chains of chains hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' chained_chained_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('chainedChained afterAll1\nchainedChained afterAll2');
        cb();
      }
    ], done);
  });

  it.only('chains objects and aliases hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' chained_object_and_alias';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.match(/chainObjectAlias beforeAll1\n.*chainObjectAlias afterAll1/);
        cb();
      }
    ], done);
  });
});<commit_msg>Removed accidental .only in tests<commit_after>// Load in child_process and chai
var cp = require('child_process'),
    exec = cp.exec,
    async = require('async'),
    chai = require('chai'),
    expect = chai.expect;

// Outline
// Basic tests
var basicTests = {
  'doubleshot': {
    'reads the `test` directory implicitly': true,
    'allows for usage of `mocha` options': true,
    'allows for explicit directory specification': true,
    'allows for explicity file (and pattern) matching alongside mocha options': true
  }
};

var intermediateTests = {
  'doubleshot': {
    'can be run against a folder not labelled `test` and options exclusively': true,
    'can be run against a .yaml file': true,
    'resets timer for long running tests': true,
    'can chain global hooks': true,
    'can chain local hooks': true
  }
};

// Kitchen sink
var kitchenSink = {
  'doubleshot': {
    'warns user when keys are unused': true,
    'warns user when keys are not found': true,
    'warns user when aliases are not found': true,
    'runs batches in isolation': true,
    'throws errors for invalid values': true,
    'runs global and local `before`, `beforeEach`, `afterEach` and `after` hooks': true,
    'throws errors for aliasing within objects to other objects': true,
    'chains `after` hooks': true
  }
};

// Handle stderr throwbacks
function cleanStdErr(stdout, stderr, cb) {
  // If there were any errors, callback with them
  // console.log(stdout);
  if (stderr) {
    var err = new Error(stderr);
    cb(err);
  } else {
  // Otherwise, callback with stdout
    cb(null, stdout);
  }
}

// Assertions for `dot` reporter
function assertDotSuccess(stdout, cb) {
  expect(stdout).to.contain('complete');
  expect(stdout).to.not.contain('pending');
  expect(stdout).to.not.contain('failed');
  cb(null, stdout);
}

// Assertions for `nyan` reporter
function assertNyanSuccess(stdout, cb) {
  expect(stdout).to.contain('( ^ .^)');
  // '( ^ .^)'; // Success face
  // '( - .-)'; // Pending face
  // '( o .o)'; // Fail face
  cb(null, stdout);
}

// Content
// Basic tests
var path = require('path'),
    doubleshot = 'node ' + path.resolve(__dirname, '../bin/doubleshot');
describe('doubleshot', function () {
  it('reads the `test` directory implicitly', function (done) {
    async.waterfall([
      // Run doubleshot implicitly
      function runDblImplicitly (cb) {
        exec(doubleshot, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('allows for usage of `mocha` options', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' --reporter nyan';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertNyanSuccess
    ], done);
  });

  it('allows for explicit directory specification', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' test';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('allows for explicity file (and pattern) matching alongside mocha options', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' --outline test/doubleshot_outline.js --content test/doubleshot_content.js --reporter nyan';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertNyanSuccess
    ], done);
  });
});

describe('doubleshot', function () {
  it('warns user when keys are unused', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/unused_keys/content.js --outline test/test_files/unused_keys/outline.json';
    exec(cmd, function handleDblUnusedKeys (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals three');
      expect(stderr).to.contain('not used');

      // Callback
      done();
    });
  });

  it('warns user when keys are not found', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/keys_not_found/content.js --outline test/test_files/keys_not_found/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals two');
      expect(stderr).to.match(/not found/);

      // Callback
      done();
    });
  });

  it('warns user when aliases are not found', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/aliases_not_found/content.js --outline test/test_files/keys_not_found/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals too');
      expect(stderr).to.match(/not found/);

      // Callback
      done();
    });
  });

  it('can be run against a folder not labelled `test` and options exclusively', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    var cmd = doubleshot + ' --content spec/content.js --outline spec/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr is empty
      expect(stderr).to.equal('');

      // Go back to original directory
      process.chdir(cwd);

      // Callback
      done();
    });
  });

  it('can be run against a .yaml file', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblYamlTest (cb) {
        var cmd = doubleshot + ' yaml';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('runs batches in isolation', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' isolated_batches';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('does not interfere with shared contexts', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' nested_shared_context';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('throws errors for invalid values', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' invalid_values';
    exec(cmd, function handleDblInvalidValues (err, stdout, stderr) {
      // Assert stderr contains info about failing items
      expect(stderr).to.contain('Value of objects can only be arrays');

      // Callback
      done();
    });
  });

  it('runs global and local `before`, `beforeEach`, `afterEach` and `after` hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' after_etc_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('global beforeAll');
        expect(stdout).to.contain('beforeAll1');
        expect(stdout).to.contain('global beforeEach');
        expect(stdout).to.contain('beforeEach1');
        expect(stdout).to.contain('afterEach1');
        expect(stdout).to.contain('global afterEach');
        expect(stdout).to.contain('afterAll1');
        expect(stdout).to.contain('global afterAll');
        cb();
      }
    ], done);
  });

  it('resets timer for long running tests', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    this.timeout(10000);
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' slow_expansions';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('can chain global hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' complex_global_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('global beforeAll1\nglobal beforeAll2');
        cb();
      }
    ], done);
  });

  it('can chain local hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' complex_local_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('local afterAll1\nlocal afterAll2');
        cb();
      }
    ], done);
  });

  it('throws errors for aliasing within objects to other objects', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' invalid_object_object_alias';
    exec(cmd, function handleDblInvalidValues (err, stdout, stderr) {
      // Assert stderr contains info about failing items
      expect(stderr).to.contain('Aliasing within an object to another object is not allowed');

      // Callback
      done();
    });
  });

  it('chains `after` hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' chained_after_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('chainedAfter afterAll1\nchainedAfter afterAll2');
        cb();
      }
    ], done);
  });

  it('chains chains of chains hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' chained_chained_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('chainedChained afterAll1\nchainedChained afterAll2');
        cb();
      }
    ], done);
  });

  it('chains objects and aliases hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' chained_object_and_alias';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.match(/chainObjectAlias beforeAll1\n.*chainObjectAlias afterAll1/);
        cb();
      }
    ], done);
  });
});<|endoftext|>


<commit_before>import * as React from 'react';
import {
  AppRegistry,
  StyleSheet,
  View,
  StatusBar,
  ScrollView,
  Platform,
} from 'react-native';
import codePush from 'react-native-code-push';
import { Scene, Router } from 'react-native-router-flux';

import Home from './components/Home';
import RnIndex from './components/RnIndex';
import WebIndex from './components/WebIndex';
import { APIS, COMPONENTS } from './demoList';

const styles = StyleSheet.create({
  content: {
    ...Platform.select({
      ios: {
        marginTop: 64,
      },
      android: {
        marginTop: 54,
      },
    }),
    flex: 1,
  },
  scrollView: {
    flex: 1,
    backgroundColor: 'white',
  },
});

class AntmRnApp extends React.Component {
  componentDidMount() {
    codePush.sync();
  }

  render() {
    const scenes = APIS.concat(COMPONENTS).map(component => {
      const Module = component.module.default;
      let Component = React.createClass({
        render() {
          return (
            <View style={styles.content}>
              <ScrollView
                style={styles.scrollView}
                automaticallyAdjustContentInsets={false}
                showsHorizontalScrollIndicator={false}
                showsVerticalScrollIndicator={false}
              >
                <Module />
              </ScrollView>
            </View>
          );
        },
      });
      if (component.module.title === 'Drawer') {
        // drawer 不能放到 ScrollView 里
        Component = React.createClass({
          render() {
            return (
              <View style={styles.content}>
                <Module onNavigate={this.props.onNavigate} navigationState={this.props.navigationState} />
              </View>
            );
          },
        });
        const DrawerMainComponent = React.createClass({
          render() {
            return (
              <component.module.DrawerMain drawerComponent={Module} />
            );
          },
        });
        return (
          <Scene key={component.title} component={Component} title={component.title}>
            <Scene key="main" tabs>
              <Scene key={`${component.title}Sub`} hideNavBar component={DrawerMainComponent} />
            </Scene>
          </Scene>
        );
      }
      return <Scene key={component.title} component={Component} title={component.title} />;
    });

    return (
      <View style={{ flex: 1 }}>
        <StatusBar barStyle="light-content" />
        <Router>
          <Scene key="root" navigationBarStyle={{ backgroundColor: '#2e2e2e' }} titleStyle={{ color: 'white' }}>
            <Scene key="home" component={Home} title="Ant Design Mobile" initial />
            <Scene key="web" component={WebIndex} title="Antm Web Component" />
            <Scene key="native" component={RnIndex} title="Antm React Native" />
            {scenes}
          </Scene>
        </Router>
      </View>
    );
  }
}

AppRegistry.registerComponent('kitchen-sink', () => AntmRnApp);

export default AntmRnApp;
<commit_msg>app update dialog<commit_after>import * as React from 'react';
import {
  AppRegistry,
  StyleSheet,
  View,
  StatusBar,
  ScrollView,
  Platform,
} from 'react-native';
import codePush from 'react-native-code-push';
import { Scene, Router } from 'react-native-router-flux';

import Home from './components/Home';
import RnIndex from './components/RnIndex';
import WebIndex from './components/WebIndex';
import { APIS, COMPONENTS } from './demoList';

const styles = StyleSheet.create({
  content: {
    ...Platform.select({
      ios: {
        marginTop: 64,
      },
      android: {
        marginTop: 54,
      },
    }),
    flex: 1,
  },
  scrollView: {
    flex: 1,
    backgroundColor: 'white',
  },
});

class AntmRnApp extends React.Component {
  componentDidMount() {
    codePush.sync({
      updateDialog: {
        updateTitle: '检测有更新',
        optionalUpdateMessage: 'demo app 有新版本，是否安装？',
        optionalIgnoreButtonLabel: 'No',
        optionalInstallButtonLabel: 'Yes',
      },
    });
  }

  render() {
    const scenes = APIS.concat(COMPONENTS).map(component => {
      const Module = component.module.default;
      let Component = React.createClass({
        render() {
          return (
            <View style={styles.content}>
              <ScrollView
                style={styles.scrollView}
                automaticallyAdjustContentInsets={false}
                showsHorizontalScrollIndicator={false}
                showsVerticalScrollIndicator={false}
              >
                <Module />
              </ScrollView>
            </View>
          );
        },
      });
      if (component.module.title === 'Drawer') {
        // drawer 不能放到 ScrollView 里
        Component = React.createClass({
          render() {
            return (
              <View style={styles.content}>
                <Module onNavigate={this.props.onNavigate} navigationState={this.props.navigationState} />
              </View>
            );
          },
        });
        const DrawerMainComponent = React.createClass({
          render() {
            return (
              <component.module.DrawerMain drawerComponent={Module} />
            );
          },
        });
        return (
          <Scene key={component.title} component={Component} title={component.title}>
            <Scene key="main" tabs>
              <Scene key={`${component.title}Sub`} hideNavBar component={DrawerMainComponent} />
            </Scene>
          </Scene>
        );
      }
      return <Scene key={component.title} component={Component} title={component.title} />;
    });

    return (
      <View style={{ flex: 1 }}>
        <StatusBar barStyle="light-content" />
        <Router>
          <Scene key="root" navigationBarStyle={{ backgroundColor: '#2e2e2e' }} titleStyle={{ color: 'white' }}>
            <Scene key="home" component={Home} title="Ant Design Mobile" initial />
            <Scene key="web" component={WebIndex} title="Antm Web Component" />
            <Scene key="native" component={RnIndex} title="Antm React Native" />
            {scenes}
          </Scene>
        </Router>
      </View>
    );
  }
}

AppRegistry.registerComponent('kitchen-sink', () => AntmRnApp);

export default AntmRnApp;
<|endoftext|>


<commit_before>var endpoint = require('../../lib/endpoints'),
    Hapi = require('hapi'),
    resourceLoader = require('../../lib/api/resource-loader'),
    path = require('path');

describe('endpoints', function() {
  var server,
      options,
      appConfig,
      caching;

  beforeEach(function(done) {
    caching = this.spy(function(request, reply) {
      reply({'winning': true});
    });
    server = new Hapi.Server(0, {
      labels: ['api']
    });

    server.start(done);
  });

});
<commit_msg>Remove unused test file<commit_after><|endoftext|>


<commit_before>"use strict";

import chai from "chai";
import chaiAsPromised from "chai-as-promised";
import sinon from "sinon";
import BusinessElementsClient from "../src";
import uuid from "uuid";
import * as requests from "../src/requests";

chai.use(chaiAsPromised);
chai.should();
chai.config.includeStack = true;

const FAKE_SERVER_URL = "http://api.fake-server";

/** @test {Exhibition} */
describe("Exhibition", () => {
  let sandbox, client, exhibitionId, exhibition;

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    client = new BusinessElementsClient(FAKE_SERVER_URL);
    exhibitionId = uuid.v4();

    exhibition = client.tenant("example.com").exhibitions().exhibition(exhibitionId);
  });

  afterEach(() => {
    sandbox.restore();
  });

  /** @test {Exhibition#get} */
  describe("#get()", () => {
    const data = {id: exhibitionId};

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(data));
    });

    it("should get exhibition", () => {
      exhibition.get();

      sinon.assert.calledWithMatch(client.execute, {
        path: `/exhibitions/${exhibitionId}`
      });
    });

    it("should return exhibition data", () => {
      return exhibition.get().should.become(data);
    });
  });

  /** @test {Exhibition#remove} */
  describe("#remove()", () => {
    const response = {status: "Ok"};
    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
      sandbox.spy(requests, "deleteExhibition");
    });

    it("should delete the exhibition", () => {
      exhibition.remove({});

      sinon.assert.calledWithMatch(requests.deleteExhibition, exhibitionId);
    });

    it("should return success", () => {
      return exhibition.remove({}).should.eventually.become(response);
    });
  });

  /** @test {Exhibition#changeExhibitionVisibility} */
  describe("#changeExhibitionVisibility()", () => {
    const response = {status: "Ok"};

    const visibility = "public";

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
      sandbox.spy(requests, "changeExhibitionVisibility");
    });

    it("should change visibility of the exhibition", () => {
      exhibition.changeExhibitionVisibility(visibility, {});

      sinon.assert.calledWithMatch(requests.changeExhibitionVisibility, exhibitionId, visibility);
    });

    it("should return success", () => {
      return exhibition.changeExhibitionVisibility(visibility, {}).should.eventually.become(response);
    });
  });

  /** @test {Exhibition#update} */
  describe("#update()", () => {
    const response = {status: "Ok"};

    const name = "exhibition name";
    const description = "exhibition description";
    const pictureUri = "exhibition pictureUri";

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
      sandbox.spy(requests, "updateExhibition");
    });

    it("should update the exhibition", () => {
      exhibition.update(name, description, pictureUri, {});

      sinon.assert.calledWithMatch(requests.updateExhibition, exhibitionId, name, description, pictureUri);
    });

    it("should return success", () => {
      return exhibition.update(name, description, pictureUri, {}).should.eventually.become(response);
    });
  });
});
<commit_msg>- added tests for exhibition.js<commit_after>"use strict";

import chai from "chai";
import chaiAsPromised from "chai-as-promised";
import sinon from "sinon";
import BusinessElementsClient from "../src";
import uuid from "uuid";
import * as requests from "../src/requests";

chai.use(chaiAsPromised);
chai.should();
chai.config.includeStack = true;

const FAKE_SERVER_URL = "http://api.fake-server";

/** @test {Exhibition} */
describe("Exhibition", () => {
  let sandbox, client, exhibitionId, exhibition, projectId, projectContextId;

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    client = new BusinessElementsClient(FAKE_SERVER_URL);
    exhibitionId = uuid.v4();
    projectId = uuid.v4();
    projectContextId = uuid.v4();

    exhibition = client.tenant("example.com").exhibitions().exhibition(exhibitionId);
  });

  afterEach(() => {
    sandbox.restore();
  });

  /** @test {Exhibition#get} */
  describe("#get()", () => {
    const data = {id: exhibitionId};

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(data));
    });

    it("should get exhibition", () => {
      exhibition.get();

      sinon.assert.calledWithMatch(client.execute, {
        path: `/exhibitions/${exhibitionId}`
      });
    });

    it("should return exhibition data", () => {
      return exhibition.get().should.become(data);
    });
  });

  /** @test {Exhibition#remove} */
  describe("#remove()", () => {
    const response = {status: "Ok"};
    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
      sandbox.spy(requests, "deleteExhibition");
    });

    it("should delete the exhibition", () => {
      exhibition.remove({});

      sinon.assert.calledWithMatch(requests.deleteExhibition, exhibitionId);
    });

    it("should return success", () => {
      return exhibition.remove({}).should.eventually.become(response);
    });
  });

  /** @test {Exhibition#changeExhibitionVisibility} */
  describe("#changeExhibitionVisibility()", () => {
    const response = {status: "Ok"};

    const visibility = "public";

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
      sandbox.spy(requests, "changeExhibitionVisibility");
    });

    it("should change visibility of the exhibition", () => {
      exhibition.changeExhibitionVisibility(visibility, {});

      sinon.assert.calledWithMatch(requests.changeExhibitionVisibility, exhibitionId, visibility);
    });

    it("should return success", () => {
      return exhibition.changeExhibitionVisibility(visibility, {}).should.eventually.become(response);
    });
  });

  /** @test {Exhibition#update} */
  describe("#update()", () => {
    const response = {status: "Ok"};

    const name = "exhibition name";
    const description = "exhibition description";
    const pictureUri = "exhibition pictureUri";

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
      sandbox.spy(requests, "updateExhibition");
    });

    it("should update the exhibition", () => {
      exhibition.update(name, description, pictureUri, {});

      sinon.assert.calledWithMatch(requests.updateExhibition, exhibitionId, name, description, pictureUri);
    });

    it("should return success", () => {
      return exhibition.update(name, description, pictureUri, {}).should.eventually.become(response);
    });
  });

  /** @test {Exhibition#assignProjectToExhibition} */
  describe("#assignProjectToExhibition()", () => {
    const response = {
      exhibition: {
        id: exhibitionId
      }
    };

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
    });

    it("should call assign project to the exhibition", () => {
      exhibition.assignProjectToExhibition(projectId, {});

      sinon.assert.calledWithMatch(client.execute, {
        method: "PUT",
        path: `/exhibitions/${exhibitionId}/project`
      });

    });

    it("should return updated exhibition", () => {
      return exhibition.assignProjectToExhibition(projectId, {}).should.eventually.become(response);
    });

  });

  /** @test {Exhibition#removeProjectFromExhibition} */
  describe("#removeProjectFromExhibition()", () => {
    const response = {
      exhibition: {
        id: exhibitionId
      }
    };

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
    });

    it("should call remove assigned project from the exhibition", () => {
      exhibition.removeProjectFromExhibition(projectId, {});

      sinon.assert.calledWithMatch(client.execute, {
        method: "DELETE",
        path: `/exhibitions/${exhibitionId}/project`
      });

    });

    it("should return updated exhibition", () => {
      return exhibition.removeProjectFromExhibition(projectId, {}).should.eventually.become(response);
    });

  });

  /** @test {Exhibition#assignProjectContextToExhibition} */
  describe("#assignProjectContextToExhibition()", () => {
    const response = {
      exhibition: {
        id: exhibitionId
      }
    };

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
    });

    it("should call assign projectContext to the exhibition", () => {
      exhibition.assignProjectContextToExhibition(projectContextId, {});

      sinon.assert.calledWithMatch(client.execute, {
        method: "PUT",
        path: `/exhibitions/${exhibitionId}/projectContext`
      });

    });

    it("should return updated exhibition", () => {
      return exhibition.assignProjectContextToExhibition(projectContextId, {}).should.eventually.become(response);
    });

  });

  /** @test {Exhibition#removeProjectContextFromExhibition} */
  describe("#removeProjectContextFromExhibition()", () => {
    const response = {
      exhibition: {
        id: exhibitionId
      }
    };

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
    });

    it("should call remove assigned projectContext from the exhibition", () => {
      exhibition.removeProjectContextFromExhibition(projectContextId, {});

      sinon.assert.calledWithMatch(client.execute, {
        method: "DELETE",
        path: `/exhibitions/${exhibitionId}/projectContext`
      });

    });

    it("should return updated exhibition", () => {
      return exhibition.removeProjectContextFromExhibition(projectContextId, {}).should.eventually.become(response);
    });

  });

  /** @test {Exhibition#listProjectContexts} */
  describe("#listProjectContexts()", () => {
    const projectContexts = [
      {
        projectContext: {
          id: exhibitionId
        }
      }
    ];
    const response = {
      "_embedded": {
        "be:project_context": projectContexts
      }
    };

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
    });

    it("should call list projectContexts related to the exhibition", () => {
      exhibition.listProjectContexts({});

      sinon.assert.calledWithMatch(client.execute, {
        path: `/projects/contexts/exhibitions/${exhibitionId}`
      });
    });

    it("should return list of projectContexts related to exhibition", () => {
      return exhibition.listProjectContexts({}).should.eventually.become(projectContexts);
    });

  });

  /** @test {Exhibition#getContentRoot} */
  describe("#getContentRoot()", () => {
    const response = {
      "content": {}
    };

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
    });

    it("should call get content-tree from exhibition", () => {
      exhibition.getContentRoot({});

      sinon.assert.calledWithMatch(client.execute, {
        path: `/content/${exhibitionId}/root`
      });
    });

    it("should return content-tree from exhibition", () => {
      return exhibition.getContentRoot({}).should.eventually.become(response);
    });

  });
});
<|endoftext|>


<commit_before>#pragma strict
var rb : Component[];
var xMovement : float;
var speed : float;
var direction;
var life : int;
var shootCount : int;
var maxShootCount : int;
var yMovement : float;
var Explosion : Transform;
var player : GameObject;
var score = 1000;

var laser : Transform;

// -------

function moveBody(direction : Vector2, force : float){
  for (var i = 0; i < rb.length; i++) {
    var rbTemp : Rigidbody2D=rb[i];
    rbTemp.AddForce(direction * force);
  }
}

// -------

function getPosition() : Vector2{
  var rbTemp : Rigidbody2D=rb[0];
  return rbTemp.position;
}

//--------

function Start () {
	direction = "right";
	life = 200;
	maxShootCount = 30;
	shootCount = maxShootCount;
  yMovement = 2;
  speed = 2;
  rb = this.GetComponentsInChildren(Rigidbody2D);
  player = GameObject.Find("Player");
}

// -------

function hit(damage : int) {
	life -= damage;
	if (life <= 0) {
    player.SendMessage("score",score);
		Instantiate(Explosion, this.getPosition(), Quaternion.identity);
		Destroy(this.gameObject);
	}
}

// -------

function shoot(){
	if (shootCount > maxShootCount) {
		Instantiate(laser, this.getPosition() +Vector2(1.26,-1) , Quaternion.identity);
    Instantiate(laser, this.getPosition() +Vector2(-1.26,-1) , Quaternion.identity);
		shootCount = 0;
	}
	shootCount++;
}

// -------

function Update () {

	if(direction == "right"){
    if (this.getPosition()[0] < Player_controls.Lowerboundry_x+1) {
      moveBody(Vector2.right, speed);
    }
    else {
      moveBody(Vector2.right, speed*0.1);
    }
		if(this.getPosition()[0] > Player_controls.Upperboundry_x-0.5){
			direction = "left";
		}
	}
	else{
    if (this.getPosition()[0] > Player_controls.Upperboundry_x-1) {
      moveBody(Vector2.left, speed);
    }
    else {
      moveBody(Vector2.left, speed*0.1);
    }
		if(this.getPosition()[0] < Player_controls.Lowerboundry_x+1){
			direction = "right";
		}
	}

  if (this.getPosition()[1] < 0.5) {
    moveBody(Vector2.up, yMovement);
  }
  else {
    moveBody(Vector2.down, yMovement);
  }

  shoot();

	if(this.getPosition()[1] < Player_controls.Lowerboundry_y){
		Destroy(this.gameObject);
	}
}

// ---- Collision -------

function OnCollisionEnter2D(collision : Collision2D) {
	if (collision.gameObject.name == "Player ship") {
		collision.gameObject.SendMessage("hit", 50);
		Destroy(this.gameObject);
	}
}
<commit_msg>Boss doesn't get destroyed on collision with Player.<commit_after>#pragma strict
var rb : Component[];
var xMovement : float;
var speed : float;
var direction;
var life : int;
var shootCount : int;
var maxShootCount : int;
var yMovement : float;
var Explosion : Transform;
var player : GameObject;
var score = 1000;

var laser : Transform;

// -------

function moveBody(direction : Vector2, force : float){
  for (var i = 0; i < rb.length; i++) {
    var rbTemp : Rigidbody2D=rb[i];
    rbTemp.AddForce(direction * force);
  }
}

// -------

function getPosition() : Vector2{
  var rbTemp : Rigidbody2D=rb[0];
  return rbTemp.position;
}

//--------

function Start () {
	direction = "right";
	life = 200;
	maxShootCount = 30;
	shootCount = maxShootCount;
  yMovement = 2;
  speed = 2;
  rb = this.GetComponentsInChildren(Rigidbody2D);
  player = GameObject.Find("Player");
}

// -------

function hit(damage : int) {
	life -= damage;
	if (life <= 0) {
    player.SendMessage("score",score);
		Instantiate(Explosion, this.getPosition(), Quaternion.identity);
		Destroy(this.gameObject);
	}
}

// -------

function shoot(){
	if (shootCount > maxShootCount) {
		Instantiate(laser, this.getPosition() +Vector2(1.26,-1) , Quaternion.identity);
    Instantiate(laser, this.getPosition() +Vector2(-1.26,-1) , Quaternion.identity);
		shootCount = 0;
	}
	shootCount++;
}

// -------

function Update () {

	if(direction == "right"){
    if (this.getPosition()[0] < Player_controls.Lowerboundry_x+1) {
      moveBody(Vector2.right, speed);
    }
    else {
      moveBody(Vector2.right, speed*0.1);
    }
		if(this.getPosition()[0] > Player_controls.Upperboundry_x-0.5){
			direction = "left";
		}
	}
	else{
    if (this.getPosition()[0] > Player_controls.Upperboundry_x-1) {
      moveBody(Vector2.left, speed);
    }
    else {
      moveBody(Vector2.left, speed*0.1);
    }
		if(this.getPosition()[0] < Player_controls.Lowerboundry_x+1){
			direction = "right";
		}
	}

  if (this.getPosition()[1] < 0.5) {
    moveBody(Vector2.up, yMovement);
  }
  else {
    moveBody(Vector2.down, yMovement);
  }

  shoot();

	if(this.getPosition()[1] < Player_controls.Lowerboundry_y){
		Destroy(this.gameObject);
	}
}

// ---- Collision -------

function OnCollisionEnter2D(collision : Collision2D) {
	if (collision.gameObject.name == "Player ship") {
		collision.gameObject.SendMessage("hit", 50);
	}
}
<|endoftext|>


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

const { Point2D, Intersection, IntersectionArgs } = require('../index');
const { CubicBezier2D } = require('kld-contours');

function find_parameter(path, point) {
    const {x, y} = path.getBernsteinPolynomials();

    x.coefs[0] -= point.x;

    const roots = x.getRootsInInterval(0.0, 1.0);

    for (let t of roots) {
        const candidate_y = y.eval(t);

        if (Math.abs(candidate_y - point.y) < 1e-6) {
            return t;
        }
    }

    return NaN;
}

// parser path data
let b1 = new CubicBezier2D(
    new Point2D(150, 150),
    new Point2D(184, 217),
    new Point2D(233, 217),
    new Point2D(300, 150)
);
let b2 = new CubicBezier2D(
    new Point2D(100, 200),
    new Point2D(167, 133),
    new Point2D(233, 133),
    new Point2D(300, 200)
);

let path1 = new IntersectionArgs("Bezier3", [b1.p1, b1.p2, b1.p3, b1.p4]);
let path2 = new IntersectionArgs("Bezier3", [b2.p1, b2.p2, b2.p3, b2.p4]);

// intersect
let result = Intersection.intersect(path1, path2);

let param1 = find_parameter(b1, result.points[0]);
let point1 = b1.getPointAtParameter(param1);

let param2 = find_parameter(b2, result.points[0]);
let point2 = b2.getPointAtParameter(param2);

console.log();
console.log("These should all be pretty close to the same point");
console.log(`Reported intersection: ${result.points[0]}`);
console.log(`Point on first curve:  ${point1}, t=${param1}`);
console.log(`Point on second curve: ${point2}, t=${param2}`);
<commit_msg>Re-arrange and comment a bit<commit_after>#!/usr/bin/env node

const { Point2D, Intersection, IntersectionArgs } = require('../index');
const { CubicBezier2D } = require('kld-contours');

function find_parameter(path, point) {
    const {x, y} = path.getBernsteinPolynomials();

    x.coefs[0] -= point.x;

    const roots = x.getRootsInInterval(0.0, 1.0);

    for (let t of roots) {
        const candidate_y = y.eval(t);

        if (Math.abs(candidate_y - point.y) < 1e-6) {
            return t;
        }
    }

    return NaN;
}

// parser path data
let b1 = new CubicBezier2D(
    new Point2D(150, 150),
    new Point2D(184, 217),
    new Point2D(233, 217),
    new Point2D(300, 150)
);
let b2 = new CubicBezier2D(
    new Point2D(100, 200),
    new Point2D(167, 133),
    new Point2D(233, 133),
    new Point2D(300, 200)
);

let path1 = new IntersectionArgs("Bezier3", [b1.p1, b1.p2, b1.p3, b1.p4]);
let path2 = new IntersectionArgs("Bezier3", [b2.p1, b2.p2, b2.p3, b2.p4]);

// intersect
let result = Intersection.intersect(path1, path2);

// find bezier parametric values from first intersection point
let param1 = find_parameter(b1, result.points[0]);
let param2 = find_parameter(b2, result.points[0]);

// calculate points on curves from their parametric values
let point1 = b1.getPointAtParameter(param1);
let point2 = b2.getPointAtParameter(param2);

// compare the results
console.log();
console.log("These should all be pretty close to the same point");
console.log(`Reported intersection: ${result.points[0]}`);
console.log(`Point on first curve:  ${point1}, t=${param1}`);
console.log(`Point on second curve: ${point2}, t=${param2}`);
<|endoftext|>


<commit_before>/**
 * Jazzify adds helpers to vanilla JS and adds chaining functionality.
 *
 * @copyright Jakob Ploens 2016
 * @author    Jakob Ploens <jakob@2helden.com>
 * @version   1.3
 */

/**
 * -----------------------------------------------------------------------------
 * Object prototype functions
 * Use like object.addClass(), where object = document.querySelector('.elem')
 *
 * @since 1.0
 * -----------------------------------------------------------------------------
 */

/**
 * addClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.addClass = function(className){
    if(this.classList){
        this.classList.add(className);
    } else {
        this.className += ' ' + className;
    }

    return this;
};

/**
 * removeClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.removeClass = function(className){
    if (this.classList){
        this.classList.remove(className);
    } else {
        this.className = this.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }

    return this;
};

/**
 * hasClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.hasClass = function(className){
    if (this.classList){
        return this.classList.contains(className);
    } else {
        return new RegExp('(^| )' + className + '( |$)', 'gi').test(this.className);
    }
};

/**
 * toggleClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.toggleClass = function(className){
    if(this.classList){
        this.classList.toggle(className);

    } else {
        var classes = thus.className.split(' ');
        var existingIndex = classes.indexOf(className);

        if(existingIndex >= 0){
            classes.splice(existingIndex, 1);
        } else {
            classes.push(className);
        }
        this.className = classes.join(' ');
    }

    return this;
};

/**
 * remove
 *
 * @return object
 * @since  1.1
 */
Object.prototype.remove = function(){
    this.parentNode.removeChild(this);
};

/**
 * css
 *
 * @return object or css value
 * @since  1.1
 */
Object.prototype.css = function(name, value){
    if(value && value !== ""){
        this.style[name] = value;
        return this;
    } else {
        return this.style[name];
    }
};

/**
 * data
 *
 * @return object or data value
 * @since  1.1
 */
Object.prototype.data = function(name, value){
    if(value && value !== ""){
        this.setAttribute('data-' + name) = value;
        return this;
    } else {
        return this.getAttribute('data-' + name);
    }
};

/**
 * attr
 *
 * @return object or attr value
 * @since  1.2
 */
Object.prototype.attr = function(name, value){
    if(value && value !== ""){
        this.setAttribute(name) = value;
        return this;
    } else {
        return this.getAttribute(name);
    }
};

/**
 * each
 * Useable on NodeLists only
 *
 * @since  1.2
 */
Object.prototype.each = function(callback, scope){
    for(var i = 0; i < this.length; i++){
        callback.call(scope, i, this[i]);
    }
};

/**
 * on
 * Attaches event on object
 *
 * @since  1.3
 */
Object.prototype.on = function(e, callback, capture){
    if(this.addEventListener){
        this.addEventListener(e, callback, capture || false);
    } else if(this.attachEvent){
        this.attachEvent('on' + e, callback);
    }
    return this;
};

/**
 * find
 * Returns nodelist or object
 *
 * @return object
 * @since  1.3
 */
Object.prototype.find = function(selector){
    var elements = this.querySelectorAll(selector);
    if(elements.length === 1) return elements[0];
    return elements;
};

/**
 * -----------------------------------------------------------------------------
 * Helper functions
 *
 * @since 1.0
 * -----------------------------------------------------------------------------
 */

/**
 * Short function to merge two objects.
 *
 * @param  object (gets overwritten)
 * @param  object (overwrites)
 * @return object (merged)
 */
var merge = function(objectA, objectB){
    var result = {};
    for(var attr in objectA){
        result[attr] = objectA[attr];
    }
    for(var attr in objectB){
        result[attr] = objectB[attr];
    }
    return result;
};

/**
 * Shortcut for document.find()
 */
var $ = function(selector){
    return document.find(selector);
};<commit_msg>Added first, last, removeAttr; fixed data and attr methods<commit_after>/**
 * Jazzify adds helpers to vanilla JS and adds chaining functionality.
 *
 * @copyright Jakob Ploens 2016
 * @author    Jakob Ploens <jakob@2helden.com>
 * @version   1.4
 */

/**
 * -----------------------------------------------------------------------------
 * Object prototype functions
 * Use like object.addClass(), where object = document.querySelector('.elem')
 *
 * @since 1.0
 * -----------------------------------------------------------------------------
 */

/**
 * addClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.addClass = function(className){
    if(this.classList){
        this.classList.add(className);
    } else {
        this.className += ' ' + className;
    }

    return this;
};

/**
 * removeClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.removeClass = function(className){
    if (this.classList){
        this.classList.remove(className);
    } else {
        this.className = this.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }

    return this;
};

/**
 * hasClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.hasClass = function(className){
    if (this.classList){
        return this.classList.contains(className);
    } else {
        return new RegExp('(^| )' + className + '( |$)', 'gi').test(this.className);
    }
};

/**
 * toggleClass
 *
 * @param  string class name
 * @return object
 * @since  1.0
 */
Object.prototype.toggleClass = function(className){
    if(this.classList){
        this.classList.toggle(className);

    } else {
        var classes = thus.className.split(' ');
        var existingIndex = classes.indexOf(className);

        if(existingIndex >= 0){
            classes.splice(existingIndex, 1);
        } else {
            classes.push(className);
        }
        this.className = classes.join(' ');
    }

    return this;
};

/**
 * remove
 *
 * @return object
 * @since  1.1
 */
Object.prototype.remove = function(){
    this.parentNode.removeChild(this);
};

/**
 * css
 *
 * @return object or css value
 * @since  1.1
 */
Object.prototype.css = function(name, value){
    if(value && value !== ""){
        this.style[name] = value;
        return this;
    } else {
        return this.style[name];
    }
};

/**
 * data
 *
 * @return object or data value
 * @since  1.1
 */
Object.prototype.data = function(name, value){
    if(value && value !== ""){
        this.setAttribute('data-' + name, value);
        return this;
    } else {
        return this.getAttribute('data-' + name);
    }
};

/**
 * attr
 *
 * @return object or attr value
 * @since  1.2
 */
Object.prototype.attr = function(name, value){
    if(value && value !== ""){
        this.setAttribute(name, value);
        return this;
    } else {
        return this.getAttribute(name);
    }
};

/**
 * removeAttr
 *
 * @return object
 * @since  1.4
 */
Object.prototype.removeAttr = function(name){
    this.removeAttribute(name) = value;
    return this;
};

/**
 * each
 * Useable on NodeLists only
 *
 * @since  1.2
 */
Object.prototype.each = function(callback, scope){
    for(var i = 0; i < this.length; i++){
        callback.call(scope, i, this[i]);
    }
};

/**
 * on
 * Attaches event on object
 *
 * @since  1.3
 */
Object.prototype.on = function(e, callback, capture){
    if(this.addEventListener){
        this.addEventListener(e, callback, capture || false);
    } else if(this.attachEvent){
        this.attachEvent('on' + e, callback);
    }
    return this;
};

/**
 * find
 * Returns nodelist or object
 *
 * @return object
 * @since  1.3
 */
Object.prototype.find = function(selector){
    var elements = this.querySelectorAll(selector);
    if(elements.length === 1) return elements[0];
    return elements;
};

/**
 * first
 * Returns first of nodelist
 *
 * @return object
 * @since  1.4
 */
Object.prototype.first = function(){
    return this[0];
};

/**
 * last
 * Returns last of nodelist
 *
 * @return object
 * @since  1.4
 */
Object.prototype.last = function(){
    return this[this.length - 1];
};

/**
 * -----------------------------------------------------------------------------
 * Helper functions
 *
 * @since 1.0
 * -----------------------------------------------------------------------------
 */

/**
 * Short function to merge two objects.
 *
 * @param  object (gets overwritten)
 * @param  object (overwrites)
 * @return object (merged)
 */
var merge = function(objectA, objectB){
    var result = {};
    for(var attr in objectA){
        result[attr] = objectA[attr];
    }
    for(var attr in objectB){
        result[attr] = objectB[attr];
    }
    return result;
};

/**
 * Shortcut for document.find()
 */
var $ = function(selector){
    return document.find(selector);
};<|endoftext|>


<commit_before>const {basename} = require('path');
const filename = basename(__filename);

const WebSocket = require('ws');
const {VertexServer, VertexSocket} = require('../');

describe.only(filename, () => {

  let wsServer, vServer;

  let wsServerSocket, wsSocket, vServerSocket, vSocket;

  before('start websocket server', done => {
    wsServer = new WebSocket.Server({ port: 8080 });
    wsServer.on('listening', done);
  });

  after('stop clients', () => {
    if (wsSocket) wsSocket.close();
    if (vSocket) vSocket.close();
  });

  after('stop websocket server', done => {
    wsServer.close(done);
  });

  before('start vertex server', done => {
    VertexServer.listen()
      .then(server => {
        vServer = server;
        done();
      })
      .catch(done);
  });

  after('stop vertex server', done => {
    if (!vServer) return done();
    vServer.close();
    done();
  });

  before('connect websocket client', done => {

    wsServer.on('connection', socket => {
      wsServerSocket = socket;
      done();
    });

    wsSocket = new WebSocket('ws://localhost:8080');

  });

  before('connect vertex client', done => {

    vServer.on('connection', socket => {
      vServerSocket = socket;
      // done();
    });

    VertexSocket.connect()
      .then(client => {
        vSocket = client;
        return vSocket.send(); // prevent "Inactivity on connect" closing the socket
      })
      .then(() => done())
      .catch(done);

  });

  context('small frames', function () {

    // 10000 small frames - websocket:     3094ms
    // 10000 small frames - vertex socket: 1373ms

    this.timeout(10000);

    it('compare websocket', done => {

      let messages = [];
      let count = 10000;
      let startAt = Date.now();

      wsServerSocket.on('message', message => {
        JSON.stringify(JSON.parse(message)); // same load as vertex
        Date.now();
        wsServerSocket.send(message);
      });

      wsSocket.on('message', message => {
        JSON.parse(message);
        Date.now();
        messages.push(message);
        if (messages.length >= count) {

          console.log('%d small frames - websocket: %dms', count, Date.now() - startAt);

          return done();
        }
        wsSocket.send(message);
      });

      wsSocket.send(JSON.stringify({small: 'payload'}));

    });

    it('compare vertex socket', done => {

      let messages = [];
      let count = 10000;
      let startAt = Date.now();

      vServerSocket.on('data', vServerSocket.send);

      vSocket.on('data', data => {
        messages.push(data);
        if (messages.length >= count) {

          console.log('%d small frames - vertex socket: %dms', count, Date.now() - startAt);

          return done();
        }
        vSocket.send(data);
      });

      vSocket.send({small: 'payload'});

    });

  });

});
<commit_msg>compare<commit_after>const {basename} = require('path');
const filename = basename(__filename);

const WebSocket = require('ws');
const {VertexServer, VertexSocket} = require('../');

describe.only(filename, () => {

  let wsServer, vServer;

  let wsServerSocket, wsSocket, vServerSocket, vSocket;

  before('start websocket server', done => {
    wsServer = new WebSocket.Server({ port: 8080 });
    wsServer.on('listening', done);
  });

  after('stop clients', () => {
    if (wsSocket) wsSocket.close();
    if (vSocket) vSocket.close();
  });

  after('stop websocket server', done => {
    wsServer.close(done);
  });

  before('start vertex server', done => {
    VertexServer.listen()
      .then(server => {
        vServer = server;
        done();
      })
      .catch(done);
  });

  after('stop vertex server', done => {
    if (!vServer) return done();
    vServer.close();
    done();
  });

  before('connect websocket client', done => {

    wsServer.on('connection', socket => {
      wsServerSocket = socket;
      done();
    });

    wsSocket = new WebSocket('ws://localhost:8080');

  });

  before('connect vertex client', done => {

    vServer.on('connection', socket => {
      vServerSocket = socket;
      // done();
    });

    VertexSocket.connect()
      .then(client => {
        vSocket = client;
        return vSocket.send(); // prevent "Inactivity on connect" closing the socket
      })
      .then(() => done())
      .catch(done);

  });

  context('small frames', function () {

    // 10000 small frames - websocket:     3094ms
    // 10000 small frames - vertex socket: 1373ms

    this.timeout(100000);

    it('compare websocket', done => {

      let messages = [];
      let count = 10000;
      let startAt = Date.now();

      wsServerSocket.on('message', message => {
        JSON.stringify(JSON.parse(message)); // same load as vertex
        Date.now();
        wsServerSocket.send(message);
      });

      wsSocket.on('message', message => {
        JSON.parse(message);
        Date.now();
        messages.push(message);
        if (messages.length >= count) {

          console.log('%d small frames - websocket: %dms', count, Date.now() - startAt);

          return done();
        }
        wsSocket.send(message);
      });

      wsSocket.send(JSON.stringify({small: 'payload'}));

    });

    it('compare vertex socket', done => {

      let messages = [];
      let count = 10000;
      let startAt = Date.now();

      vServerSocket.on('data', vServerSocket.send);

      vSocket.on('data', data => {
        messages.push(data);
        if (messages.length >= count) {

          console.log('%d small frames - vertex socket: %dms', count, Date.now() - startAt);

          return done();
        }
        vSocket.send(data);
      });

      vSocket.send({small: 'payload'});

    });

  });

});
<|endoftext|>


<commit_before>require("../env");

var vows = require("vows"),
    assert = require("assert");

var suite = vows.describe("d3.geo.bounds");

suite.addBatch({
  "bounds": {
    topic: function() {
      return d3.geo.bounds;
    },
    "Feature": function(bounds) {
      assert.deepEqual(bounds({
        type: "Feature",
        geometry: {
          type: "MultiPoint",
          coordinates: [[-123, 39], [-122, 38]]
        }
      }), [[-123, 38], [-122, 39]])
    },
    "FeatureCollection": function(bounds) {
      assert.deepEqual(bounds({
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: [-123, 39]
            }
          },
          {
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: [-122, 38]
            }
          }
        ]
      }), [[-123, 38], [-122, 39]])
    },
    "GeometryCollection": function(bounds) {
      assert.deepEqual(bounds({
        type: "GeometryCollection",
        geometries: [
          {
            type: "Point",
            coordinates: [-123, 39]
          },
          {
            type: "Point",
            coordinates: [-122, 38]
          }
        ]
      }), [[-123, 38], [-122, 39]])
    },
    "LineString": function(bounds) {
      assert.deepEqual(bounds({
        type: "LineString",
        coordinates: [[-123, 39], [-122, 38]]
      }), [[-123, 38], [-122, 39]])
    },
    "MultiLineString": function(bounds) {
      assert.deepEqual(bounds({
        type: "MultiLineString",
        coordinates: [[[-123, 39], [-122, 38]]]
      }), [[-123, 38], [-122, 39]])
    },
    "MultiPoint": function(bounds) {
      assert.deepEqual(bounds({
        type: "MultiPoint",
        coordinates: [[-123, 39], [-122, 38]]
      }), [[-123, 38], [-122, 39]])
    },
    "MultiPolygon": function(bounds) {
      assert.deepEqual(bounds({
        type: "MultiPolygon",
        coordinates: [[[[-123, 39], [-122, 39], [-122, 38], [-123, 39]], [[10, 20], [20, 20], [20, 10], [10, 10], [10, 20]]]]
      }), [[-123, 38], [-122, 39]])
    },
    "Point": function(bounds) {
      assert.deepEqual(bounds({
        type: "Point",
        coordinates: [-123, 39]
      }), [[-123, 39], [-123, 39]])
    },
    "Polygon": function(bounds) {
      assert.deepEqual(bounds({
        type: "Polygon",
        coordinates: [[[-123, 39], [-122, 39], [-122, 38], [-123, 39]], [[10, 20], [20, 20], [20, 10], [10, 10], [10, 20]]]
      }), [[-123, 38], [-122, 39]])
    }
  }
});

suite.export(module);
<commit_msg>test for problematic nesting case<commit_after>require("../env");

var vows = require("vows"),
    assert = require("assert");

var suite = vows.describe("d3.geo.bounds");

suite.addBatch({
  "bounds": {
    topic: function() {
      return d3.geo.bounds;
    },
    "Feature": function(bounds) {
      assert.deepEqual(bounds({
        type: "Feature",
        geometry: {
          type: "MultiPoint",
          coordinates: [[-123, 39], [-122, 38]]
        }
      }), [[-123, 38], [-122, 39]])
    },
    "FeatureCollection": function(bounds) {
      assert.deepEqual(bounds({
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: [-123, 39]
            }
          },
          {
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: [-122, 38]
            }
          }
        ]
      }), [[-123, 38], [-122, 39]])
    },
    "GeometryCollection": function(bounds) {
      assert.deepEqual(bounds({
        type: "GeometryCollection",
        geometries: [
          {
            type: "Point",
            coordinates: [-123, 39]
          },
          {
            type: "Point",
            coordinates: [-122, 38]
          }
        ]
      }), [[-123, 38], [-122, 39]])
    },
    "LineString": function(bounds) {
      assert.deepEqual(bounds({
        type: "LineString",
        coordinates: [[-123, 39], [-122, 38]]
      }), [[-123, 38], [-122, 39]])
    },
    "MultiLineString": function(bounds) {
      assert.deepEqual(bounds({
        type: "MultiLineString",
        coordinates: [[[-123, 39], [-122, 38]]]
      }), [[-123, 38], [-122, 39]])
    },
    "MultiPoint": function(bounds) {
      assert.deepEqual(bounds({
        type: "MultiPoint",
        coordinates: [[-123, 39], [-122, 38]]
      }), [[-123, 38], [-122, 39]])
    },
    "MultiPolygon": function(bounds) {
      assert.deepEqual(bounds({
        type: "MultiPolygon",
        coordinates: [[[[-123, 39], [-122, 39], [-122, 38], [-123, 39]], [[10, 20], [20, 20], [20, 10], [10, 10], [10, 20]]]]
      }), [[-123, 38], [-122, 39]])
    },
    "Point": function(bounds) {
      assert.deepEqual(bounds({
        type: "Point",
        coordinates: [-123, 39]
      }), [[-123, 39], [-123, 39]])
    },
    "Polygon": function(bounds) {
      assert.deepEqual(bounds({
        type: "Polygon",
        coordinates: [[[-123, 39], [-122, 39], [-122, 38], [-123, 39]], [[10, 20], [20, 20], [20, 10], [10, 10], [10, 20]]]
      }), [[-123, 38], [-122, 39]])
    },
    "NestedCollection": function (bounds) {
        assert.deepEqual(bounds({
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "GeometryCollection",
              geometries: [
                {
                  type: "Point",
                  coordinates: [-120,47]
                },
                {
                  type: "Point",
                  coordinates: [-119,46]
                }
              ]
            }
          }
        ]
      }), [[-120,46], [-119,47]])
    }
  }
});

suite.export(module);
<|endoftext|>