<commit_before>var assert = require("assert");
var helpers = require("./helpers");
var _ = require("underscore")._;
var db;

describe('Tables', function () {

  before(function(done){
    helpers.resetDb(function(err,res){
      db = res;
      done();
    });
  });

  describe("Executing inline SQL", function () {
    it('with run and no args returns 3 products', function (done) {
      db.run("select * from products", function(err,res){
        assert.equal(3, res.length)
        done()
      });
    });
    it('with run and id returns Product 1', function (done) {
      db.run("select * from products where id=$1",[1], function(err,res){
        assert.equal(1, res[0].id)
        done()
      });
    });
  });
  describe('Simple queries with args', function () {
    it('returns product 1 with 1 as only arg', function (done) {
      db.products.find(1, function(err,res){
        assert.equal(res.id, 1);
        done();
      });
    });
    it('returns first record with findOne no args', function (done) {
      db.products.findOne(1, function(err,res){
        assert.equal(res.id, 1);
        done();
      });
    });
  });
  describe('Simple queries without args', function () {
    it('returns all records on find with no args', function (done) {
      db.products.find(function(err,res){
        assert.equal(res.length, 3);
        done();
      });
    });
    it('returns first record with findOne no args', function (done) {
      db.products.findOne(function(err,res){
        assert.equal(res.id, 1);
        done();
      });
    });
  });
  describe('Simple queries with AND and OR', function () {
    it('returns Product 1 OR Product 2', function (done) {
      db.products.where("id=$1 OR id=$2", [1,2],function(err,res){
        assert.equal(res.length, 2);
        done();
      });
    });
    it('returns Product 1 AND Product 2', function (done) {
      db.products.where("id=$1 AND price=$2", [1,12.00],function(err,res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns Product 1 with params as not array', function (done) {
      db.products.where("id=$1", 1,function(err,res){
        assert.equal(res.length, 1);
        done();
      });
    });
  });
  describe('Simple queries with count', function () {
    it('returns 2 for OR id 1 or 2', function (done) {
      db.products.count("id=$1 OR id=$2", [1,2],function(err,res){
        assert.equal(res,2);
        done();
      });
    });
    it('returns 1 for id 1', function (done) {
      db.products.count("id=$1", [1],function(err,res){
        assert.equal(res, 1);
        done();
      });
    });
  });
  describe('Simple comparative queries', function () {
    it('returns product with id greater than 2', function (done) {
      db.products.find({"id > " : 2}, function(err,res){
        assert.equal(res[0].id, 3);
        done();
      });
    });
    it('returns product with id less than 2', function (done) {
      db.products.find({"id < " : 2}, function(err,res){
        assert.equal(res[0].id, 1);
        done();
      });
    });
    it('returns products IN 1 and 2', function (done) {
      db.products.find({id : [1,2]}, function(err,res){
        assert.equal(res[0].id, 1);
        done();
      });
    });
    it('returns product NOT IN 1 and 2', function (done) {
      db.products.find({"id <>" : [1,2]}, function(err,res){
        assert.equal(res[0].id, 3);
        done();
      });
    });
  });
  describe('Limiting and Offsetting results', function () {
    it('returns 1 result with limit of 1', function (done) {
      db.products.find(null,{limit : 1}, function(err,res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns second result with limit of 1, offset of 1', function (done) {
      db.products.find({},{limit : 1, offset: 1}, function(err,res){
        assert.equal(res[0].id, 2);
        done();
      });
    });
    it('returns id and name if sending in columns', function (done) {
      db.products.find({},{columns :["id","name"]}, function(err,res){
        var keys = _.keys(res[0]);
        assert.equal(keys.length,2);
        done();
      });
    });
  });

  describe('Ordering results', function () {
    it('returns ascending order of products by price', function (done) {
      db.products.find({}, {order : "price"}, function(err,res){
        assert.equal(res.length, 3);
        assert.equal(res[0].id, 1);
        assert.equal(res[2].id, 3);
        done();
      });
    });
    it('returns descending order of products', function (done) {
      db.products.find({},{order : "id desc"}, function(err,res){
        assert.equal(res.length, 3);
        assert.equal(res[0].id, 3);
        assert.equal(res[2].id, 1);
        done();
      });
    });
  });

  describe('Casing issues', function () {
    it('returns users because we delimit OK', function (done) {
      db.Users.find({}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns the first user because we delimit OK', function (done) {
      db.Users.findOne(function(err,res){
        assert.equal(res.Id, 1);
        done();
      });
    });
    it('returns a subset of columns, when we delimit in the calling code', function (done) {
      db.Users.find({},{columns: ['"Id"','"Email"']}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns a single column, when we delimit in the calling code', function (done) {
      db.Users.find({},{columns: '"Email"'}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns users with a simple order by', function (done) {
      db.Users.find({}, {order: '"Email"'}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns users with a compound order by', function (done) {
      db.Users.find({}, {order: '"Email" asc, "Id" desc'}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
  });
  describe('Full Text search', function () {
    it('returns 3 products for term "product"', function (done) {
      db.products.search({columns : ["name"], term: "Product"},function(err,res){
        assert.equal(res.length,3);
        done();
      });
    });
    it('returns 1 products for term "3"', function (done) {
      db.products.search({columns : ["name"], term: "3"},function(err,res){
        assert.equal(res.length,1);
        done();
      });
    });
  });
});<commit_msg>add tests for add/update/delete #33<commit_after>var assert = require("assert");
var helpers = require("./helpers");
var _ = require("underscore")._;
var db;

describe('Tables -Add/Edit/Delete', function () {

  //Separate 'suite' for add/edit/delete so query tests don't get borked:
  before(function(done){
    helpers.resetDb(function(err,res){
      db = res;
      done();
    });
  });

  describe('Add/Update/Delete records:', function() {
    it('adds a product ', function (done) {
      db.products.save({name : "Gibson Les Paul", description : "Lester's brain child", price : 3500}, function(err, res){
        assert.equal(res.id, 4);
        done();
      });
    });
    it('updates a product ', function (done) {
      db.products.save({id : 4, name : "Fender Stratocaster", description : "Leo Fender's baby", price : 1200}, function(err, res){
        // Update returns an array - Iassume because more than one item can be updated...
        assert.equal(res[0].name, "Fender Stratocaster");
        done();
      });
    });
    it('deletes a product ', function (done) {
      db.products.destroy({id : 4}, function(err, deleted){
        var remaining = db.products.find(4, function(err, found) {
          //Deleted returns an array...
          assert(found == undefined && deleted[0].id == 4);
          done();
        });
      });
    });
  });

});

describe('Tables', function () {

  before(function(done){
    helpers.resetDb(function(err,res){
      db = res;
      done();
    });
  });

  describe("Executing inline SQL", function () {
    it('with run and no args returns 3 products', function (done) {
      db.run("select * from products", function(err,res){
        assert.equal(3, res.length)
        done()
      });
    });
    it('with run and id returns Product 1', function (done) {
      db.run("select * from products where id=$1",[1], function(err,res){
        assert.equal(1, res[0].id)
        done()
      });
    });
  });
  describe('Simple queries with args', function () {
    it('returns product 1 with 1 as only arg', function (done) {
      db.products.find(1, function(err,res){
        assert.equal(res.id, 1);
        done();
      });
    });
    it('returns first record with findOne no args', function (done) {
      db.products.findOne(1, function(err,res){
        assert.equal(res.id, 1);
        done();
      });
    });
  });
  describe('Simple queries without args', function () {
    it('returns all records on find with no args', function (done) {
      db.products.find(function(err,res){
        assert.equal(res.length, 3);
        done();
      });
    });
    it('returns first record with findOne no args', function (done) {
      db.products.findOne(function(err,res){
        assert.equal(res.id, 1);
        done();
      });
    });
  });
  describe('Simple queries with AND and OR', function () {
    it('returns Product 1 OR Product 2', function (done) {
      db.products.where("id=$1 OR id=$2", [1,2],function(err,res){
        assert.equal(res.length, 2);
        done();
      });
    });
    it('returns Product 1 AND Product 2', function (done) {
      db.products.where("id=$1 AND price=$2", [1,12.00],function(err,res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns Product 1 with params as not array', function (done) {
      db.products.where("id=$1", 1,function(err,res){
        assert.equal(res.length, 1);
        done();
      });
    });
  });
  describe('Simple queries with count', function () {
    it('returns 2 for OR id 1 or 2', function (done) {
      db.products.count("id=$1 OR id=$2", [1,2],function(err,res){
        assert.equal(res,2);
        done();
      });
    });
    it('returns 1 for id 1', function (done) {
      db.products.count("id=$1", [1],function(err,res){
        assert.equal(res, 1);
        done();
      });
    });
  });
  describe('Simple comparative queries', function () {
    it('returns product with id greater than 2', function (done) {
      db.products.find({"id > " : 2}, function(err,res){
        assert.equal(res[0].id, 3);
        done();
      });
    });
    it('returns product with id less than 2', function (done) {
      db.products.find({"id < " : 2}, function(err,res){
        assert.equal(res[0].id, 1);
        done();
      });
    });
    it('returns products IN 1 and 2', function (done) {
      db.products.find({id : [1,2]}, function(err,res){
        assert.equal(res[0].id, 1);
        done();
      });
    });
    it('returns product NOT IN 1 and 2', function (done) {
      db.products.find({"id <>" : [1,2]}, function(err,res){
        assert.equal(res[0].id, 3);
        done();
      });
    });
  });
  describe('Limiting and Offsetting results', function () {
    it('returns 1 result with limit of 1', function (done) {
      db.products.find(null,{limit : 1}, function(err,res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns second result with limit of 1, offset of 1', function (done) {
      db.products.find({},{limit : 1, offset: 1}, function(err,res){
        assert.equal(res[0].id, 2);
        done();
      });
    });
    it('returns id and name if sending in columns', function (done) {
      db.products.find({},{columns :["id","name"]}, function(err,res){
        var keys = _.keys(res[0]);
        assert.equal(keys.length,2);
        done();
      });
    });
  });

  describe('Ordering results', function () {
    it('returns ascending order of products by price', function (done) {
      db.products.find({}, {order : "price"}, function(err,res){
        assert.equal(res.length, 3);
        assert.equal(res[0].id, 1);
        assert.equal(res[2].id, 3);
        done();
      });
    });
    it('returns descending order of products', function (done) {
      db.products.find({},{order : "id desc"}, function(err,res){
        assert.equal(res.length, 3);
        assert.equal(res[0].id, 3);
        assert.equal(res[2].id, 1);
        done();
      });
    });
  });
  describe('Casing issues', function () {
    it('returns users because we delimit OK', function (done) {
      db.Users.find({}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns the first user because we delimit OK', function (done) {
      db.Users.findOne(function(err,res){
        assert.equal(res.Id, 1);
        done();
      });
    });
    it('returns a subset of columns, when we delimit in the calling code', function (done) {
      db.Users.find({},{columns: ['"Id"','"Email"']}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns a single column, when we delimit in the calling code', function (done) {
      db.Users.find({},{columns: '"Email"'}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns users with a simple order by', function (done) {
      db.Users.find({}, {order: '"Email"'}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
    it('returns users with a compound order by', function (done) {
      db.Users.find({}, {order: '"Email" asc, "Id" desc'}, function(err, res){
        assert.equal(res.length, 1);
        done();
      });
    });
  });
  describe('Full Text search', function () {
    it('returns 3 products for term "product"', function (done) {
      db.products.search({columns : ["name"], term: "Product"},function(err,res){
        assert.equal(res.length,3);
        done();
      });
    });
    it('returns 1 products for term "3"', function (done) {
      db.products.search({columns : ["name"], term: "3"},function(err,res){
        assert.equal(res.length,1);
        done();
      });
    });
  });
});<|endoftext|>


<commit_before>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'

import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Platform,
  Dimensions,
  Image,
} from 'react-native';

window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
window.fetch = new RNFetchBlob.polyfill.Fetch({
  auto : true,
  binaryContentTypes : ['image/', 'video/', 'audio/']
}).build()

const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : '0.8.2',
  run : true,
  expand : true,
  timeout : 20000,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
const dirs = RNFetchBlob.fs.dirs

let prefix = ((Platform.OS === 'android') ? 'file://' : '')

describe('whatwg-fetch - GET should work correctly', (report, done) => {
  console.log(fetch)
  fetch(`${TEST_SERVER_URL}/unicode`, {
    method : 'GET'
  })
  .then((res) => {
    return res.json()
  })
  .then((data) => {
    console.log(data)
    report(<Assert key="data should correct" expect={'你好!'} actual={data.data}/>)
    done()
  })
})
<commit_msg>Add test case #72<commit_after>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'

import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Platform,
  Dimensions,
  Image,
} from 'react-native';

window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = RNFetchBlob.polyfill.Blob
window.fetch = new RNFetchBlob.polyfill.Fetch({
  auto : true,
  binaryContentTypes : ['image/', 'video/', 'audio/']
}).build()

const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : '0.8.2',
  run : true,
  expand : true,
  timeout : 20000,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
const dirs = RNFetchBlob.fs.dirs

let prefix = ((Platform.OS === 'android') ? 'file://' : '')

describe('whatwg-fetch - GET should work correctly', (report, done) => {
  console.log(fetch)
  fetch(`${TEST_SERVER_URL}/unicode`, {
    method : 'GET'
  })
  .then((res) => {
    return res.json()
  })
  .then((data) => {
    console.log(data)
    report(<Assert key="data should correct" expect={'你好!'} actual={data.data}/>)
    done()
  })
})

RNTest.config({
  group : '0.8.2',
  run : true,
  expand : false,
  timeout : 24000
})('request should not retry after timed out', (report, done) => {

  let count = 0
  RNFetchBlob
    .config({ timeout : 3000 })
    .fetch('GET', `${TEST_SERVER_URL}/timeout`)
    .then((res) => {
      report(<Assert key="request should not success" expect={true} actual={false}/>)
    })
    .catch(() => {
      count ++
    })
  setTimeout(() => {
    report(<Assert key="request does not retry" expect={1} actual={count}/>)
    done()
  }, 12000)
})
<|endoftext|>


<commit_before>var Builder = require('../index');
var inline = require('../lib/output').inlineSourceMap;
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
if (process.argv[2] == 'typescript')
  global.ts = require('typescript');

var minify = true;

var err = function(e) {
  setTimeout(function() {
    throw e;
  });
};

var builder = new Builder('test/fixtures/test-tree', 'test/fixtures/test-tree.config.js');

function testPhantom(html) {
  return new Promise(function(resolve, reject) {
    spawn('node_modules/.bin/mocha-phantomjs' + (process.platform.match(/^win/) ? '.cmd' : ''), [html], { stdio: 'inherit' })
    .on('close', function(code) {
      if (code !== 0)
        reject(Error('Phantom test failed ' + html + ' failed.'));
      else
        resolve();
    });
  });
}

function doTests(transpiler) {

  test('In-memory build', function() {
    builder.reset();
    builder.config({ transpiler: transpiler });
    return builder.bundle('first.js', { sourceMaps: true, minify: minify })
    .then(function(output) {
      fs.writeFileSync('test/output/memory-test.js', inline(output.source, output.sourceMap));
    });
  });

  test('Multi-format tree build', function() {
    builder.reset();
    builder.config({ transpiler: transpiler });

    return builder.bundle('first.js', 'test/output/tree-build.js', { sourceMaps: true, minify: minify, globalDefs: { DEBUG: false } })
    .then(function(output) {
      assert(output.assetList[0].url);
      var treeFirst;
      Promise.all(['first.js', 'amd.js'].map(builder.trace.bind(builder)))
      .then(function(trees) {
        treeFirst = trees[0];
        return builder.bundle(builder.subtractTrees(trees[0], trees[1]), 'test/output/excluded.js');
      })

      .then(function() {
        return builder.trace('global-inner.js').then(function(tree) {
          return builder.bundle(tree, 'test/output/global-inner.js');
        });
      })

      .then(function() {
        return builder.trace('global-outer.js').then(function(tree) {
          return builder.bundle(tree, 'test/output/global-outer.js');
        });
      })

      .then(function() {
        return builder.trace('amd-1.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-1.js');
        });
      })

      .then(function() {
        return builder.trace('amd-2.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-2.js');
        });
      })

      .then(function() {
        return builder.trace('amd-3.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-3.js');
        });
      })

      .then(function() {
        return builder.trace('amd-4.js').then(function(tree) {
          return builder.getDeferredImports(tree)
          .then(function(deferredImports) {
            assert(deferredImports[0].name == 'x');
            return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-4.js');
          });
        });
      })

      .then(function() {
        return builder.trace('amd-5a.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-5a.js');
        });
      })

      .then(function() {
        return builder.trace('amd-5b.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-5b.js');
        });
      })

      .then(function() {
        return builder.trace('amd-6a.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-6a.js');
        });
      })

      .then(function() {
        return builder.trace('amd-6b.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-6b.js');
        });
      })

      .then(function() {
        return builder.trace('umd.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/umd.js');
        });
      })

      .then(function() {
        return builder.bundle('amd-7.js', 'test/output/amd-7.js');
      })

      .then(function() {
        return builder.bundle('amd-8.js', 'test/output/amd-8.js');
      })

      .then(function() {
        return builder.bundle('amd-9.js', 'test/output/amd-9.js');
      })

      .then(function() {
        return builder.bundle('amd-10.js', 'test/output/amd-10.js');
      })

      .then(function() {
        return builder.bundle('amd-11.js', 'test/output/amd-11.js');
      })

      .then(function() {
        return builder.bundle('amd-12.js', 'test/output/amd-12.js');
      })

      .then(function() {
        builder.loader.config({ paths: { 'output/*': './test/output/*' } });
        return builder.bundle('cjs-globals.js - output/amd-8.js', 'test/output/cjs-globals.js');
      })

      .then(function() {
        return builder.bundle('cjs-resolve.js', 'test/output/cjs-resolve.js');
      })

      .then(function() {
        return builder.bundle('runtime.js', 'test/output/runtime.js');
      })
    })
    .then(function () {
      return testPhantom('test/test-build.html');
    })
    ['catch'](function(err) {
      throw err;
    });
  });

  // traceur runtime function.bind fails in Phantom
  if (transpiler != 'traceur')
  test('SFX tree build', function() {
    builder.reset();
    builder.config({ transpiler: transpiler });
    builder.config({
      map: {
        'toamd1': 'amd-1.js'
      },
      meta: {
        'jquery-cdn': {
          build: false
        }
      }
    });
    return builder.buildStatic('toamd1', 'test/output/sfx.js', {
      runtime: true,
      minify: minify,
      format: 'global',
      globalDefs: { DEBUG: false },
      globalName: 'amd1',
      globalDeps: {
        'jquery-cdn': '$'
      }
    })
    .then(function() {
      return testPhantom('test/test-sfx.html');
    });
  });
}

suite('Test tree builds - Traceur', function() {

  doTests('traceur');

});

suite('Test tree builds - Babel', function() {

  doTests('babel');

});

suite('Test tree builds - TypeScript', function() {

  doTests('typescript');

});

suite('Bundle Format', function() {
  test('Test AMD format', function() {
    return Promise.resolve()
    .then(function() {
      return builder.buildStatic('sfx-format-01.js', 'test/output/sfx-amd.js', { format: 'amd' });
    })
    .then(function() {
      return testPhantom('test/test-sfx-amd.html');
    });
  });
});

<commit_msg>windows test fix<commit_after>var Builder = require('../index');
var inline = require('../lib/output').inlineSourceMap;
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
if (process.argv[2] == 'typescript')
  global.ts = require('typescript');

var minify = true;

var err = function(e) {
  setTimeout(function() {
    throw e;
  });
};

var builder = new Builder('test/fixtures/test-tree', 'test/fixtures/test-tree.config.js');

function testPhantom(html) {
  return new Promise(function(resolve, reject) {
    spawn(path.resolve('node_modules/.bin/mocha-phantomjs' + (process.platform.match(/^win/) ? '.cmd' : '')), [html], { stdio: 'inherit' })
    .on('close', function(code) {
      if (code !== 0)
        reject(Error('Phantom test failed ' + html + ' failed.'));
      else
        resolve();
    });
  });
}

function doTests(transpiler) {

  test('In-memory build', function() {
    builder.reset();
    builder.config({ transpiler: transpiler });
    return builder.bundle('first.js', { sourceMaps: true, minify: minify })
    .then(function(output) {
      fs.writeFileSync('test/output/memory-test.js', inline(output.source, output.sourceMap));
    });
  });

  test('Multi-format tree build', function() {
    builder.reset();
    builder.config({ transpiler: transpiler });

    return builder.bundle('first.js', 'test/output/tree-build.js', { sourceMaps: true, minify: minify, globalDefs: { DEBUG: false } })
    .then(function(output) {
      assert(output.assetList[0].url);
      var treeFirst;
      Promise.all(['first.js', 'amd.js'].map(builder.trace.bind(builder)))
      .then(function(trees) {
        treeFirst = trees[0];
        return builder.bundle(builder.subtractTrees(trees[0], trees[1]), 'test/output/excluded.js');
      })

      .then(function() {
        return builder.trace('global-inner.js').then(function(tree) {
          return builder.bundle(tree, 'test/output/global-inner.js');
        });
      })

      .then(function() {
        return builder.trace('global-outer.js').then(function(tree) {
          return builder.bundle(tree, 'test/output/global-outer.js');
        });
      })

      .then(function() {
        return builder.trace('amd-1.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-1.js');
        });
      })

      .then(function() {
        return builder.trace('amd-2.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-2.js');
        });
      })

      .then(function() {
        return builder.trace('amd-3.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-3.js');
        });
      })

      .then(function() {
        return builder.trace('amd-4.js').then(function(tree) {
          return builder.getDeferredImports(tree)
          .then(function(deferredImports) {
            assert(deferredImports[0].name == 'x');
            return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-4.js');
          });
        });
      })

      .then(function() {
        return builder.trace('amd-5a.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-5a.js');
        });
      })

      .then(function() {
        return builder.trace('amd-5b.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-5b.js');
        });
      })

      .then(function() {
        return builder.trace('amd-6a.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-6a.js');
        });
      })

      .then(function() {
        return builder.trace('amd-6b.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/amd-6b.js');
        });
      })

      .then(function() {
        return builder.trace('umd.js').then(function(tree) {
          return builder.bundle(builder.subtractTrees(tree, treeFirst), 'test/output/umd.js');
        });
      })

      .then(function() {
        return builder.bundle('amd-7.js', 'test/output/amd-7.js');
      })

      .then(function() {
        return builder.bundle('amd-8.js', 'test/output/amd-8.js');
      })

      .then(function() {
        return builder.bundle('amd-9.js', 'test/output/amd-9.js');
      })

      .then(function() {
        return builder.bundle('amd-10.js', 'test/output/amd-10.js');
      })

      .then(function() {
        return builder.bundle('amd-11.js', 'test/output/amd-11.js');
      })

      .then(function() {
        return builder.bundle('amd-12.js', 'test/output/amd-12.js');
      })

      .then(function() {
        builder.loader.config({ paths: { 'output/*': './test/output/*' } });
        return builder.bundle('cjs-globals.js - output/amd-8.js', 'test/output/cjs-globals.js');
      })

      .then(function() {
        return builder.bundle('cjs-resolve.js', 'test/output/cjs-resolve.js');
      })

      .then(function() {
        return builder.bundle('runtime.js', 'test/output/runtime.js');
      })
    })
    .then(function () {
      return testPhantom('test/test-build.html');
    })
    ['catch'](function(err) {
      throw err;
    });
  });

  // traceur runtime function.bind fails in Phantom
  if (transpiler != 'traceur')
  test('SFX tree build', function() {
    builder.reset();
    builder.config({ transpiler: transpiler });
    builder.config({
      map: {
        'toamd1': 'amd-1.js'
      },
      meta: {
        'jquery-cdn': {
          build: false
        }
      }
    });
    return builder.buildStatic('toamd1', 'test/output/sfx.js', {
      runtime: true,
      minify: minify,
      format: 'global',
      globalDefs: { DEBUG: false },
      globalName: 'amd1',
      globalDeps: {
        'jquery-cdn': '$'
      }
    })
    .then(function() {
      return testPhantom('test/test-sfx.html');
    });
  });
}

suite('Test tree builds - Traceur', function() {

  doTests('traceur');

});

suite('Test tree builds - Babel', function() {

  doTests('babel');

});

suite('Test tree builds - TypeScript', function() {

  doTests('typescript');

});

suite('Bundle Format', function() {
  test('Test AMD format', function() {
    return Promise.resolve()
    .then(function() {
      return builder.buildStatic('sfx-format-01.js', 'test/output/sfx-amd.js', { format: 'amd' });
    })
    .then(function() {
      return testPhantom('test/test-sfx-amd.html');
    });
  });
});

<|endoftext|>


<commit_before>const {eq} = require("prosemirror-test-builder")
const ist = require("ist")

const {schema, defaultMarkdownParser, defaultMarkdownSerializer} = require("../dist")

const {doc, blockquote, h1, h2, p, hr, li, ol, ul, pre, em, strong, code, a, br, img} = require("./build")

function parse(text, doc) {
  ist(defaultMarkdownParser.parse(text), doc, eq)
}

function serialize(doc, text) {
  ist(defaultMarkdownSerializer.serialize(doc), text)
}

function same(text, doc) {
  parse(text, doc)
  serialize(doc, text)
}

describe("markdown", () => {
  it("parses a paragraph", () =>
     same("hello!",
          doc(p("hello!"))))

  it("parses headings", () =>
     same("# one\n\n## two\n\nthree",
          doc(h1("one"), h2("two"), p("three"))))

  it("parses a blockquote", () =>
     same("> once\n\n> > twice",
          doc(blockquote(p("once")), blockquote(blockquote(p("twice"))))))

  // FIXME bring back testing for preserving bullets and tight attrs
  // when supported again

  it("parses a bullet list", () =>
     same("* foo\n\n  * bar\n\n  * baz\n\n* quux",
          doc(ul(li(p("foo"), ul(li(p("bar")), li(p("baz")))), li(p("quux"))))))

  it("parses an ordered list", () =>
     same("1. Hello\n\n2. Goodbye\n\n3. Nest\n\n   1. Hey\n\n   2. Aye",
          doc(ol(li(p("Hello")), li(p("Goodbye")), li(p("Nest"), ol(li(p("Hey")), li(p("Aye"))))))))

  it("parses a code block", () =>
     same("Some code:\n\n```\nHere it is\n```\n\nPara",
          doc(p("Some code:"), schema.node("code_block", {params: ""}, [schema.text("Here it is")]), p("Para"))))

  it("parses an intended code block", () =>
     parse("Some code:\n\n    Here it is\n\nPara",
          doc(p("Some code:"), pre("Here it is"), p("Para"))))

  it("parses a fenced code block with info string", () =>
     same("foo\n\n```javascript\n1\n```",
          doc(p("foo"), schema.node("code_block", {params: "javascript"}, [schema.text("1")]))))

  it("parses inline marks", () =>
     same("Hello. Some *em* text, some **strong** text, and some `code`",
          doc(p("Hello. Some ", em("em"), " text, some ", strong("strong"), " text, and some ", code("code")))))

  it("parses overlapping inline marks", () =>
     same("This is **strong *emphasized text with `code` in* it**",
          doc(p("This is ", strong("strong ", em("emphasized text with ", code("code"), " in"), " it")))))

  it("parses links inside strong text", () =>
     same("**[link](foo) is bold**",
          doc(p(strong(a("link"), " is bold")))))

  it("parses code mark inside strong text", () =>
     same("**`code` is bold**",
          doc(p(strong(code("code"), " is bold")))))

  it("parses links", () =>
     same("My [link](foo) goes to foo",
          doc(p("My ", a("link"), " goes to foo"))))

  it("parses an image", () =>
     same("Here's an image: ![x](img.png)",
          doc(p("Here's an image: ", img))))

  it("parses a line break", () =>
     same("line one\\\nline two",
          doc(p("line one", br, "line two"))))

  it("parses a horizontal rule", () =>
     same("one two\n\n---\n\nthree",
          doc(p("one two"), hr, p("three"))))

  it("ignores HTML tags", () =>
     same("Foo < img> bar",
          doc(p("Foo < img> bar"))))

  it("doesn't accidentally generate list markup", () =>
     same("1\\. foo",
          doc(p("1. foo"))))

  it("doesn't fail with line break inside inline mark", () =>
     same("**text1\ntext2**", doc(p(strong("text1\ntext2")))))

  it("drops trailing hard breaks", () =>
     serialize(doc(p("a", br, br)), "a"))

  it("expels enclosing whitespace from inside emphasis", () =>
     serialize(doc(p("Some emphasized text with", strong(em("  whitespace   ")), "surrounding the emphasis.")),
               "Some emphasized text with  ***whitespace***   surrounding the emphasis."))

  it("puts trailing hard break out of emphasised content", () =>
     serialize(doc(p("text1", strong(em("before break", br)), "text2")),
               "text1***before break***\\\ntext2"))

  it("puts trailing hard break out of emphasised content", () =>
     serialize(doc(p("text1 ", strong(em("before break", br)), "text2")),
               "text1 ***before break***\\\ntext2"))

  it("leaves non-trailing hard break in emphasized content", () =>
     serialize(doc(p("text1 ", strong(em("before break", br, "after break")), " text2")),
               "text1 ***before break\\\nafter break*** text2"))

  it("drops nodes when all whitespace is expelled from them", () =>
     serialize(doc(p("Text with", em(" "), "an emphasized space")),
               "Text with an emphasized space"))

  it("doesn't put a code block after a list item inside the list item", () =>
     same("* list item\n\n```\ncode\n```",
          doc(ul(li(p("list item"))), pre("code"))))

  it("doesn't escape characters in code", () =>
     same("foo`*`", doc(p("foo", code("*")))))
})
<commit_msg>Add tests for serializing inline code<commit_after>const {eq} = require("prosemirror-test-builder")
const ist = require("ist")

const {schema, defaultMarkdownParser, defaultMarkdownSerializer} = require("../dist")

const {doc, blockquote, h1, h2, p, hr, li, ol, ul, pre, em, strong, code, a, br, img} = require("./build")

function parse(text, doc) {
  ist(defaultMarkdownParser.parse(text), doc, eq)
}

function serialize(doc, text) {
  ist(defaultMarkdownSerializer.serialize(doc), text)
}

function same(text, doc) {
  parse(text, doc)
  serialize(doc, text)
}

describe("markdown", () => {
  it("parses a paragraph", () =>
     same("hello!",
          doc(p("hello!"))))

  it("parses headings", () =>
     same("# one\n\n## two\n\nthree",
          doc(h1("one"), h2("two"), p("three"))))

  it("parses a blockquote", () =>
     same("> once\n\n> > twice",
          doc(blockquote(p("once")), blockquote(blockquote(p("twice"))))))

  // FIXME bring back testing for preserving bullets and tight attrs
  // when supported again

  it("parses a bullet list", () =>
     same("* foo\n\n  * bar\n\n  * baz\n\n* quux",
          doc(ul(li(p("foo"), ul(li(p("bar")), li(p("baz")))), li(p("quux"))))))

  it("parses an ordered list", () =>
     same("1. Hello\n\n2. Goodbye\n\n3. Nest\n\n   1. Hey\n\n   2. Aye",
          doc(ol(li(p("Hello")), li(p("Goodbye")), li(p("Nest"), ol(li(p("Hey")), li(p("Aye"))))))))

  it("parses a code block", () =>
     same("Some code:\n\n```\nHere it is\n```\n\nPara",
          doc(p("Some code:"), schema.node("code_block", {params: ""}, [schema.text("Here it is")]), p("Para"))))

  it("parses an intended code block", () =>
     parse("Some code:\n\n    Here it is\n\nPara",
          doc(p("Some code:"), pre("Here it is"), p("Para"))))

  it("parses a fenced code block with info string", () =>
     same("foo\n\n```javascript\n1\n```",
          doc(p("foo"), schema.node("code_block", {params: "javascript"}, [schema.text("1")]))))

  it("parses inline marks", () =>
     same("Hello. Some *em* text, some **strong** text, and some `code`",
          doc(p("Hello. Some ", em("em"), " text, some ", strong("strong"), " text, and some ", code("code")))))

  it("parses overlapping inline marks", () =>
     same("This is **strong *emphasized text with `code` in* it**",
          doc(p("This is ", strong("strong ", em("emphasized text with ", code("code"), " in"), " it")))))

  it("parses links inside strong text", () =>
     same("**[link](foo) is bold**",
          doc(p(strong(a("link"), " is bold")))))

  it("parses code mark inside strong text", () =>
     same("**`code` is bold**",
          doc(p(strong(code("code"), " is bold")))))

  it("parses code mark containing backticks", () =>
     same("``` one backtick: ` two backticks: `` ```",
          doc(p(code("one backtick: ` two backticks: ``")))))

  it("parses code mark containing only whitespace", () =>
     serialize(doc(p("Three spaces: ", code("   "))),
               "Three spaces: `   `"))

  it("parses links", () =>
     same("My [link](foo) goes to foo",
          doc(p("My ", a("link"), " goes to foo"))))

  it("parses an image", () =>
     same("Here's an image: ![x](img.png)",
          doc(p("Here's an image: ", img))))

  it("parses a line break", () =>
     same("line one\\\nline two",
          doc(p("line one", br, "line two"))))

  it("parses a horizontal rule", () =>
     same("one two\n\n---\n\nthree",
          doc(p("one two"), hr, p("three"))))

  it("ignores HTML tags", () =>
     same("Foo < img> bar",
          doc(p("Foo < img> bar"))))

  it("doesn't accidentally generate list markup", () =>
     same("1\\. foo",
          doc(p("1. foo"))))

  it("doesn't fail with line break inside inline mark", () =>
     same("**text1\ntext2**", doc(p(strong("text1\ntext2")))))

  it("drops trailing hard breaks", () =>
     serialize(doc(p("a", br, br)), "a"))

  it("expels enclosing whitespace from inside emphasis", () =>
     serialize(doc(p("Some emphasized text with", strong(em("  whitespace   ")), "surrounding the emphasis.")),
               "Some emphasized text with  ***whitespace***   surrounding the emphasis."))

  it("drops nodes when all whitespace is expelled from them", () =>
     serialize(doc(p("Text with", em(" "), "an emphasized space")),
               "Text with an emphasized space"))

  it("doesn't put a code block after a list item inside the list item", () =>
     same("* list item\n\n```\ncode\n```",
          doc(ul(li(p("list item"))), pre("code"))))

  it("doesn't escape characters in code", () =>
     same("foo`*`", doc(p("foo", code("*")))))
})
<|endoftext|>


<commit_before>var ECDSA = require('../lib/ecdsa');
var Hash = require('../lib/hash');
var Key = require('../lib/key');
var Privkey = require('../lib/privkey');
var Pubkey = require('../lib/pubkey');
var Signature = require('../lib/signature');
var BN = require('../lib/bn');
var point = require('../lib/point');
var should = require('chai').should();

describe("ECDSA", function() {

  it('should create a blank ecdsa', function() {
    var ecdsa = new ECDSA();
  });

  var ecdsa = new ECDSA();
  ecdsa.hashbuf = Hash.sha256(new Buffer('test data'));
  ecdsa.key = new Key();
  ecdsa.key.privkey = new Privkey(BN.fromBuffer(new Buffer('fee0a1f7afebf9d2a5a80c0c98a31c709681cce195cbcd06342b517970c0be1e', 'hex')));
  ecdsa.key.pubkey = new Pubkey(point(BN.fromBuffer(new Buffer('ac242d242d23be966085a2b2b893d989f824e06c9ad0395a8a52f055ba39abb2', 'hex')),
                                      BN.fromBuffer(new Buffer('4836ab292c105a711ed10fcfd30999c31ff7c02456147747e03e739ad527c380', 'hex'))));

  describe('#calci', function() {

    it('should calculate i', function() {
      ecdsa.randomK();
      ecdsa.sign();
      ecdsa.calci();
      should.exist(ecdsa.sig.i);
    });

    it('should calulate this known i', function() {
      var hashbuf = Hash.sha256(new Buffer('some data'));
      var r = BN('71706645040721865894779025947914615666559616020894583599959600180037551395766', 10);
      var s = BN('109412465507152403114191008482955798903072313614214706891149785278625167723646', 10);
      var ecdsa = new ECDSA();
      ecdsa.key = new Key();
      ecdsa.key.privkey = Privkey();
      ecdsa.key.privkey.bn = BN().fromBuffer(Hash.sha256(new Buffer('test')));
      ecdsa.key.privkey2pubkey();
      ecdsa.hashbuf = hashbuf;
      ecdsa.sig = new Signature(r, s);

      ecdsa.calci();
      ecdsa.sig.i.should.equal(1);
    });

  });

  describe('#fromString', function() {

    it('should to a round trip with to string', function() {
      var str = ecdsa.toString();
      var ecdsa2 = new ECDSA();
      ecdsa2.fromString(str);
      should.exist(ecdsa.hashbuf);
      should.exist(ecdsa.key);
    });

  });

  describe('#randomK', function() {

    it('should generate a new random k when called twice in a row', function() {
      ecdsa.randomK();
      var k1 = ecdsa.k;
      ecdsa.randomK();
      var k2 = ecdsa.k;
      (k1.cmp(k2) === 0).should.equal(false);
    });

    it('should generate a random k that is (almost always) greater than this relatively small number', function() {
      ecdsa.randomK();
      var k1 = ecdsa.k;
      var k2 = BN(Math.pow(2, 32)).mul(BN(Math.pow(2, 32))).mul(BN(Math.pow(2, 32)));
      k2.gt(k1).should.equal(false);
    });

  });

  describe('#sig2pubkey', function() {

    it('should calculate the correct public key', function() {
      ecdsa.k = BN('114860389168127852803919605627759231199925249596762615988727970217268189974335', 10);
      ecdsa.sign();
      ecdsa.sig.i = 1;
      var pubkey = ecdsa.sig2pubkey();
      pubkey.point.eq(ecdsa.key.pubkey.point).should.equal(true);
    });

  });

  describe('#sigError', function() {

    it('should return an error if the hash is invalid', function() {
      var ecdsa = new ECDSA();
      ecdsa.sigError().should.equal('Invalid hash');
    });

    it('should return an error if the pubkey is invalid', function() {
      var ecdsa = new ECDSA();
      ecdsa.hashbuf = Hash.sha256(new Buffer('test'));
      ecdsa.sigError().indexOf("Invalid pubkey").should.equal(0);
    });

    it('should return an error if r, s are invalid', function() {
      var ecdsa = new ECDSA();
      ecdsa.hashbuf = Hash.sha256(new Buffer('test'));
      var pk = new Pubkey();
      pk.fromDER(new Buffer('041ff0fe0f7b15ffaa85ff9f4744d539139c252a49710fb053bb9f2b933173ff9a7baad41d04514751e6851f5304fd243751703bed21b914f6be218c0fa354a341', 'hex'));
      ecdsa.key = new Key();
      ecdsa.key.pubkey = pk;
      ecdsa.sig = new Signature();
      ecdsa.sig.r = BN(0);
      ecdsa.sig.s = BN(0);
      ecdsa.sigError().should.equal("r and s not in range");
    });

    it('should return an error if the signature is incorrect', function() {
      ecdsa.sig = new Signature();
      ecdsa.sig.fromString('3046022100e9915e6236695f093a4128ac2a956c40ed971531de2f4f41ba05fac7e2bd019c02210094e6a4a769cc7f2a8ab3db696c7cd8d56bcdbfff860a8c81de4bc6a798b90827');
      ecdsa.sig.r = ecdsa.sig.r.add(BN(1));
      ecdsa.sigError().should.equal("Invalid signature");
    });

  });

  describe('#sign', function() {

    it('should create a valid signature', function() {
      ecdsa.randomK();
      ecdsa.sign();
      ecdsa.verify().should.equal(true);
    });

  });

  describe('#signRandomK', function() {

    it('should produce a signature', function() {
      ecdsa.signRandomK();
      should.exist(ecdsa.sig);
    });

  });

  describe('#toString', function() {

    it('should convert this to a string', function() {
      var str = ecdsa.toString();
      (typeof str === 'string').should.equal(true);
    });

  });

  describe('#verify', function() {

    it('should verify a signature that was just signed', function() {
      ecdsa.sig = new Signature();
      ecdsa.sig.fromString('3046022100e9915e6236695f093a4128ac2a956c40ed971531de2f4f41ba05fac7e2bd019c02210094e6a4a769cc7f2a8ab3db696c7cd8d56bcdbfff860a8c81de4bc6a798b90827');
      ecdsa.verify().should.equal(true);
    });

    it('should verify this known good signature', function() {
      ecdsa.signRandomK();
      ecdsa.verify().should.equal(true);
    });

  });

});
<commit_msg>BN -> BN()<commit_after>var ECDSA = require('../lib/ecdsa');
var Hash = require('../lib/hash');
var Key = require('../lib/key');
var Privkey = require('../lib/privkey');
var Pubkey = require('../lib/pubkey');
var Signature = require('../lib/signature');
var BN = require('../lib/bn');
var point = require('../lib/point');
var should = require('chai').should();

describe("ECDSA", function() {

  it('should create a blank ecdsa', function() {
    var ecdsa = new ECDSA();
  });

  var ecdsa = new ECDSA();
  ecdsa.hashbuf = Hash.sha256(new Buffer('test data'));
  ecdsa.key = new Key();
  ecdsa.key.privkey = new Privkey(BN().fromBuffer(new Buffer('fee0a1f7afebf9d2a5a80c0c98a31c709681cce195cbcd06342b517970c0be1e', 'hex')));
  ecdsa.key.pubkey = new Pubkey(point(BN().fromBuffer(new Buffer('ac242d242d23be966085a2b2b893d989f824e06c9ad0395a8a52f055ba39abb2', 'hex')),
                                      BN().fromBuffer(new Buffer('4836ab292c105a711ed10fcfd30999c31ff7c02456147747e03e739ad527c380', 'hex'))));

  describe('#calci', function() {

    it('should calculate i', function() {
      ecdsa.randomK();
      ecdsa.sign();
      ecdsa.calci();
      should.exist(ecdsa.sig.i);
    });

    it('should calulate this known i', function() {
      var hashbuf = Hash.sha256(new Buffer('some data'));
      var r = BN('71706645040721865894779025947914615666559616020894583599959600180037551395766', 10);
      var s = BN('109412465507152403114191008482955798903072313614214706891149785278625167723646', 10);
      var ecdsa = new ECDSA();
      ecdsa.key = new Key();
      ecdsa.key.privkey = Privkey();
      ecdsa.key.privkey.bn = BN().fromBuffer(Hash.sha256(new Buffer('test')));
      ecdsa.key.privkey2pubkey();
      ecdsa.hashbuf = hashbuf;
      ecdsa.sig = new Signature(r, s);

      ecdsa.calci();
      ecdsa.sig.i.should.equal(1);
    });

  });

  describe('#fromString', function() {

    it('should to a round trip with to string', function() {
      var str = ecdsa.toString();
      var ecdsa2 = new ECDSA();
      ecdsa2.fromString(str);
      should.exist(ecdsa.hashbuf);
      should.exist(ecdsa.key);
    });

  });

  describe('#randomK', function() {

    it('should generate a new random k when called twice in a row', function() {
      ecdsa.randomK();
      var k1 = ecdsa.k;
      ecdsa.randomK();
      var k2 = ecdsa.k;
      (k1.cmp(k2) === 0).should.equal(false);
    });

    it('should generate a random k that is (almost always) greater than this relatively small number', function() {
      ecdsa.randomK();
      var k1 = ecdsa.k;
      var k2 = BN(Math.pow(2, 32)).mul(BN(Math.pow(2, 32))).mul(BN(Math.pow(2, 32)));
      k2.gt(k1).should.equal(false);
    });

  });

  describe('#sig2pubkey', function() {

    it('should calculate the correct public key', function() {
      ecdsa.k = BN('114860389168127852803919605627759231199925249596762615988727970217268189974335', 10);
      ecdsa.sign();
      ecdsa.sig.i = 1;
      var pubkey = ecdsa.sig2pubkey();
      pubkey.point.eq(ecdsa.key.pubkey.point).should.equal(true);
    });

  });

  describe('#sigError', function() {

    it('should return an error if the hash is invalid', function() {
      var ecdsa = new ECDSA();
      ecdsa.sigError().should.equal('Invalid hash');
    });

    it('should return an error if the pubkey is invalid', function() {
      var ecdsa = new ECDSA();
      ecdsa.hashbuf = Hash.sha256(new Buffer('test'));
      ecdsa.sigError().indexOf("Invalid pubkey").should.equal(0);
    });

    it('should return an error if r, s are invalid', function() {
      var ecdsa = new ECDSA();
      ecdsa.hashbuf = Hash.sha256(new Buffer('test'));
      var pk = new Pubkey();
      pk.fromDER(new Buffer('041ff0fe0f7b15ffaa85ff9f4744d539139c252a49710fb053bb9f2b933173ff9a7baad41d04514751e6851f5304fd243751703bed21b914f6be218c0fa354a341', 'hex'));
      ecdsa.key = new Key();
      ecdsa.key.pubkey = pk;
      ecdsa.sig = new Signature();
      ecdsa.sig.r = BN(0);
      ecdsa.sig.s = BN(0);
      ecdsa.sigError().should.equal("r and s not in range");
    });

    it('should return an error if the signature is incorrect', function() {
      ecdsa.sig = new Signature();
      ecdsa.sig.fromString('3046022100e9915e6236695f093a4128ac2a956c40ed971531de2f4f41ba05fac7e2bd019c02210094e6a4a769cc7f2a8ab3db696c7cd8d56bcdbfff860a8c81de4bc6a798b90827');
      ecdsa.sig.r = ecdsa.sig.r.add(BN(1));
      ecdsa.sigError().should.equal("Invalid signature");
    });

  });

  describe('#sign', function() {

    it('should create a valid signature', function() {
      ecdsa.randomK();
      ecdsa.sign();
      ecdsa.verify().should.equal(true);
    });

  });

  describe('#signRandomK', function() {

    it('should produce a signature', function() {
      ecdsa.signRandomK();
      should.exist(ecdsa.sig);
    });

  });

  describe('#toString', function() {

    it('should convert this to a string', function() {
      var str = ecdsa.toString();
      (typeof str === 'string').should.equal(true);
    });

  });

  describe('#verify', function() {

    it('should verify a signature that was just signed', function() {
      ecdsa.sig = new Signature();
      ecdsa.sig.fromString('3046022100e9915e6236695f093a4128ac2a956c40ed971531de2f4f41ba05fac7e2bd019c02210094e6a4a769cc7f2a8ab3db696c7cd8d56bcdbfff860a8c81de4bc6a798b90827');
      ecdsa.verify().should.equal(true);
    });

    it('should verify this known good signature', function() {
      ecdsa.signRandomK();
      ecdsa.verify().should.equal(true);
    });

  });

});
<|endoftext|>


<commit_before>describe("utils", function () {
    var utils = require('phonegap/utils');

    describe("clone", function () {
        it("can clone null", function () {
            expect(utils.clone(null)).toBeNull();
        });
    });
});
<commit_msg>added some more utils tests<commit_after>describe("utils", function () {
    var utils = require('phonegap/utils');

    describe("when cloning", function () {
        it("can clone an array", function () {
            var orig = [1, 2, 3, {four: 4}, "5"];

            expect(utils.clone(orig)).toEqual(orig);
            expect(utils.clone(orig)).not.toBe(orig);
        });

        it("can clone null", function () {
            expect(utils.clone(null)).toBeNull();
        });

        it("can clone undefined", function () {
            expect(utils.clone(undefined)).not.toBeDefined();
        });

        it("can clone a function", function () {
            var f = function () { return 4; };
            expect(utils.clone(f)).toBe(f);
        });

        it("can clone a number", function () {
            expect(utils.clone(4)).toBe(4);
        });

        it("can clone a string", function () {
            expect(utils.clone("why")).toBe("why");
        });

        it("can clone a date", function () {
            var d = Date.now();
            expect(utils.clone(d)).toBe(d);
        });

        it("can clone an object", function () {

            var orig = {
                a: {
                    b: {
                        c: "d"
                    },
                },
                e: "f",
                g: "unit"
            },
            expected = {
                a: {
                    b: {
                        c: "d"
                    },
                },
                e: "f",
                g: "unit"
            };

            expect(utils.clone(orig)).toEqual(expected);
        });
    });
});
<|endoftext|>


<commit_before>'use strict'
const test = require('tape')
const subsTest = require('../util')

test('test - basic', function (t) {
  const subs = {
    letters: {
      $any: {
        $test: {
          exec (state) {
            return state.compute() === 'a'
          },
          $pass: { val: true }
        }
      }
    }
  }

  const state = {
    letters: [ 'a', 'b', 'c' ]
  }

  const s = subsTest(t, state, subs)

  s('initial subscription', [
    { path: 'letters/0', type: 'new' }
  ])

  s(
    'change letters/2 to a',
    [
      { path: 'letters/2', type: 'new' }
    ],
    { letters: { 2: 'a' } }
  )

  t.end()
})
<commit_msg>added breaking root case<commit_after>'use strict'
const test = require('tape')
const subsTest = require('../util')

test('test - basic', function (t) {
  const subs = {
    letters: {
      $any: {
        $test: {
          exec (state) {
            return state.compute() === 'a'
          },
          $pass: { val: true }
        }
      }
    }
  }

  const state = {
    letters: [ 'a', 'b', 'c' ]
  }

  const s = subsTest(t, state, subs)

  s('initial subscription', [
    { path: 'letters/0', type: 'new' }
  ])

  s(
    'change letters/2 to a',
    [
      { path: 'letters/2', type: 'new' }
    ],
    { letters: { 2: 'a' } }
  )

  t.end()
})

test('test - basic - root', function (t) {
  const subs = {
    x: {
      $test: {
        exec (state) {
          return state.compute() > 50
        },
        $pass: { $root: { bla: { val: true } } }
      }
    }
  }

  const state = { bla: true, x: 100 }
  const s = subsTest(t, state, subs)

  s('initial subscription', [
    { path: 'bla', type: 'new' }
  ])

  s(
    'change bla to false',
    [
      { path: 'bla', type: 'update' }
    ],
    { bla: false }
  )

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


<commit_before><commit_msg>Added a few more solutions<commit_after><|endoftext|>


<commit_before>goog.provide('options');
goog.require('api.Bitbucket');
goog.require('api.Redmine');

/**
 * @return {{sync: string, redmineHost: string, redmineApiKey: string, token: string}}
 */
function readSettings() {
	return {
		sync: document.getElementById('settings').value,
		redmineHost: document.getElementById('settings_redmine_host').value,
		redmineApiKey: document.getElementById('settings_redmine_api_key').value,
		token: document.getElementById('settings_token').value,
		bitbucketOwner: document.getElementById('settings_bitbucket_owner').value
	};
}

/**
 * @param {{
 *      sync: string,
 *      redmineHost: string,
 *      redmineApiKey: string,
 *      token: string
 * }} settings
 * @return {Promise}
 */
function saveOptions(settings) {
	return new Promise(function(resolve, reject) {
		chrome.storage.sync.set({
			'settings': settings
		}, function() {
			// Update status to let user know options were saved.
			var status = document.getElementById('status');
			status.textContent = 'Options saved.';

			resolve();
		});
	});
}

/**
 * @return {Promise}
 */
function restoreOptions() {
	return new Promise(function(resolve, reject) {
		chrome.storage.sync.get(null, function(items) {
			document.getElementById('settings').value = items.settings.sync || '';
			document.getElementById('settings_token').value = items.settings.token || '';
			document.getElementById('settings_redmine_host').value = items.settings.redmineHost || '';
			document.getElementById('settings_redmine_api_key').value = items.settings.redmineApiKey || '';
			document.getElementById('settings_bitbucket_owner').value = 'interfaced';

			resolve();
		});
	});
}

document.addEventListener('DOMContentLoaded', function() {
	restoreOptions().then(function() {
		var _api = {
			bitbucket: new api.Bitbucket,
			redmine: new api.Redmine
		};

		Promise.all([
				_api.redmine.getProjects(),
				_api.bitbucket.getRepositories(document.getElementById('settings_bitbucket_owner').value)
			])
			.then(function(response) {
				var redmineProjects = response[0].projects;
				var bitbucketRepo = response[1];

				var sort = function(a, b) {
					return a.name.localeCompare(b.name);
				};
				redmineProjects.sort(sort).forEach(function(project) {
					var option = document.createElement('option');
					option.setAttribute('value', project.identifier);
					option.innerText = project.name;
					document.getElementById('redmine-projects').appendChild(option);
				});

				bitbucketRepo.sort(sort).forEach(function(repo) {
					var option = document.createElement('option');
					option.setAttribute('value', repo.name);
					option.innerText = repo.name;
					document.getElementById('bitbucket-repo').appendChild(option);
				});

			});
	});
});
document.getElementById('save').addEventListener('click', function() {
	saveOptions(readSettings());
});
document.getElementById('link-button').addEventListener('click', function() {
	var redmineProject = document.getElementById('redmine-projects').value;
	var bitbucketRepo = document.getElementById('bitbucket-repo').value;

	var settings = readSettings();
	var sync = settings.sync;

	try {
		sync = JSON.parse(sync);
	} catch (e) {
		sync = {};
	}

	var bitbucketOwner = settings.bitbucketOwner;
	sync[bitbucketOwner] = sync[bitbucketOwner] || {};
	sync[bitbucketOwner][redmineProject] = bitbucketRepo;
	settings.sync = JSON.stringify(sync);

	saveOptions(settings).then(restoreOptions);
});
<commit_msg>#42 Fix saving bad data before load repo and projects (#43)<commit_after>goog.provide('options');
goog.require('api.Bitbucket');
goog.require('api.Redmine');

/**
 * @return {{sync: string, redmineHost: string, redmineApiKey: string, token: string}}
 */
function readSettings() {
	return {
		sync: document.getElementById('settings').value,
		redmineHost: document.getElementById('settings_redmine_host').value,
		redmineApiKey: document.getElementById('settings_redmine_api_key').value,
		token: document.getElementById('settings_token').value,
		bitbucketOwner: document.getElementById('settings_bitbucket_owner').value
	};
}

/**
 * @param {{
 *      sync: string,
 *      redmineHost: string,
 *      redmineApiKey: string,
 *      token: string
 * }} settings
 * @return {Promise}
 */
function saveOptions(settings) {
	return new Promise(function(resolve, reject) {
		chrome.storage.sync.set({
			'settings': settings
		}, function() {
			// Update status to let user know options were saved.
			var status = document.getElementById('status');
			status.textContent = 'Options saved.';

			resolve();
		});
	});
}

/**
 * @return {Promise}
 */
function restoreOptions() {
	return new Promise(function(resolve, reject) {
		chrome.storage.sync.get(null, function(items) {
			document.getElementById('settings').value = items.settings.sync || '';
			document.getElementById('settings_token').value = items.settings.token || '';
			document.getElementById('settings_redmine_host').value = items.settings.redmineHost || '';
			document.getElementById('settings_redmine_api_key').value = items.settings.redmineApiKey || '';
			document.getElementById('settings_bitbucket_owner').value = 'interfaced';

			resolve();
		});
	});
}

document.addEventListener('DOMContentLoaded', function() {
	restoreOptions().then(function() {
		var _api = {
			bitbucket: new api.Bitbucket,
			redmine: new api.Redmine
		};

		Promise.all([
				_api.redmine.getProjects(),
				_api.bitbucket.getRepositories(document.getElementById('settings_bitbucket_owner').value)
			])
			.then(function(response) {
				var redmineProjects = response[0].projects;
				var bitbucketRepo = response[1];

				var sort = function(a, b) {
					return a.name.localeCompare(b.name);
				};
				redmineProjects.sort(sort).forEach(function(project) {
					var option = document.createElement('option');
					option.setAttribute('value', project.identifier);
					option.innerText = project.name;
					document.getElementById('redmine-projects').appendChild(option);
				});

				bitbucketRepo.sort(sort).forEach(function(repo) {
					var option = document.createElement('option');
					option.setAttribute('value', repo.name);
					option.innerText = repo.name;
					document.getElementById('bitbucket-repo').appendChild(option);
				});

			});
	});
});
document.getElementById('save').addEventListener('click', function() {
	saveOptions(readSettings());
});
document.getElementById('link-button').addEventListener('click', function() {
	var redmineProject = document.getElementById('redmine-projects').value;
	var bitbucketRepo = document.getElementById('bitbucket-repo').value;

	if (!redmineProject || !bitbucketRepo) {
		return;
	}

	var settings = readSettings();
	var sync = settings.sync;

	try {
		sync = JSON.parse(sync);
	} catch (e) {
		sync = {};
	}

	var bitbucketOwner = settings.bitbucketOwner;
	sync[bitbucketOwner] = sync[bitbucketOwner] || {};
	sync[bitbucketOwner][redmineProject] = bitbucketRepo;
	settings.sync = JSON.stringify(sync);

	saveOptions(settings).then(restoreOptions);
});
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var sysPath = require('path');
var fs = require('fs');

var mode = process.argv[2];

var fsExists = fs.exists || sysPath.exists;

var execute = function(pathParts, params, callback) {
  if (callback == null) callback = function() {};
  var path = sysPath.join.apply(null, pathParts);
  var command = 'node ' + path + ' ' + params;
  console.log('Executing', command);
  exec(command, function(error, stdout, stderr) {
    if (error != null) return process.stderr.write(stderr.toString());
    console.log(stdout.toString());
  });
};

if (mode.match(/postinstall|prepublish|postinstall|build|watch/)) {
  fsExists(sysPath.join(__dirname, 'tabcordion.js'), function(exists) {
    if (mode === 'postinstall' && exists) return;
    execute(['node_modules', 'coffee-script', 'bin', 'coffee'], (mode === 'watch' ? '-w ' : '') + '-o . src/');
    execute(['node_modules', 'jade', 'bin', 'jade'], (mode === 'watch' ? '-w ' : '') + '-O . *.jade');
  });
} else if (mode === 'test') {
  execute(['node_modules', 'mocha', 'bin', 'mocha'],
    '--require test/common.js --colors');
}
<commit_msg>Added built tabcordion.js<commit_after>var exec = require('child_process').exec;
var sysPath = require('path');
var fs = require('fs');

var mode = process.argv[2];

var fsExists = fs.exists || sysPath.exists;

var execute = function(pathParts, params, callback) {
  if (callback == null) callback = function() {};
  var path = sysPath.join.apply(null, pathParts);
  var command = 'node ' + path + ' ' + params;
  console.log('Executing', command);
  exec(command, function(error, stdout, stderr) {
    if (error != null) return process.stderr.write(stderr.toString());
    console.log(stdout.toString());
  });
};

if (mode.match(/postinstall|prepublish|postinstall|build|watch/)) {
  fsExists(sysPath.join(__dirname, 'tabcordion.js'), function(exists) {
    if (mode === 'postinstall' && exists) return;
    execute(['node_modules', 'coffee-script', 'bin', 'coffee'], (mode === 'watch' ? '-w ' : '') + '-o . src/');
    // execute(['node_modules', 'jade', 'bin', 'jade'], (mode === 'watch' ? '-w ' : '') + '-O . *.jade');
  });
} else if (mode === 'test') {
  execute(['node_modules', 'mocha', 'bin', 'mocha'],
    '--require test/common.js --colors');
}
<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */

function addKeyword(pkg, regex, keyword) {
  if (pkg.name.match(regex)) {
    if (!pkg.keywords.find(k => k === keyword)) {
      pkg.keywords.push(keyword);
    }
  }
}

export default function (target, template, context, options = {}) {
  target = JSON.parse(target);
  template = JSON.parse(template);

  context.properties.module = target.module;
  context.properties.main = target.main || 'indes.js';

  const deepPropeties = ['scripts', 'devDependencies', 'engines'];

  deepPropeties.forEach(p => {
    if (target[p] === undefined) {
      target[p] = {};
    }
    Object.assign(target[p], template[p]);
  });

  Object.keys(template).forEach(p => {
    if (p !== 'template') {
      if (target[p] === undefined) {
        target[p] = template[p];
      }
    }
  });

  if (target.module === '{{module}}') {
    delete target.module;
  }

  if (target.contributors !== undefined && target.author !== undefined) {
    const m = target.author.match(/(^[^<]+)<([^>]+)>/);
    if (m !== undefined) {
      const name = String(m[1]).replace(/^\s+|\s+$/g, '');
      const email = m[2];

      if (target.contributors.find(c => c.name === name && c.email === email)) {
        delete target.author;
      }
    }
  }

  const [user, repo] = options.targetRepo.split(/\//);

  if (template.config && template.config.keywords) {
    Object.keys(template.config.keywords).forEach(r =>
      addKeyword(target, new RegExp(r), template.config.keywords[r])
    );
  }

  /* TODO move data into template
  addKeyword(target, /^kronos-interceptor.+/, 'kronos-interceptor');
  addKeyword(target, /^kronos-service.+/, 'kronos-service');
  addKeyword(target, /^kronos-step.+/, 'kronos-step');
  addKeyword(target, /^kronos-adapter.+/, 'kronos-step');
  */

  return JSON.stringify(context.expand(target), undefined, 2);
}
<commit_msg>fix: save extra build steps (after &&)<commit_after>/* jslint node: true, esnext: true */

function addKeyword(pkg, regex, keyword) {
  if (pkg.name.match(regex)) {
    if (!pkg.keywords.find(k => k === keyword)) {
      pkg.keywords.push(keyword);
    }
  }
}

export default function (target, template, context, options = {}) {
  target = JSON.parse(target);
  template = JSON.parse(template);

  context.properties.module = target.module;
  context.properties.main = target.main || 'indes.js';

  const deepPropeties = ['scripts', 'devDependencies', 'engines'];

  let extraBuild;

  if (target.scripts && target.scripts.build) {
    const m = target.scripts.build.match(/\&\&\s*(.+)/);
    if (m) {
      extraBuild = m[1];
    }
  }

  deepPropeties.forEach(p => {
    if (target[p] === undefined) {
      target[p] = {};
    }
    Object.assign(target[p], template[p]);
  });

  Object.keys(template).forEach(p => {
    if (p !== 'template') {
      if (target[p] === undefined) {
        target[p] = template[p];
      }
    }
  });

  if (extraBuild) {
    target.scripts.build += ` && ${extraBuild}`;
  }

  if (target.module === '{{module}}') {
    delete target.module;
  }

  if (target.contributors !== undefined && target.author !== undefined) {
    const m = target.author.match(/(^[^<]+)<([^>]+)>/);
    if (m !== undefined) {
      const name = String(m[1]).replace(/^\s+|\s+$/g, '');
      const email = m[2];

      if (target.contributors.find(c => c.name === name && c.email === email)) {
        delete target.author;
      }
    }
  }

  const [user, repo] = options.targetRepo.split(/\//);

  if (template.config && template.config.keywords) {
    Object.keys(template.config.keywords).forEach(r =>
      addKeyword(target, new RegExp(r), template.config.keywords[r])
    );
  }

  /* TODO move data into template
  addKeyword(target, /^kronos-interceptor.+/, 'kronos-interceptor');
  addKeyword(target, /^kronos-service.+/, 'kronos-service');
  addKeyword(target, /^kronos-step.+/, 'kronos-step');
  addKeyword(target, /^kronos-adapter.+/, 'kronos-step');
  */

  return JSON.stringify(context.expand(target), undefined, 2);
}
<|endoftext|>


<commit_before>/**
 * Parses input from a URL query string into an Order.
 * @example
 * // where tip is a percentage
 * parseQueryStringInput('tax=0.30&fee=1.50&tip=15&Gus=5.00');
 * @param {string} queryString - The URL query string
 * @returns {Order} An order parsed from the URL query string
 */
function parseQueryStringInput (queryString) {
  var overheads = ['fee', 'tax']; // tip is a special case, it maps to tipPercent

  var pairs = queryString.split('&');
  var order = Order();

  for (var i = 0; i < pairs.length; i++) {
    var pairValues = pairs[i].split('=');

    pairValues[1] = Number(pairValues[1]);

    if (pairValues[0] === 'tip') {
      order.tipPercent = pairValues[1];
    } else if (overheads.indexOf(pairValues[0]) > -1) {
      order[pairValues[0]] = pairValues[1];
    } else {
      order.addItem(pairValues[0], pairValues[1]);
    }
  }

  return order;
}

/**
 * Parses the confirmation summary from an OrderUp.com order
 * @param {string} orderUpText - The confirmation summary from OrderUp.com
 * @return {Order} An order parsed from the OrderUp.com confirmation summary
 */
function parseOrderUpInput (orderUpText, fee, tax, tipPercent) {
  // TODO: check if the number at the beginning of the line affects the item cost
  // example: 2 Chicken $4.00
  //   should the cost for the person be $4 or $8?

  var order = Order(fee, tax, tipPercent);
  var label = 'Label for:';
  var itemCost = null;
  var array = orderUpText.split('\n');

  for (var i = 0; i < array.length; i++) {
    var line = array[i].trim();
    line = line.replace(/\s+/g, ' '); // replace all whitespace with single space

    if (!itemCost) {
      var dollarIndex = line.indexOf('$');
      if (dollarIndex > -1) {
        itemCost = Number(line.substring(dollarIndex + 1, line.length));
      }
      continue;
    }

    var labelIndex = line.indexOf(label);
    if (labelIndex > -1) {
      var name = line.substring(labelIndex + label.length, line.length);
      order.addItem(name, itemCost);
      itemCost = null;
    }
  }

  return order;
}
<commit_msg>Change tip in URL query string to be non-percentage tip value<commit_after>/**
 * Parses input from a URL query string into an Order.
 * @example
 * parseQueryStringInput('tax=0.30&fee=1.50&tip=1.25&Gus=5.00');
 * @param {string} queryString - The URL query string
 * @returns {Order} An order parsed from the URL query string
 */
function parseQueryStringInput (queryString) {
  var overheads = ['fee', 'tax', 'tip'];

  var pairs = queryString.split('&');
  var order = Order();

  for (var i = 0; i < pairs.length; i++) {
    var pairValues = pairs[i].split('=');

    pairValues[1] = Number(pairValues[1]);

    if (overheads.indexOf(pairValues[0]) > -1) {
      order[pairValues[0]] = pairValues[1];
    } else {
      order.addItem(pairValues[0], pairValues[1]);
    }
  }

  return order;
}

/**
 * Parses the confirmation summary from an OrderUp.com order
 * @param {string} orderUpText - The confirmation summary from OrderUp.com
 * @return {Order} An order parsed from the OrderUp.com confirmation summary
 */
function parseOrderUpInput (orderUpText, fee, tax, tipPercent) {
  // TODO: check if the number at the beginning of the line affects the item cost
  // example: 2 Chicken $4.00
  //   should the cost for the person be $4 or $8?

  var order = Order(fee, tax, tipPercent);
  var label = 'Label for:';
  var itemCost = null;
  var array = orderUpText.split('\n');

  for (var i = 0; i < array.length; i++) {
    var line = array[i].trim();
    line = line.replace(/\s+/g, ' '); // replace all whitespace with single space

    if (!itemCost) {
      var dollarIndex = line.indexOf('$');
      if (dollarIndex > -1) {
        itemCost = Number(line.substring(dollarIndex + 1, line.length));
      }
      continue;
    }

    var labelIndex = line.indexOf(label);
    if (labelIndex > -1) {
      var name = line.substring(labelIndex + label.length, line.length);
      order.addItem(name, itemCost);
      itemCost = null;
    }
  }

  return order;
}
<|endoftext|>


<commit_before>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

module('Item');

test('copyTo(project)', function() {
	var project = paper.project;
	var path = new Path();
	var secondDoc = new Project();
	var copy = path.copyTo(secondDoc);
	equals(function() {
		return secondDoc.activeLayer.children.indexOf(copy) != -1;
	}, true);
	equals(function() {
		return project.activeLayer.children.indexOf(copy) == -1;
	}, true);
	equals(function() {
		return copy != path;
	}, true);
});

test('copyTo(layer)', function() {
	var project = paper.project;
	var path = new Path();

	var layer = new Layer();
	var copy = path.copyTo(layer);
	equals(function() {
		return layer.children.indexOf(copy) != -1;
	}, true);
	equals(function() {
		return project.layers[0].children.indexOf(copy) == -1;
	}, true);
});

test('clone()', function() {
	var project = paper.project;
	var path = new Path();
	var copy = path.clone();
	equals(function() {
		return project.activeLayer.children.length;
	}, 2);
	equals(function() {
		return path != copy;
	}, true);
});

test('addChild(item)', function() {
	var project = paper.project;
	var path = new Path();
	project.activeLayer.addChild(path);
	equals(function() {
		return project.activeLayer.children.length;
	},  1);
});

test('item.parent / item.isChild / item.isParent / item.layer', function() {
	var project = paper.project;
	var secondDoc = new Project();
	var path = new Path();
	project.activeLayer.addChild(path);
	equals(function() {
		return project.activeLayer.children.indexOf(path) != -1;
	}, true);
		equals(function() {
		return path.layer == project.activeLayer;
	}, true);
	secondDoc.activeLayer.addChild(path);
	equals(function() {
		return project.activeLayer.isChild(path);
	}, false);
	equals(function() {
		return path.layer == secondDoc.activeLayer;
	}, true);
	equals(function() {
		return path.isParent(project.activeLayer);
	}, false);
	equals(function() {
		return secondDoc.activeLayer.isChild(path);
	}, true);
	equals(function() {
		return path.isParent(secondDoc.activeLayer);
	}, true);
	equals(function() {
		return project.activeLayer.children.indexOf(path) == -1;
	}, true);
	equals(function() {
		return secondDoc.activeLayer.children.indexOf(path) == 0;
	}, true);
});

test('item.lastChild / item.firstChild', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	equals(function() {
		return project.activeLayer.firstChild == path;
	}, true);
	equals(function() {
		return project.activeLayer.lastChild == secondPath;
	}, true);
});

test('insertChild(0, item)', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	project.activeLayer.insertChild(0, secondPath);
	equals(function() {
		return secondPath.index < path.index;
	}, true);
});

test('insertAbove(item)', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	path.insertAbove(secondPath);
	equals(function() {
		return project.activeLayer.lastChild == path;
	}, true);
});

test('insertBelow(item)', function() {
	var project = paper.project;
	var firstPath = new Path();
	var secondPath = new Path();
	equals(function() {
		return secondPath.index > firstPath.index;
	}, true);
	secondPath.insertBelow(firstPath);
	equals(function() {
		return secondPath.index < firstPath.index;
	}, true);
});

test('isDescendant(item) / isAncestor(item)', function() {
	var project = paper.project;
	var path = new Path();
	equals(function() {
		return path.isDescendant(project.activeLayer);
	}, true);
	equals(function() {
		return project.activeLayer.isDescendant(path);
	}, false);
	equals(function() {
		return path.isAncestor(project.activeLayer);
	}, false);
	equals(function() {
		return project.activeLayer.isAncestor(path);
	}, true);

	// an item can't be its own descendant:
	equals(function() {
		return project.activeLayer.isDescendant(project.activeLayer);
	}, false);
	// an item can't be its own ancestor:
	equals(function() {
		return project.activeLayer.isAncestor(project.activeLayer);
	}, false);
});

test('isGroupedWith', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	var group = new Group([path]);
	var secondGroup = new Group([secondPath]);

	equals(function() {
		return path.isGroupedWith(secondPath);
	}, false);
	secondGroup.addChild(path);
	equals(function() {
		return path.isGroupedWith(secondPath);
	}, true);
	equals(function() {
		return path.isGroupedWith(group);
	}, false);
	equals(function() {
		return path.isDescendant(secondGroup);
	}, true);
	equals(function() {
		return secondGroup.isDescendant(path);
	}, false);
	equals(function() {
		return secondGroup.isDescendant(secondGroup);
	}, false);
	equals(function() {
		return path.isGroupedWith(secondGroup);
	}, false);
	paper.project.activeLayer.addChild(path);
	equals(function() {
		return path.isGroupedWith(secondPath);
	}, false);
	paper.project.activeLayer.addChild(secondPath);
	equals(function() {
		return path.isGroupedWith(secondPath);
	}, false);
});

test('getPreviousSibling() / getNextSibling()', function() {
	var firstPath = new Path();
	var secondPath = new Path();
	equals(function() {
		return firstPath.nextSibling == secondPath;
	}, true);
	equals(function() {
		return secondPath.previousSibling == firstPath;
	}, true);
	equals(function() {
		return secondPath.nextSibling == null;
	}, true);
});

test('reverseChildren()', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	var thirdPath = new Path();
	equals(function() {
		return project.activeLayer.firstChild == path;
	}, true);
	project.activeLayer.reverseChildren();
	equals(function() {
		return project.activeLayer.firstChild == path;
	}, false);
	equals(function() {
		return project.activeLayer.firstChild == thirdPath;
	}, true);
	equals(function() {
		return project.activeLayer.lastChild == path;
	}, true);
});

test('Check item#project when moving items across projects', function() {
	var project = paper.project;
	var doc1 = new Project();
	var path = new Path();
	var group = new Group();
	group.addChild(new Path());

	equals(function() {
		return path.project == doc1;
	}, true);
	var doc2 = new Project();
	doc2.activeLayer.addChild(path);
	equals(function() {
		return path.project == doc2;
	}, true);

	doc2.activeLayer.addChild(group);
	equals(function() {
		return group.children[0].project == doc2;
	}, true);
});

test('group.selected', function() {
	var path = new Path([0, 0]);
	var path2 = new Path([0, 0]);
	var group = new Group([path, path2]);
	path.selected = true;
	equals(function() {
		return group.selected;
	}, true);

	path.selected = false;
	equals(function() {
		return group.selected;
	}, false);

	group.selected = true;
	equals(function() {
		return path.selected;
	}, true);
	equals(function() {
		return path2.selected;
	}, true);

	group.selected = false;
	equals(function() {
		return path.selected;
	}, false);
	equals(function() {
		return path2.selected;
	}, false);
});

test('Check parent children object for named item', function() {
	var path = new Path();
	path.name = 'test';
	equals(function() {
		return paper.project.activeLayer.children['test'] == path;
	}, true);

	var path2 = new Path();
	path2.name = 'test';

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);

	path2.remove();

	equals(function() {
		return paper.project.activeLayer.children['test'] == path;
	}, true);

	path.remove();

	equals(function() {
		return !paper.project.activeLayer.children['test'];
	}, true);
});

test('Named child access 1', function() {
	var path = new Path();
	path.name = 'test';

	var path2 = new Path();
	path2.name = 'test';

	path.remove();

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);
});

test('Named child access 2', function() {
	var path = new Path();
	path.name = 'test';

	var path2 = new Path();
	path2.name = 'test';

	path.remove();

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);

	equals(function() {
		return paper.project.activeLayer._namedChildren['test'].length == 1;
	}, true);

	path2.remove();

	equals(function() {
		return !paper.project.activeLayer._namedChildren['test'];
	}, true);

	equals(function() {
		return paper.project.activeLayer.children['test'] === undefined;
	}, true);
});

test('Named child access 3', function() {
	var path = new Path();
	path.name = 'test';

	var path2 = new Path();
	path2.name = 'test';

	var group = new Group();

	group.addChild(path2);

	equals(function() {
		return paper.project.activeLayer.children['test'] == path;
	}, true);

	// TODO: Tests should not access internal properties
	equals(function() {
		return paper.project.activeLayer._namedChildren['test'].length;
	}, 1);

	equals(function() {
		return group.children['test'] == path2;
	}, true);

	equals(function() {
		return group._namedChildren['test'].length == 1;
	}, true);

	equals(function() {
		return paper.project.activeLayer._namedChildren['test'][0] == path;
	}, true);

	paper.project.activeLayer.appendTop(path2);

	equals(function() {
		return group.children['test'] == null;
	}, true);

	equals(function() {
		return group._namedChildren['test'] === undefined;
	}, true);

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);

	equals(function() {
		return paper.project.activeLayer._namedChildren['test'].length;
	}, 2);
});

test('Setting name of child back to null', function() {
	var path = new Path();
	path.name = 'test';

	var path2 = new Path();
	path2.name = 'test';

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);

	path2.name = null;

	equals(function() {
		return paper.project.activeLayer.children['test'] == path;
	}, true);

	path.name = null;

	equals(function() {
		return paper.project.activeLayer.children['test'] === undefined;
	}, true);
});

test('Renaming item', function() {
	var path = new Path();
	path.name = 'test';

	path.name = 'test2';

	equals(function() {
		return paper.project.activeLayer.children['test'] === undefined;
	}, true);

	equals(function() {
		return paper.project.activeLayer.children['test2'] == path;
	}, true);
});

test('Changing item#position.x', function() {
	var path = new Path.Circle(new Point(50, 50), 50);
	path.position.x += 5;
	equals(path.position.toString(), '{ x: 55, y: 50 }', 'path.position.x += 5');
});

test('Naming a removed item', function() {
	var path = new Path();
	path.remove();
	path.name = 'test';
});

test('Naming a layer', function() {
	var layer = new Layer();
	layer.name = 'test';
});

test('Cloning a linked size', function() {
	var path = new Path([40, 75], [140, 75]);
	var error = null;
	try {
		var cloneSize = path.bounds.size.clone();
	} catch (e) {
		error = e;
	}
	var description = 'Cloning a linked size should not throw an error';
	if (error)
		description += ': ' + error;
	equals(error == null, true, description);
});<commit_msg>Add failing test when inserting multiple children into the same parent.<commit_after>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

module('Item');

test('copyTo(project)', function() {
	var project = paper.project;
	var path = new Path();
	var secondDoc = new Project();
	var copy = path.copyTo(secondDoc);
	equals(function() {
		return secondDoc.activeLayer.children.indexOf(copy) != -1;
	}, true);
	equals(function() {
		return project.activeLayer.children.indexOf(copy) == -1;
	}, true);
	equals(function() {
		return copy != path;
	}, true);
});

test('copyTo(layer)', function() {
	var project = paper.project;
	var path = new Path();

	var layer = new Layer();
	var copy = path.copyTo(layer);
	equals(function() {
		return layer.children.indexOf(copy) != -1;
	}, true);
	equals(function() {
		return project.layers[0].children.indexOf(copy) == -1;
	}, true);
});

test('clone()', function() {
	var project = paper.project;
	var path = new Path();
	var copy = path.clone();
	equals(function() {
		return project.activeLayer.children.length;
	}, 2);
	equals(function() {
		return path != copy;
	}, true);
});

test('addChild(item)', function() {
	var project = paper.project;
	var path = new Path();
	project.activeLayer.addChild(path);
	equals(function() {
		return project.activeLayer.children.length;
	},  1);
});

test('item.parent / item.isChild / item.isParent / item.layer', function() {
	var project = paper.project;
	var secondDoc = new Project();
	var path = new Path();
	project.activeLayer.addChild(path);
	equals(function() {
		return project.activeLayer.children.indexOf(path) != -1;
	}, true);
		equals(function() {
		return path.layer == project.activeLayer;
	}, true);
	secondDoc.activeLayer.addChild(path);
	equals(function() {
		return project.activeLayer.isChild(path);
	}, false);
	equals(function() {
		return path.layer == secondDoc.activeLayer;
	}, true);
	equals(function() {
		return path.isParent(project.activeLayer);
	}, false);
	equals(function() {
		return secondDoc.activeLayer.isChild(path);
	}, true);
	equals(function() {
		return path.isParent(secondDoc.activeLayer);
	}, true);
	equals(function() {
		return project.activeLayer.children.indexOf(path) == -1;
	}, true);
	equals(function() {
		return secondDoc.activeLayer.children.indexOf(path) == 0;
	}, true);
});

test('item.lastChild / item.firstChild', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	equals(function() {
		return project.activeLayer.firstChild == path;
	}, true);
	equals(function() {
		return project.activeLayer.lastChild == secondPath;
	}, true);
});

test('insertChild(0, item)', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	project.activeLayer.insertChild(0, secondPath);
	equals(function() {
		return secondPath.index < path.index;
	}, true);
});

test('insertAbove(item)', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	path.insertAbove(secondPath);
	equals(function() {
		return project.activeLayer.lastChild == path;
	}, true);
});

test('insertBelow(item)', function() {
	var project = paper.project;
	var firstPath = new Path();
	var secondPath = new Path();
	equals(function() {
		return secondPath.index > firstPath.index;
	}, true);
	secondPath.insertBelow(firstPath);
	equals(function() {
		return secondPath.index < firstPath.index;
	}, true);
});

test('isDescendant(item) / isAncestor(item)', function() {
	var project = paper.project;
	var path = new Path();
	equals(function() {
		return path.isDescendant(project.activeLayer);
	}, true);
	equals(function() {
		return project.activeLayer.isDescendant(path);
	}, false);
	equals(function() {
		return path.isAncestor(project.activeLayer);
	}, false);
	equals(function() {
		return project.activeLayer.isAncestor(path);
	}, true);

	// an item can't be its own descendant:
	equals(function() {
		return project.activeLayer.isDescendant(project.activeLayer);
	}, false);
	// an item can't be its own ancestor:
	equals(function() {
		return project.activeLayer.isAncestor(project.activeLayer);
	}, false);
});

test('addChildren(items)', function() {
	var project = paper.project;
	var path1 = new Path(),
		path2 = new Path(),
		path3 = new Path(),
		group = new Group([path1, path2, path3]);

	function check(i1, i2, i3) {
		equals(function() {
			return group.children.length;
		}, 3);
		equals(function() {
			return path1.index;
		}, i1);
		equals(function() {
			return path2.index;
		}, i2);
		equals(function() {
			return path3.index;
		}, i3);
	}
	check(0, 1, 2);
	group.addChild(path1);
	check(2, 0, 1);
	group.addChild(path2);
	check(1, 2, 0);
	group.addChildren([path1, path2, path3]);
	check(0, 1, 2);
});

test('isGroupedWith', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	var group = new Group([path]);
	var secondGroup = new Group([secondPath]);

	equals(function() {
		return path.isGroupedWith(secondPath);
	}, false);
	secondGroup.addChild(path);
	equals(function() {
		return path.isGroupedWith(secondPath);
	}, true);
	equals(function() {
		return path.isGroupedWith(group);
	}, false);
	equals(function() {
		return path.isDescendant(secondGroup);
	}, true);
	equals(function() {
		return secondGroup.isDescendant(path);
	}, false);
	equals(function() {
		return secondGroup.isDescendant(secondGroup);
	}, false);
	equals(function() {
		return path.isGroupedWith(secondGroup);
	}, false);
	paper.project.activeLayer.addChild(path);
	equals(function() {
		return path.isGroupedWith(secondPath);
	}, false);
	paper.project.activeLayer.addChild(secondPath);
	equals(function() {
		return path.isGroupedWith(secondPath);
	}, false);
});

test('getPreviousSibling() / getNextSibling()', function() {
	var firstPath = new Path();
	var secondPath = new Path();
	equals(function() {
		return firstPath.nextSibling == secondPath;
	}, true);
	equals(function() {
		return secondPath.previousSibling == firstPath;
	}, true);
	equals(function() {
		return secondPath.nextSibling == null;
	}, true);
});

test('reverseChildren()', function() {
	var project = paper.project;
	var path = new Path();
	var secondPath = new Path();
	var thirdPath = new Path();
	equals(function() {
		return project.activeLayer.firstChild == path;
	}, true);
	project.activeLayer.reverseChildren();
	equals(function() {
		return project.activeLayer.firstChild == path;
	}, false);
	equals(function() {
		return project.activeLayer.firstChild == thirdPath;
	}, true);
	equals(function() {
		return project.activeLayer.lastChild == path;
	}, true);
});

test('Check item#project when moving items across projects', function() {
	var project = paper.project;
	var doc1 = new Project();
	var path = new Path();
	var group = new Group();
	group.addChild(new Path());

	equals(function() {
		return path.project == doc1;
	}, true);
	var doc2 = new Project();
	doc2.activeLayer.addChild(path);
	equals(function() {
		return path.project == doc2;
	}, true);

	doc2.activeLayer.addChild(group);
	equals(function() {
		return group.children[0].project == doc2;
	}, true);
});

test('group.selected', function() {
	var path = new Path([0, 0]);
	var path2 = new Path([0, 0]);
	var group = new Group([path, path2]);
	path.selected = true;
	equals(function() {
		return group.selected;
	}, true);

	path.selected = false;
	equals(function() {
		return group.selected;
	}, false);

	group.selected = true;
	equals(function() {
		return path.selected;
	}, true);
	equals(function() {
		return path2.selected;
	}, true);

	group.selected = false;
	equals(function() {
		return path.selected;
	}, false);
	equals(function() {
		return path2.selected;
	}, false);
});

test('Check parent children object for named item', function() {
	var path = new Path();
	path.name = 'test';
	equals(function() {
		return paper.project.activeLayer.children['test'] == path;
	}, true);

	var path2 = new Path();
	path2.name = 'test';

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);

	path2.remove();

	equals(function() {
		return paper.project.activeLayer.children['test'] == path;
	}, true);

	path.remove();

	equals(function() {
		return !paper.project.activeLayer.children['test'];
	}, true);
});

test('Named child access 1', function() {
	var path = new Path();
	path.name = 'test';

	var path2 = new Path();
	path2.name = 'test';

	path.remove();

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);
});

test('Named child access 2', function() {
	var path = new Path();
	path.name = 'test';

	var path2 = new Path();
	path2.name = 'test';

	path.remove();

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);

	equals(function() {
		return paper.project.activeLayer._namedChildren['test'].length == 1;
	}, true);

	path2.remove();

	equals(function() {
		return !paper.project.activeLayer._namedChildren['test'];
	}, true);

	equals(function() {
		return paper.project.activeLayer.children['test'] === undefined;
	}, true);
});

test('Named child access 3', function() {
	var path = new Path();
	path.name = 'test';

	var path2 = new Path();
	path2.name = 'test';

	var group = new Group();

	group.addChild(path2);

	equals(function() {
		return paper.project.activeLayer.children['test'] == path;
	}, true);

	// TODO: Tests should not access internal properties
	equals(function() {
		return paper.project.activeLayer._namedChildren['test'].length;
	}, 1);

	equals(function() {
		return group.children['test'] == path2;
	}, true);

	equals(function() {
		return group._namedChildren['test'].length == 1;
	}, true);

	equals(function() {
		return paper.project.activeLayer._namedChildren['test'][0] == path;
	}, true);

	paper.project.activeLayer.appendTop(path2);

	equals(function() {
		return group.children['test'] == null;
	}, true);

	equals(function() {
		return group._namedChildren['test'] === undefined;
	}, true);

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);

	equals(function() {
		return paper.project.activeLayer._namedChildren['test'].length;
	}, 2);
});

test('Setting name of child back to null', function() {
	var path = new Path();
	path.name = 'test';

	var path2 = new Path();
	path2.name = 'test';

	equals(function() {
		return paper.project.activeLayer.children['test'] == path2;
	}, true);

	path2.name = null;

	equals(function() {
		return paper.project.activeLayer.children['test'] == path;
	}, true);

	path.name = null;

	equals(function() {
		return paper.project.activeLayer.children['test'] === undefined;
	}, true);
});

test('Renaming item', function() {
	var path = new Path();
	path.name = 'test';

	path.name = 'test2';

	equals(function() {
		return paper.project.activeLayer.children['test'] === undefined;
	}, true);

	equals(function() {
		return paper.project.activeLayer.children['test2'] == path;
	}, true);
});

test('Changing item#position.x', function() {
	var path = new Path.Circle(new Point(50, 50), 50);
	path.position.x += 5;
	equals(path.position.toString(), '{ x: 55, y: 50 }', 'path.position.x += 5');
});

test('Naming a removed item', function() {
	var path = new Path();
	path.remove();
	path.name = 'test';
});

test('Naming a layer', function() {
	var layer = new Layer();
	layer.name = 'test';
});

test('Cloning a linked size', function() {
	var path = new Path([40, 75], [140, 75]);
	var error = null;
	try {
		var cloneSize = path.bounds.size.clone();
	} catch (e) {
		error = e;
	}
	var description = 'Cloning a linked size should not throw an error';
	if (error)
		description += ': ' + error;
	equals(error == null, true, description);
});<|endoftext|>