<commit_before>/**
 * Date mock object that works as if current time is fixed at
 * Sun Oct 26 2014 23:12:54 GMT+0100 (CET)
 */

'use strict';

define([], function() {

    var realDate;
    function mockDate(val) {
        if (!val) {
            this.date = new realDate(1413101574805);
        } else {
            this.date = new realDate(val);
        }
    }
    mockDate.hook = function() {
        if (realDate) {
            throw Error('Hook date called two times!');
        }
        realDate = window.Date;
        window.Date = mockDate;
    }
    mockDate.restore = function() {
        window.Date = realDate;
        realDate = undefined;
    }
    mockDate.prototype.setDate = function(val) {
        return this.date.setDate(val);
    }
    mockDate.prototype.toLocaleDateString = function() {
        return this.date.toLocaleDateString();
    }
    mockDate.prototype.valueOf = function() {
        return this.date.valueOf();
    }
    mockDate.prototype.getDate = function() {
        return this.date.getDate();
    }
    mockDate.prototype.getDay = function() {
        return this.date.getDay();
    }
    mockDate.prototype.getMonth = function() {
        return this.date.getMonth();
    }
    mockDate.prototype.getFullYear = function() {
        return this.date.getFullYear();
    }
    mockDate.prototype.getHours = function() {
        return this.date.getHours();
    }
    mockDate.prototype.getMinutes = function() {
        return this.date.getMinutes();
    }
    mockDate.prototype.getTime = function() {
        return this.date.getTime();
    }

    return mockDate;

});
<commit_msg>Fix comment about fixed date in the mock.<commit_after>/**
 * Date mock object that works as if current time is fixed at
 * Sun Oct 12 2014 10:12:54 GMT+0200 (CEST)
 */

'use strict';

define([], function() {

    var realDate;
    function mockDate(val) {
        if (!val) {
            this.date = new realDate(1413101574805);
        } else {
            this.date = new realDate(val);
        }
    }
    mockDate.hook = function() {
        if (realDate) {
            throw Error('Hook date called two times!');
        }
        realDate = window.Date;
        window.Date = mockDate;
    }
    mockDate.restore = function() {
        window.Date = realDate;
        realDate = undefined;
    }
    mockDate.prototype.setDate = function(val) {
        return this.date.setDate(val);
    }
    mockDate.prototype.toLocaleDateString = function() {
        return this.date.toLocaleDateString();
    }
    mockDate.prototype.valueOf = function() {
        return this.date.valueOf();
    }
    mockDate.prototype.getDate = function() {
        return this.date.getDate();
    }
    mockDate.prototype.getDay = function() {
        return this.date.getDay();
    }
    mockDate.prototype.getMonth = function() {
        return this.date.getMonth();
    }
    mockDate.prototype.getFullYear = function() {
        return this.date.getFullYear();
    }
    mockDate.prototype.getHours = function() {
        return this.date.getHours();
    }
    mockDate.prototype.getMinutes = function() {
        return this.date.getMinutes();
    }
    mockDate.prototype.getTime = function() {
        return this.date.getTime();
    }

    return mockDate;

});
<|endoftext|>


<commit_before>/**
 * Allow non-camelcase naming:
 */
/*jshint camelcase:false*/

var facade = require('..');

describe('Octopress', function(){
  var categoryDir = '/categories';
  var filters = facade('octopress', {categoryDir: categoryDir});

  describe('#category_link()', function(){
    it('should create link from a category', function(){
      filters
        .category_link('rdfa')
        .should.equal(
          'rdfa'
        );
    });

    it('should create link and URL encode the category', function(){
      filters
        .category_link('semantic web')
        .should.equal(
          'semantic web'
        );
    });
  });

  describe('#category_links()', function(){
    it('should create links from one category', function(){
      filters
        .category_links(['rdfa'])
        .should.equal(
          'rdfa'
        );
    });

    it('should create links from a list of categories', function(){
      filters
        .category_links(['rdfa', 'semantic web'])
        .should.equal(
          'rdfa, ' +
          'semantic web'
        );
    });

    it('should sort the list of categories before creating links', function(){
      filters
        .category_links(['xforms', 'c++'])
        .should.equal(
          'c++, ' +
          'xforms'
        );
    });

    it('should cope with non-arrays', function(){
      filters
        .category_links('rdfa')
        .should.equal(
          'rdfa'
        );

      filters
        .category_links(123)
        .should.equal(
          '123'
        );

      filters
        .category_links(true)
        .should.equal(
          'true'
        );
    });

    it('missing array should be empty string', function(){
      filters
        .category_links(null)
        .should.equal('');
    });
  });

  describe('#condense_spaces()', function(){
    it('should remove duplicate spaces', function(){
      filters
        .condense_spaces('   too   many  spaces      ')
        .should.equal(' too many spaces ');
    });

    it('should remove control characters', function(){
      filters
        .condense_spaces('   too   many \tspaces   \r\n   ')
        .should.equal(' too many spaces ');
    });

    it('should not fail on null', function(){
      filters
        .condense_spaces(null)
        .should.equal('null');
    });

    it('should cope with numbers', function(){
      filters
        .condense_spaces(123)
        .should.equal('123');
    });

    it('should cope with booleans', function(){
      filters
        .condense_spaces(true)
        .should.equal('true');
    });
  });

  describe('#expand_urls()', function(){
    it('should map relative URL to an absolute one with no site', function(){
      filters
        .expand_urls('Article C')
        .should.equal('Article C');
    });

    it('should not map URL with no root', function(){
      filters
        .expand_urls('Article C')
        .should.equal('Article C');
    });

    it('should map relative URL to an absolute one with site', function(){
      filters
        .expand_urls(
          'Article C'
        , 'http://markbirbeck.com'
        )
        .should.equal(
          'Article C'
        );
    });

    it('should not get fooled by URLs outside markup', function(){
      filters
        .expand_urls(
          'a link to "/a/b/c"', 'http://markbirbeck.com'
        )
        .should.equal(
          'a link to "/a/b/c"'
        );
    });

    it('should map multiple URLs', function(){
      filters
        .expand_urls(
          'Article CArticle D'
        , 'http://markbirbeck.com'
        )
        .should.equal(
          'Article C'
        + 'Article D'
        );
    });

    it('should return everything if no link is present', function(){
      filters
        .expand_urls(
          '
This is content from a different place.
'
        )
        .should.equal(
          '
This is content from a different place.
'
        );
    });

    it('should cope with non-strings', function(){
      filters
        .expand_urls(123)
        .should.equal('123');

      filters
        .expand_urls(true)
        .should.equal('true');

      filters
        .expand_urls(null)
        .should.equal('null');
    });
  });

  describe('#raw_content()', function(){
    it('should extract raw content from a template with footer', function(){
      filters
        .raw_content(
          '
this is an article with a footer
'
        )
        .should.equal(
          'this is an article with a footer'
        );
    });

    it('should extract raw content from a template with no footer', function(){
      filters
        .raw_content(
          '
this is an article without a footer

'
        )
        .should.equal(
          'this is an article without a footer'
        );
    });

    it('should return everything if the template is not present', function(){
      filters
        .raw_content(
          '
This is content from a different place.
'
        )
        .should.equal(
          '
This is content from a different place.
'
        );
    });

    it('should cope with non-strings', function(){
      filters
        .raw_content(123)
        .should.equal('123');

      filters
        .raw_content(true)
        .should.equal('true');

      filters
        .raw_content(null)
        .should.equal('null');
    });
  });

  describe('#shorthand_url()', function(){
    it('should get path from HTTP URL', function(){
      filters
        .shorthand_url('http://a/b/c/')
        .should.equal('a/b/c/');
    });

    it('should get path from HTTPS URL', function(){
      filters
        .shorthand_url('https://a/b/c/')
        .should.equal('a/b/c/');
    });

    it('should not get path from FTP URL', function(){
      filters
        .shorthand_url('ftp://a/b/c')
        .should.equal('ftp://a/b/c');
    });

    it('should leave other strings intact', function(){
      filters
        .shorthand_url('this is a string')
        .should.equal('this is a string');
    });

    it('should not fail on null', function(){
      filters
        .shorthand_url(null)
        .should.equal('null');
    });

    it('should cope with numbers', function(){
      filters
        .shorthand_url(123)
        .should.equal('123');
    });

    it('should cope with booleans', function(){
      filters
        .shorthand_url(true)
        .should.equal('true');
    });
  });

  describe('#strip_slash()', function(){
    it('should remove trailing slash from path', function(){
      filters
        .strip_slash('a/b/c/')
        .should.equal('a/b/c');
    });

    it('should remove trailing slash from root', function(){
      filters
        .strip_slash('/')
        .should.equal('');
    });

    it('should leave other paths intact', function(){
      filters
        .strip_slash('d/e/f')
        .should.equal('d/e/f');
    });

    it('should not fail on null', function(){
      filters
        .strip_slash(null)
        .should.equal('null');
    });

    it('should cope with numbers', function(){
      filters
        .strip_slash(123)
        .should.equal('123');
    });

    it('should cope with booleans', function(){
      filters
        .strip_slash(true)
        .should.equal('true');
    });
  });

  describe('#titlecase()', function(){
    it('should turn all words to titlecase', function(){
      filters
        .titlecase('A Film Title')
        .should.equal('A Film Title');
    });

    it('should ignore small words', function(){
      filters
        .titlecase('This is a film title')
        .should.equal('This Is a Film Title');
    });

    it('should not fail on null', function(){
      filters
        .titlecase(null)
        .should.equal('Null');
    });

    it('should cope with numbers', function(){
      filters
        .titlecase(123)
        .should.equal('123');
    });

    it('should cope with booleans', function(){
      filters
        .titlecase(true)
        .should.equal('True');
    });
  });
});
<commit_msg>chg: minor fix to the Octopress#titlecase() test.<commit_after>/**
 * Allow non-camelcase naming:
 */
/*jshint camelcase:false*/

var facade = require('..');

describe('Octopress', function(){
  var categoryDir = '/categories';
  var filters = facade('octopress', {categoryDir: categoryDir});

  describe('#category_link()', function(){
    it('should create link from a category', function(){
      filters
        .category_link('rdfa')
        .should.equal(
          'rdfa'
        );
    });

    it('should create link and URL encode the category', function(){
      filters
        .category_link('semantic web')
        .should.equal(
          'semantic web'
        );
    });
  });

  describe('#category_links()', function(){
    it('should create links from one category', function(){
      filters
        .category_links(['rdfa'])
        .should.equal(
          'rdfa'
        );
    });

    it('should create links from a list of categories', function(){
      filters
        .category_links(['rdfa', 'semantic web'])
        .should.equal(
          'rdfa, ' +
          'semantic web'
        );
    });

    it('should sort the list of categories before creating links', function(){
      filters
        .category_links(['xforms', 'c++'])
        .should.equal(
          'c++, ' +
          'xforms'
        );
    });

    it('should cope with non-arrays', function(){
      filters
        .category_links('rdfa')
        .should.equal(
          'rdfa'
        );

      filters
        .category_links(123)
        .should.equal(
          '123'
        );

      filters
        .category_links(true)
        .should.equal(
          'true'
        );
    });

    it('missing array should be empty string', function(){
      filters
        .category_links(null)
        .should.equal('');
    });
  });

  describe('#condense_spaces()', function(){
    it('should remove duplicate spaces', function(){
      filters
        .condense_spaces('   too   many  spaces      ')
        .should.equal(' too many spaces ');
    });

    it('should remove control characters', function(){
      filters
        .condense_spaces('   too   many \tspaces   \r\n   ')
        .should.equal(' too many spaces ');
    });

    it('should not fail on null', function(){
      filters
        .condense_spaces(null)
        .should.equal('null');
    });

    it('should cope with numbers', function(){
      filters
        .condense_spaces(123)
        .should.equal('123');
    });

    it('should cope with booleans', function(){
      filters
        .condense_spaces(true)
        .should.equal('true');
    });
  });

  describe('#expand_urls()', function(){
    it('should map relative URL to an absolute one with no site', function(){
      filters
        .expand_urls('Article C')
        .should.equal('Article C');
    });

    it('should not map URL with no root', function(){
      filters
        .expand_urls('Article C')
        .should.equal('Article C');
    });

    it('should map relative URL to an absolute one with site', function(){
      filters
        .expand_urls(
          'Article C'
        , 'http://markbirbeck.com'
        )
        .should.equal(
          'Article C'
        );
    });

    it('should not get fooled by URLs outside markup', function(){
      filters
        .expand_urls(
          'a link to "/a/b/c"', 'http://markbirbeck.com'
        )
        .should.equal(
          'a link to "/a/b/c"'
        );
    });

    it('should map multiple URLs', function(){
      filters
        .expand_urls(
          'Article CArticle D'
        , 'http://markbirbeck.com'
        )
        .should.equal(
          'Article C'
        + 'Article D'
        );
    });

    it('should return everything if no link is present', function(){
      filters
        .expand_urls(
          '
This is content from a different place.
'
        )
        .should.equal(
          '
This is content from a different place.
'
        );
    });

    it('should cope with non-strings', function(){
      filters
        .expand_urls(123)
        .should.equal('123');

      filters
        .expand_urls(true)
        .should.equal('true');

      filters
        .expand_urls(null)
        .should.equal('null');
    });
  });

  describe('#raw_content()', function(){
    it('should extract raw content from a template with footer', function(){
      filters
        .raw_content(
          '
this is an article with a footer
'
        )
        .should.equal(
          'this is an article with a footer'
        );
    });

    it('should extract raw content from a template with no footer', function(){
      filters
        .raw_content(
          '
this is an article without a footer

'
        )
        .should.equal(
          'this is an article without a footer'
        );
    });

    it('should return everything if the template is not present', function(){
      filters
        .raw_content(
          '
This is content from a different place.
'
        )
        .should.equal(
          '
This is content from a different place.
'
        );
    });

    it('should cope with non-strings', function(){
      filters
        .raw_content(123)
        .should.equal('123');

      filters
        .raw_content(true)
        .should.equal('true');

      filters
        .raw_content(null)
        .should.equal('null');
    });
  });

  describe('#shorthand_url()', function(){
    it('should get path from HTTP URL', function(){
      filters
        .shorthand_url('http://a/b/c/')
        .should.equal('a/b/c/');
    });

    it('should get path from HTTPS URL', function(){
      filters
        .shorthand_url('https://a/b/c/')
        .should.equal('a/b/c/');
    });

    it('should not get path from FTP URL', function(){
      filters
        .shorthand_url('ftp://a/b/c')
        .should.equal('ftp://a/b/c');
    });

    it('should leave other strings intact', function(){
      filters
        .shorthand_url('this is a string')
        .should.equal('this is a string');
    });

    it('should not fail on null', function(){
      filters
        .shorthand_url(null)
        .should.equal('null');
    });

    it('should cope with numbers', function(){
      filters
        .shorthand_url(123)
        .should.equal('123');
    });

    it('should cope with booleans', function(){
      filters
        .shorthand_url(true)
        .should.equal('true');
    });
  });

  describe('#strip_slash()', function(){
    it('should remove trailing slash from path', function(){
      filters
        .strip_slash('a/b/c/')
        .should.equal('a/b/c');
    });

    it('should remove trailing slash from root', function(){
      filters
        .strip_slash('/')
        .should.equal('');
    });

    it('should leave other paths intact', function(){
      filters
        .strip_slash('d/e/f')
        .should.equal('d/e/f');
    });

    it('should not fail on null', function(){
      filters
        .strip_slash(null)
        .should.equal('null');
    });

    it('should cope with numbers', function(){
      filters
        .strip_slash(123)
        .should.equal('123');
    });

    it('should cope with booleans', function(){
      filters
        .strip_slash(true)
        .should.equal('true');
    });
  });

  describe('#titlecase()', function(){
    it('should turn all words to titlecase', function(){
      filters
        .titlecase('a film title')
        .should.equal('A Film Title');
    });

    it('should ignore small words', function(){
      filters
        .titlecase('This is a film title')
        .should.equal('This Is a Film Title');
    });

    it('should not fail on null', function(){
      filters
        .titlecase(null)
        .should.equal('Null');
    });

    it('should cope with numbers', function(){
      filters
        .titlecase(123)
        .should.equal('123');
    });

    it('should cope with booleans', function(){
      filters
        .titlecase(true)
        .should.equal('True');
    });
  });
});
<|endoftext|>


<commit_before>import { relativeToFile, join, parseQueryString, buildQueryString } from '../src/index';

describe('relativeToFile', () => {
  it('can make a dot path relative to a simple file', () => {
    var file = 'some/file.html';
    var path = './other/module';

    expect(relativeToFile(path, file)).toBe('some/other/module');
  });

  it('can make a dot path relative to an absolute file', () => {
    var file = 'http://durandal.io/some/file.html';
    var path = './other/module';

    expect(relativeToFile(path, file)).toBe('http://durandal.io/some/other/module');
  });

  it('can make a double dot path relative to an absolute file', () => {
    var file = 'http://durandal.io/some/file.html';
    var path = '../other/module';

    expect(relativeToFile(path, file)).toBe('http://durandal.io/other/module');
  });

  it('returns path if null file provided', () => {
    var file = null;
    var path = 'module';

    expect(relativeToFile(path, file)).toBe('module');
  });

  it('returns path if empty file provided', () => {
    var file = '';
    var path = 'module';

    expect(relativeToFile(path, file)).toBe('module');
  });
});

describe('join', () => {
  it('can combine two simple paths', () => {
    var path1 = 'one';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('one/two');
  });

  it('can combine an absolute path and a simple path', () => {
    var path1 = '/one';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('/one/two');
  });

  it('can combine an absolute path and a simple path with slash', () => {
    var path1 = '/one';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('/one/two');
  });

  it('can combine a single slash and a simple path', () => {
    var path1 = '/';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('/two');
  });

  it('can combine a single slash and a simple path with slash', () => {
    var path1 = '/';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('/two');
  });

  it('can combine an absolute path with protocol and a simple path', () => {
    var path1 = 'http://durandal.io';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('http://durandal.io/two');
  });

  it('can combine an absolute path with protocol and a simple path with slash', () => {
    var path1 = 'http://durandal.io';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('http://durandal.io/two');
  });

  it('can combine an absolute path and a simple path with a dot', () => {
    var path1 = 'http://durandal.io';
    var path2 = './two';

    expect(join(path1, path2)).toBe('http://durandal.io/two');
  });

  it('can combine a simple path and a relative path', () => {
    var path1 = 'one';
    var path2 = '../two';

    expect(join(path1, path2)).toBe('two');
  });

  it('can combine an absolute path and a relative path', () => {
    var path1 = 'http://durandal.io/somewhere';
    var path2 = '../two';

    expect(join(path1, path2)).toBe('http://durandal.io/two');
  });

  it('can combine a protocol independent path and a simple path', () => {
    var path1 = '//durandal.io';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('//durandal.io/two');
  });

  it('can combine a protocol independent path and a simple path with slash', () => {
    var path1 = '//durandal.io';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('//durandal.io/two');
  });

  it('can combine a protocol independent path and a simple path with a dot', () => {
    var path1 = '//durandal.io';
    var path2 = './two';

    expect(join(path1, path2)).toBe('//durandal.io/two');
  });

  it('can combine a protocol independent path and a relative path', () => {
    var path1 = '//durandal.io/somewhere';
    var path2 = '../two';

    expect(join(path1, path2)).toBe('//durandal.io/two');
  });

  it('can combine a complex path and a relative path', () => {
    var path1 = 'one/three';
    var path2 = '../two';

    expect(join(path1, path2)).toBe('one/two');
  });

  it('returns path2 if path1 null', () => {
    var path1 = null;
    var path2 = 'two';

    expect(join(path1, path2)).toBe('two');
  });

  it('returns path2 if path1 empty', () => {
    var path1 = '';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('two');
  });

  it('returns path1 if path2 null', () => {
    var path1 = 'one';
    var path2 = null;

    expect(join(path1, path2)).toBe('one');
  });

  it('returns path1 if path2 empty', () => {
    var path1 = 'one';
    var path2 = '';

    expect(join(path1, path2)).toBe('one');
  });

  it('should respect a trailing slash', () => {
    var path1 = 'one/';
    var path2 = 'two/';

    expect(join(path1, path2)).toBe('one/two/');
  });

  it('should respect file:/// protocol with three slashes (empty host)', () => {
    var path1 = 'file:///one';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('file:///one/two');
  });

  it('should respect file:// protocol with two slashes (host given)', () => {
    var path1 = 'file://localhost:8080';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('file://localhost:8080/two');
  });

  it('should allow scheme-relative URL that uses colons in the path', () => {
    var path1 = '//localhost/one:/';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('//localhost/one:/two');
  });

  it('should not add more than two leading slashes to http:// protocol', () => {
    var path1 = 'http:///';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('http://two');
  });
});

describe('query strings', () => {
  it('should build query strings', () => {
    let gen = buildQueryString;

    expect(gen()).toBe('');
    expect(gen(null)).toBe('');
    expect(gen({})).toBe('');
    expect(gen({ a: null })).toBe('');

    expect(gen({ '': 'a' })).toBe('=a');
    expect(gen({ a: 'b' })).toBe('a=b');
    expect(gen({ a: 'b', c: 'd' })).toBe('a=b&c=d');
    expect(gen({ a: 'b', c: null })).toBe('a=b');

    expect(gen({ a: ['b', 'c'] })).toBe('a%5B%5D=b&a%5B%5D=c');
    expect(gen({ '&': ['b', 'c'] })).toBe('%26%5B%5D=b&%26%5B%5D=c');

    expect(gen({ a: '&' })).toBe('a=%26');
    expect(gen({ '&': 'a' })).toBe('%26=a');
    expect(gen({ a: true })).toBe('a=true');
    expect(gen({ '$test': true })).toBe('$test=true');

    expect(gen({ obj: { a: 5, b: "str", c: false } })).toBe('obj%5Ba%5D=5&obj%5Bb%5D=str&obj%5Bc%5D=false');
    expect(gen({ obj:{ a: 5, b: undefined}})).toBe('obj%5Ba%5D=5');

    expect(gen({a: {b: ['c','d', ['f', 'g']]}})).toBe('a%5Bb%5D%5B%5D=c&a%5Bb%5D%5B%5D=d&a%5Bb%5D%5B2%5D%5B%5D=f&a%5Bb%5D%5B2%5D%5B%5D=g');
  });

  it('should parse query strings', () => {
    let parse = parseQueryString;

    expect(parse('')).toEqual({});
    expect(parse('=')).toEqual({});
    expect(parse('&')).toEqual({});
    expect(parse('?')).toEqual({});

    expect(parse('a')).toEqual({ a: true });
    expect(parse('a&b')).toEqual({ a: true, b: true });
    expect(parse('a=')).toEqual({ a: '' });
    expect(parse('a=&b=')).toEqual({ a: '', b: '' });

    expect(parse('a=b')).toEqual({ a: 'b' });
    expect(parse('a=b&c=d')).toEqual({ a: 'b', c: 'd' });
    expect(parse('a=b&&c=d')).toEqual({ a: 'b', c: 'd' });
    expect(parse('a=b&a=c')).toEqual({ a: 'c' });

    expect(parse('a=%26')).toEqual({ a: '&' });
    expect(parse('%26=a')).toEqual({ '&': 'a' });
    expect(parse('%26[]=b&%26[]=c')).toEqual({ '&': ['b', 'c'] });

    expect(parse('a[b]=c&a[d]=e')).toEqual({a: {b: 'c', d: 'e'}});
    expect(parse('a[b][c][d]=e')).toEqual({a: {b: {c: {d: 'e'}}}});
    expect(parse('a[b][]=c&a[b][]=d&a[b][2][]=f&a[b][2][]=g')).toEqual({a: {b: ['c','d', ['f', 'g']]}});
    expect(parse('a[0]=b')).toEqual({a: ['b']});
  });
});
<commit_msg>Added Unit tests for Fix for query string return true for param with equal sign on the end<commit_after>import { relativeToFile, join, parseQueryString, buildQueryString } from '../src/index';

describe('relativeToFile', () => {
  it('can make a dot path relative to a simple file', () => {
    var file = 'some/file.html';
    var path = './other/module';

    expect(relativeToFile(path, file)).toBe('some/other/module');
  });

  it('can make a dot path relative to an absolute file', () => {
    var file = 'http://durandal.io/some/file.html';
    var path = './other/module';

    expect(relativeToFile(path, file)).toBe('http://durandal.io/some/other/module');
  });

  it('can make a double dot path relative to an absolute file', () => {
    var file = 'http://durandal.io/some/file.html';
    var path = '../other/module';

    expect(relativeToFile(path, file)).toBe('http://durandal.io/other/module');
  });

  it('returns path if null file provided', () => {
    var file = null;
    var path = 'module';

    expect(relativeToFile(path, file)).toBe('module');
  });

  it('returns path if empty file provided', () => {
    var file = '';
    var path = 'module';

    expect(relativeToFile(path, file)).toBe('module');
  });
});

describe('join', () => {
  it('can combine two simple paths', () => {
    var path1 = 'one';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('one/two');
  });

  it('can combine an absolute path and a simple path', () => {
    var path1 = '/one';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('/one/two');
  });

  it('can combine an absolute path and a simple path with slash', () => {
    var path1 = '/one';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('/one/two');
  });

  it('can combine a single slash and a simple path', () => {
    var path1 = '/';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('/two');
  });

  it('can combine a single slash and a simple path with slash', () => {
    var path1 = '/';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('/two');
  });

  it('can combine an absolute path with protocol and a simple path', () => {
    var path1 = 'http://durandal.io';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('http://durandal.io/two');
  });

  it('can combine an absolute path with protocol and a simple path with slash', () => {
    var path1 = 'http://durandal.io';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('http://durandal.io/two');
  });

  it('can combine an absolute path and a simple path with a dot', () => {
    var path1 = 'http://durandal.io';
    var path2 = './two';

    expect(join(path1, path2)).toBe('http://durandal.io/two');
  });

  it('can combine a simple path and a relative path', () => {
    var path1 = 'one';
    var path2 = '../two';

    expect(join(path1, path2)).toBe('two');
  });

  it('can combine an absolute path and a relative path', () => {
    var path1 = 'http://durandal.io/somewhere';
    var path2 = '../two';

    expect(join(path1, path2)).toBe('http://durandal.io/two');
  });

  it('can combine a protocol independent path and a simple path', () => {
    var path1 = '//durandal.io';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('//durandal.io/two');
  });

  it('can combine a protocol independent path and a simple path with slash', () => {
    var path1 = '//durandal.io';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('//durandal.io/two');
  });

  it('can combine a protocol independent path and a simple path with a dot', () => {
    var path1 = '//durandal.io';
    var path2 = './two';

    expect(join(path1, path2)).toBe('//durandal.io/two');
  });

  it('can combine a protocol independent path and a relative path', () => {
    var path1 = '//durandal.io/somewhere';
    var path2 = '../two';

    expect(join(path1, path2)).toBe('//durandal.io/two');
  });

  it('can combine a complex path and a relative path', () => {
    var path1 = 'one/three';
    var path2 = '../two';

    expect(join(path1, path2)).toBe('one/two');
  });

  it('returns path2 if path1 null', () => {
    var path1 = null;
    var path2 = 'two';

    expect(join(path1, path2)).toBe('two');
  });

  it('returns path2 if path1 empty', () => {
    var path1 = '';
    var path2 = 'two';

    expect(join(path1, path2)).toBe('two');
  });

  it('returns path1 if path2 null', () => {
    var path1 = 'one';
    var path2 = null;

    expect(join(path1, path2)).toBe('one');
  });

  it('returns path1 if path2 empty', () => {
    var path1 = 'one';
    var path2 = '';

    expect(join(path1, path2)).toBe('one');
  });

  it('should respect a trailing slash', () => {
    var path1 = 'one/';
    var path2 = 'two/';

    expect(join(path1, path2)).toBe('one/two/');
  });

  it('should respect file:/// protocol with three slashes (empty host)', () => {
    var path1 = 'file:///one';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('file:///one/two');
  });

  it('should respect file:// protocol with two slashes (host given)', () => {
    var path1 = 'file://localhost:8080';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('file://localhost:8080/two');
  });

  it('should allow scheme-relative URL that uses colons in the path', () => {
    var path1 = '//localhost/one:/';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('//localhost/one:/two');
  });

  it('should not add more than two leading slashes to http:// protocol', () => {
    var path1 = 'http:///';
    var path2 = '/two';

    expect(join(path1, path2)).toBe('http://two');
  });
});

describe('query strings', () => {
  it('should build query strings', () => {
    let gen = buildQueryString;

    expect(gen()).toBe('');
    expect(gen(null)).toBe('');
    expect(gen({})).toBe('');
    expect(gen({ a: null })).toBe('');

    expect(gen({ '': 'a' })).toBe('=a');
    expect(gen({ a: 'b' })).toBe('a=b');
    expect(gen({ a: 'b', c: 'd' })).toBe('a=b&c=d');
    expect(gen({ a: 'b', c: null })).toBe('a=b');

    expect(gen({ a: ['b', 'c'] })).toBe('a%5B%5D=b&a%5B%5D=c');
    expect(gen({ '&': ['b', 'c'] })).toBe('%26%5B%5D=b&%26%5B%5D=c');

    expect(gen({ a: '&' })).toBe('a=%26');
    expect(gen({ '&': 'a' })).toBe('%26=a');
    expect(gen({ a: true })).toBe('a=true');
    expect(gen({ '$test': true })).toBe('$test=true');

    expect(gen({ obj: { a: 5, b: "str", c: false } })).toBe('obj%5Ba%5D=5&obj%5Bb%5D=str&obj%5Bc%5D=false');
    expect(gen({ obj:{ a: 5, b: undefined}})).toBe('obj%5Ba%5D=5');

    expect(gen({a: {b: ['c','d', ['f', 'g']]}})).toBe('a%5Bb%5D%5B%5D=c&a%5Bb%5D%5B%5D=d&a%5Bb%5D%5B2%5D%5B%5D=f&a%5Bb%5D%5B2%5D%5B%5D=g');
  });

  it('should parse query strings', () => {
    let parse = parseQueryString;

    expect(parse('')).toEqual({});
    expect(parse('=')).toEqual({});
    expect(parse('&')).toEqual({});
    expect(parse('?')).toEqual({});

    expect(parse('a')).toEqual({ a: true });
    expect(parse('a&b')).toEqual({ a: true, b: true });
    expect(parse('a=')).toEqual({ a: '' });
    expect(parse('a=&b=')).toEqual({ a: '', b: '' });

    expect(parse('a=b')).toEqual({ a: 'b' });
    expect(parse('a=b&c=d')).toEqual({ a: 'b', c: 'd' });
    expect(parse('a=b&&c=d')).toEqual({ a: 'b', c: 'd' });
    expect(parse('a=b&a=c')).toEqual({ a: 'c' });

    expect(parse('a=b&c=d=')).toEqual({ a: 'b', c: 'd' });
    expect(parse('a=b&c=d==')).toEqual({ a: 'b', c: 'd' });

    expect(parse('a=%26')).toEqual({ a: '&' });
    expect(parse('%26=a')).toEqual({ '&': 'a' });
    expect(parse('%26[]=b&%26[]=c')).toEqual({ '&': ['b', 'c'] });

    expect(parse('a[b]=c&a[d]=e')).toEqual({a: {b: 'c', d: 'e'}});
    expect(parse('a[b][c][d]=e')).toEqual({a: {b: {c: {d: 'e'}}}});
    expect(parse('a[b][]=c&a[b][]=d&a[b][2][]=f&a[b][2][]=g')).toEqual({a: {b: ['c','d', ['f', 'g']]}});
    expect(parse('a[0]=b')).toEqual({a: ['b']});
  });
});
<|endoftext|>


<commit_before>var prompt = require('prompt');

console.log('Collecting tags...');
var collectTags = require('./lib/collectTags.js');
var result = collectTags('./data/byField.in.graph');
var tags = result.tags;
console.log('Collected ' + result.totalTags + '; Unique tags: ' + result.uniqueTags);

console.log('Computing page rank...');
var computePageRank = require('./lib/computePageRank.js');
var rank = computePageRank('./data/dependenciesGraph.out.graph');
console.log('Done');

prompt.start();
getNextInput();

function getNextInput() {
  prompt.get([{
    description: 'Enter package keyword',
    name: 'keyword'
  }], function (err, result) {
    var matches = (tags[result.keyword] || []).sort(byPagerank);
    console.log('----------------------------------------------------------------------');
    console.log(matches.slice(0, Math.min(20, matches.length)).map(toDisplay).join('\n'));
    getNextInput();
  });
}

function toDisplay(x) {
  return 'https://www.npmjs.com/package/' + x + ' - ' + rank[x];
}

function byPagerank(x, y) {
  return rank[y] - rank[x];
}
<commit_msg>updated recommendation code<commit_after>var prompt = require('prompt');

console.log('Collecting tags...');
var collectTags = require('./lib/collectTags.js');
collectTags('./data/graph.in', process);

function process(result) {
  var tags = result.tags;
  console.log('Collected ' + result.totalTags + '; Unique tags: ' + result.uniqueTags);

  console.log('Computing page rank...');
  var computePageRank = require('./lib/computePageRank.js');
  var rank = computePageRank('./data/dependenciesGraph.out.graph');
  console.log('Done');

  prompt.start();
  getNextInput();

  function getNextInput() {
    prompt.get([{
      description: 'Enter package keyword',
      name: 'keyword'
    }], function (err, result) {
      var matches = (tags[result.keyword] || []).sort(byPagerank);
      console.log('----------------------------------------------------------------------');
      console.log(matches.slice(0, Math.min(20, matches.length)).map(toDisplay).join('\n'));
      getNextInput();
    });
  }

  function toDisplay(x) {
    return 'https://www.npmjs.com/package/' + x + ' - ' + rank[x];
  }

  function byPagerank(x, y) {
    return rank[y] - rank[x];
  }
}
<|endoftext|>


<commit_before>/**
 * @fileoverview Performance test.
 */

// ydn.debug.log('ydn.db', 'finest');

var db_name = 'pref-test-1';
var schema = {
  stores: [
    {
      name: 'st',
      autoIncrement: true
    }, {
      name: 'big',
      autoIncrement: true,
      indexes: [
        {
          name: 'n',
          unique: true,
          type: 'NUMERIC'
        }, {
          name: 't',
          type: 'TEXT'
        }, {
          name: 'm',
          multiEntry: true
        }]
    }]
};
var db = new ydn.db.Storage(db_name, schema);

var testPutSmall = function(db, data, onComplete, n) {
  // small data put test
  var small_data = {foo: 'bar'};
  for (var i = 0; i < n; i++) {
    var req = db.put('st', small_data);
    if (i == n - 1) {
      req.always(function() {
        onComplete(); // timer end
      });
    }
  }
};

var testPutOnRunSmall = function(th_db, data, onComplete, n) {
  // NOTE: thread policy don't metter in this test.
  var small_data = {foo: 'bar'};
  var req = db.run(function(tdb) { // make sure req is committed.
    for (var i = 0; i < n; i++) {
      tdb.put('st', small_data);
    }
  }, null, 'readwrite');
  req.always(function() {
    onComplete();
  });
};

var initClear = function(cb) {
  db.clear().always(function() {
    cb();
  });
};

var initPutArraySmall = function(cb, n) {
  // small data put test
  var data = [];
  for (var i = 0; i < n; i++) {
    data[i] = {foo: 'bar'};
  }
  db.clear().always(function() {
    cb(data);
  });
};

var testPutArraySmall = function(db, data, onComplete, n) {
  var req = db.put('st', data);
  req.always(function() {
    // make sure it complete write
    db.get('st', 1).always(function() {
      onComplete();
    });
  });
};

var initGetSmall = function(onComplete, n) {
  var data = [];
  for (var i = 0; i < n; i++) {
    data[i] = {foo: 'bar'};
  }
  db.clear('st').always(function() {
    var req = db.put('st', data);
    req.always(function() {
      // make sure it complete write
      db.keys('st', null, 1).always(function(x) {
        // smallest key
        onComplete(x[0]);
      });
    });
  });
};

var testGetSmall = function(db, data, onComplete, n) {
  // small data put test
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var id = (n * Math.random()) | 0;
    var req = db.get('st', id);
    req.always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      }
    });
  };

};

var testValuesKeyRangeSmall = function(db, start, onComplete, n) {
  var range = ydn.db.KeyRange.bound(start, start + n, false, true);
  db.values('st', range, 100000).always(function(x) {
    onComplete();
    if (x.length != n) {
      throw new Error('result must have ' + n + ' objects, but found ' +
          x.length, x);
    }
  });
};

var testKeysKeyRangeSmall = function(db, start, onComplete, n) {
  var range = ydn.db.KeyRange.bound(start, start + n, false, true);
  db.keys('st', range, 10000).always(function(x) {
    onComplete();
    if (x.length != n) {
      throw new Error('keys result must have ' + n + ' objects, but found ' +
          x.length, x);
    }
  });
};

var initBigData = function(cb, n) {
  var long =  (new Array(1000)).join(
      (new Array(10)).join('abcdefghijklmnopuqstubc'));
  var arr = [];
  for (var i = 0; i < 16; i++) {
    arr[i] = Math.random();
  }
  var data = [];
  for (var i = 0; i < n; i++) {
    data[i] = {
      load: long,
      n: Math.random(),
      m: arr,
      t: Math.random().toString(36).slice(2)
    };
  }
  console.log(n + ' big data generated');
  cb(data);
};

var testPutBig = function(db, data, onComplete, n) {
  // small data put test
  var small_data = {foo: 'bar'};
  for (var i = 0; i < n; i++) {
    var req = db.put('big', small_data);
    if (i == n - 1) {
      req.always(function() {
        onComplete(); // timer end
      });
    }
  }
};

var init100IndexData = function(cb) {
  initBigData(function(data) {
    db.clear('big').always(function() {
      var req = db.put('big', data);
      req.always(function() {
        cb(data); // timer end
      });
    });
  }, 100);
};

var valuesIndexKeyRangeBig = function(db, start, onComplete, n) {
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var range = ydn.db.KeyRange.lowerBound(Math.random());
    db.values('big', 'n', range, 1).always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      } else {
        // console.log(x); // ok
      }
    });
  }
};

var keysIndexKeyRangeBig = function(db, start, onComplete, n) {
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var range = ydn.db.KeyRange.lowerBound(Math.random());
    db.keys('big', 'n', range, 1).always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      } else {
        // console.log(x); // ok
      }
    });
  }
};

var valuesIndexKeyRangeBigLimit5 = function(db, start, onComplete, n) {
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var range = ydn.db.KeyRange.lowerBound(Math.random());
    db.values('big', 'n', range, 10).always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      } else {
        // console.log(x); // ok
      }
    });
  }
};

var keysIndexKeyRangeBigLimit5 = function(db, start, onComplete, n) {
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var range = ydn.db.KeyRange.lowerBound(Math.random());
    db.keys('big', 'n', range, 10).always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      } else {
        // console.log(x); // ok
      }
    });
  }
};

var valuesIndexIterBig = function(db, start, onComplete, n) {
  for (var i = 0; i < n; i++) {
    var iter = ydn.db.IndexValueCursors.where('big', 'n', '>', Math.random());
    db.values(iter, 1).always(function(x) {
      if (i == n - 1) {
        onComplete(); // timer end
      } else {

      }
    });
  };
};

var pref = new Pref(db);

 pref.addTest('Put (small-object)', testPutSmall, initClear, 100, 10);
 pref.addTest('Put array (small-object)', testPutArraySmall, initPutArraySmall, 100, 10);
 pref.addTest('Put on a transaction (small-object)', testPutOnRunSmall, initClear, 100, 10);
 pref.addTest('Get (small-object)', testGetSmall, initGetSmall, 100, 10);
 pref.addTest('Values by key range (small-object)', testValuesKeyRangeSmall, null, 100, 10);
 pref.addTest('Keys by key range (small-object)', testKeysKeyRangeSmall, null, 100, 10);

 pref.addTest('Put (with indexes)', testPutBig, initBigData, 20, 5);

pref.addTest('Keys index key range limit 1', keysIndexKeyRangeBig, init100IndexData, 20, 10);
 pref.addTest('Values index key range limit 1', valuesIndexKeyRangeBig, null, 20, 10);
 pref.addTest('Values index key range limit 10', valuesIndexKeyRangeBigLimit5, null, 20, 10);
 pref.addTest('Keys index key range limit 10', keysIndexKeyRangeBigLimit5, null, 20, 10);
pref.run();
<commit_msg>add std<commit_after>/**
 * @fileoverview Performance test.
 */

// ydn.debug.log('ydn.db', 'finest');

var db_name = 'pref-test-1';
var schema = {
  stores: [
    {
      name: 'st',
      autoIncrement: true
    }, {
      name: 'big',
      autoIncrement: true,
      indexes: [
        {
          name: 'n',
          unique: true,
          type: 'NUMERIC'
        }, {
          name: 't',
          type: 'TEXT'
        }, {
          name: 'm',
          multiEntry: true
        }]
    }]
};
var db = new ydn.db.Storage(db_name, schema);

var testPutTightSmall = function(db, data, onComplete, n) {
  // small data put test
  var small_data = {foo: 'bar'};
  for (var i = 0; i < n; i++) {
    var req = db.put('st', small_data);
    if (i == n - 1) {
      req.always(function() {
        onComplete(); // timer end
      });
    }
  }
};

var testPutSmall = function(db, data, onComplete, n) {
  var small_data = {foo: 'bar'};
  var test = function(i) {
    var req = db.put('st', small_data);
    i++;
    req.always(function(x) {
      if (i == n) {
        onComplete(); // timer end
      } else {
        test(i);
      }
    });
  };
  test(0);
};

var testPutOnRunSmall = function(th_db, data, onComplete, n) {
  // NOTE: thread policy don't metter in this test.
  var small_data = {foo: 'bar'};
  var req = db.run(function(tdb) { // make sure req is committed.
    for (var i = 0; i < n; i++) {
      tdb.put('st', small_data);
    }
  }, null, 'readwrite');
  req.always(function() {
    onComplete();
  });
};

var initClear = function(cb) {
  db.clear().always(function() {
    cb();
  });
};

var initPutArraySmall = function(cb, n) {
  // small data put test
  var data = [];
  for (var i = 0; i < n; i++) {
    data[i] = {foo: 'bar'};
  }
  db.clear().always(function() {
    cb(data);
  });
};

var testPutArraySmall = function(db, data, onComplete, n) {
  var req = db.put('st', data);
  req.always(function() {
    // make sure it complete write
    db.get('st', 1).always(function() {
      onComplete();
    });
  });
};

var initGetSmall = function(onComplete, n) {
  var data = [];
  for (var i = 0; i < n; i++) {
    data[i] = {foo: 'bar'};
  }
  db.clear('st').always(function() {
    var req = db.put('st', data);
    req.always(function() {
      // make sure it complete write
      db.keys('st', null, 1).always(function(x) {
        // smallest key
        onComplete(x[0]);
      });
    });
  });
};

var testGetTightSmall = function(db, data, onComplete, n) {
  // small data put test
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var id = (n * Math.random()) | 0;
    var req = db.get('st', id);
    req.always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      }
    });
  }
};

var testGetSmall = function(db, data, onComplete, n) {
  // small data put test
  var test = function(i) {
    var id = (n * Math.random()) | 0;
    var req = db.get('st', id);
    i++;
    req.always(function(x) {
      if (i == n) {
        onComplete(); // timer end
      } else {
        test(i);
      }
    });
  };
  test(0);
};

var testValuesKeyRangeSmall = function(db, start, onComplete, n) {
  var range = ydn.db.KeyRange.bound(start, start + n, false, true);
  db.values('st', range, 100000).always(function(x) {
    onComplete();
    if (x.length != n) {
      throw new Error('result must have ' + n + ' objects, but found ' +
          x.length, x);
    }
  });
};

var testKeysKeyRangeSmall = function(db, start, onComplete, n) {
  var range = ydn.db.KeyRange.bound(start, start + n, false, true);
  db.keys('st', range, 10000).always(function(x) {
    onComplete();
    if (x.length != n) {
      throw new Error('keys result must have ' + n + ' objects, but found ' +
          x.length, x);
    }
  });
};

var initBigData = function(cb, n) {
  var long =  (new Array(1000)).join(
      (new Array(10)).join('abcdefghijklmnopuqstubc'));
  var data = [];
  for (var i = 0; i < n; i++) {
    var arr = [];
    for (var j = 0; j < 16; j++) {
      arr[j] = Math.random();
    }
    data[i] = {
      load: long,
      n: Math.random(),
      m: arr,
      t: Math.random().toString(36).slice(2)
    };
  }
  console.log(n + ' big data generated');
  cb(data);
};

var testPutBig = function(db, data, onComplete, n) {
  // small data put test
  var small_data = {foo: 'bar'};
  for (var i = 0; i < n; i++) {
    var req = db.put('big', small_data);
    if (i == n - 1) {
      req.always(function() {
        onComplete(); // timer end
      });
    }
  }
};

var init100IndexData = function(cb) {
  initBigData(function(data) {
    db.clear('big').always(function() {
      var req = db.put('big', data);
      req.always(function() {
        cb(data); // timer end
      });
    });
  }, 100);
};

var valuesIndexKeyRangeBig = function(db, start, onComplete, n) {
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var range = ydn.db.KeyRange.lowerBound(Math.random());
    db.values('big', 'n', range, 1).always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      } else {
        // console.log(x); // ok
      }
    });
  }
};

var keysIndexKeyRangeBig = function(db, start, onComplete, n) {
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var range = ydn.db.KeyRange.lowerBound(Math.random());
    db.keys('big', 'n', range, 1).always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      } else {
        // console.log(x); // ok
      }
    });
  }
};

var valuesIndexKeyRangeBigLimit5 = function(db, start, onComplete, n) {
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var range = ydn.db.KeyRange.lowerBound(Math.random());
    db.values('big', 'n', range, 10).always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      } else {
        // console.log(x); // ok
      }
    });
  }
};

var keysIndexKeyRangeBigLimit5 = function(db, start, onComplete, n) {
  var cnt = 0;
  for (var i = 0; i < n; i++) {
    var range = ydn.db.KeyRange.lowerBound(Math.random());
    db.keys('big', 'n', range, 10).always(function(x) {
      cnt++;
      if (cnt == n) {
        onComplete(); // timer end
      } else {
        // console.log(x); // ok
      }
    });
  }
};

var valuesIndexIterBig = function(db, start, onComplete, n) {
  for (var i = 0; i < n; i++) {
    var iter = ydn.db.IndexValueCursors.where('big', 'n', '>', Math.random());
    db.values(iter, 1).always(function(x) {
      if (i == n - 1) {
        onComplete(); // timer end
      } else {

      }
    });
  };
};

var pref = new Pref(db);

 pref.addTest('Put (small-object)', testPutSmall, initClear, 100, 10);
 pref.addTest('Put tight loop (small-object)', testPutTightSmall, initClear, 100, 10);
 pref.addTest('Put array (small-object)', testPutArraySmall, initPutArraySmall, 100, 10);
 pref.addTest('Put on a transaction (small-object)', testPutOnRunSmall, initClear, 100, 10);
 pref.addTest('Get (small-object)', testGetSmall, initGetSmall, 100, 10);
 pref.addTest('Get tight loop (small-object)', testGetTightSmall, initGetSmall, 100, 10);
 pref.addTest('Values by key range (small-object)', testValuesKeyRangeSmall, null, 100, 10);
 pref.addTest('Keys by key range (small-object)', testKeysKeyRangeSmall, null, 100, 10);

 pref.addTest('Put (with indexes)', testPutBig, initBigData, 20, 5);

pref.addTest('Keys index key range limit 1', keysIndexKeyRangeBig, init100IndexData, 20, 10);
 pref.addTest('Values index key range limit 1', valuesIndexKeyRangeBig, null, 20, 10);
 pref.addTest('Values index key range limit 10', valuesIndexKeyRangeBigLimit5, null, 20, 10);
 pref.addTest('Keys index key range limit 10', keysIndexKeyRangeBigLimit5, null, 20, 10);
pref.run();
<|endoftext|>


<commit_before>if (process.env.SAUCE_USERNAME) {
	console.info("Running only selenium tests, skipping this one");
	return;
}

var expect = require('expect.js');
var request = require('request');
var express = require('express');
var dom = require('express-dom');

dom.settings.stall = 5000;
dom.settings.allow = 'all';
dom.settings.timeout = 10000;
dom.settings.console = true;

var host = "http://localhost";

describe("Prerendering", function suite() {
	this.timeout(3000);
	var server, port;

	before(function(done) {
		var app = express();
		app.set('views', __dirname + '/public');
		app.get(/\.(json|js|css|png)$/, express.static(app.get('views')));
		app.get(/\/templates\/.+\.html$/, express.static(app.get('views')));
		app.get(/\.html$/, dom().load());

		server = app.listen(function(err) {
			if (err) console.error(err);
			port = server.address().port;
			done();
		});
	});

	after(function(done) {
		server.close();
		done();
	});

	it("should run build but not setup", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/build.html'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf("I'm built0")).to.be.greaterThan(0);
			done();
		});
	});

	it("should run route and build", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=build'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf("I'm built0")).to.be.greaterThan(0);
			done();
		});
	});

	it("should read and store data before route, and read it during build", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/store.html?template=store'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf("I'm built0 with thing=1 and data.template=store")).to.be.greaterThan(0);
			expect(body.indexOf('data-page-thing="1"')).to.not.be.greaterThan(0);
			done();
		});
	});

	it("should run route and imports", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=import'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf("I'm built0")).to.be.greaterThan(0);
			expect(body.indexOf("your body0")).to.be.greaterThan(0);
			done();
		});
	});

	it("should run route and ignore imports", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=import-ignore'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf('data-page-stage="2"')).to.be.greaterThan(0);
			expect(body.indexOf("I'm built0")).to.be.greaterThan(0);
			expect(body.indexOf('
77
')).to.be.greaterThan(0);
			done();
		});
	});

	it("should run route and load scripts in correct order", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=order-scripts'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf("ABBACCBAC")).to.be.greaterThan(0);
			done();
		});
	});

	it("should not load have stylesheets loaded by express-dom prerendering mode anyway", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=stylesheets'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf('
squared0
')).to.not.be.greaterThan(0);
			done();
		});
	});

});

<commit_msg>Additional check in test<commit_after>if (process.env.SAUCE_USERNAME) {
	console.info("Running only selenium tests, skipping this one");
	return;
}

var expect = require('expect.js');
var request = require('request');
var express = require('express');
var dom = require('express-dom');

dom.settings.stall = 5000;
dom.settings.allow = 'all';
dom.settings.timeout = 10000;
dom.settings.console = true;

var host = "http://localhost";

describe("Prerendering", function suite() {
	this.timeout(3000);
	var server, port;

	before(function(done) {
		var app = express();
		app.set('views', __dirname + '/public');
		app.get(/\.(json|js|css|png)$/, express.static(app.get('views')));
		app.get(/\/templates\/.+\.html$/, express.static(app.get('views')));
		app.get(/\.html$/, dom().load());

		server = app.listen(function(err) {
			if (err) console.error(err);
			port = server.address().port;
			done();
		});
	});

	after(function(done) {
		server.close();
		done();
	});

	it("should run build but not setup", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/build.html'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf("I'm built0")).to.be.greaterThan(0);
			done();
		});
	});

	it("should run route and build", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=build'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf("I'm built0")).to.be.greaterThan(0);
			done();
		});
	});

	it("should read and store data before route, and read it during build", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/store.html?template=store'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf("I'm built0 with thing=1 and data.template=store")).to.be.greaterThan(0);
			expect(body.indexOf('data-page-thing="1"')).to.not.be.greaterThan(0);
			done();
		});
	});

	it("should run route and imports", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=import'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf('data-page-stage="2"')).to.be.greaterThan(0);
			expect(body.indexOf("I'm built0")).to.be.greaterThan(0);
			expect(body.indexOf("your body0")).to.be.greaterThan(0);
			done();
		});
	});

	it("should run route and ignore imports", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=import-ignore'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf('data-page-stage="2"')).to.be.greaterThan(0);
			expect(body.indexOf("I'm built0")).to.be.greaterThan(0);
			expect(body.indexOf('
77
')).to.be.greaterThan(0);
			done();
		});
	});

	it("should run route and load scripts in correct order", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=order-scripts'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf("ABBACCBAC")).to.be.greaterThan(0);
			done();
		});
	});

	it("should not load have stylesheets loaded by express-dom prerendering mode anyway", function(done) {
		request({
			method: 'GET',
			url: host + ':' + port + '/route.html?template=stylesheets'
		}, function(err, res, body) {
			expect(res.statusCode).to.be(200);
			expect(body.indexOf('
squared0
')).to.not.be.greaterThan(0);
			done();
		});
	});

});

<|endoftext|>


<commit_before>'use strict';

var chai = require('chai');
var assert = chai.assert;
var util = require('../src/util');
var read = require('../src/import/read');
var type = require('../src/import/type');

var fs = require('fs');
var topojson = require('topojson');

chai.config.truncateThreshold = 0;

var fields = ['a', 'b', 'c', 'd', 'e'];
var data = [
  {a:1, b:'aaa', c:true,  d:'1/1/2001', e:1.2},
  {a:2, b:'bbb', c:false, d:'1/2/2001', e:3.4},
  {a:3, b:'ccc', c:false, d:'1/3/2001', e:5.6},
  {a:4, b:'ddd', c:true,  d:'1/4/2001', e:7.8},
];
var strings = data.map(function(x) {
  return {a:String(x.a), b:x.b, c:String(x.c), d:x.d, e:String(x.e)};
});
strings.columns = fields;

// d3-dsv includes "columns" annotation, json parse does not
// so create two versions of parsed columns for testing
var parsed = data.map(function(x) {
  return {a:x.a, b:x.b, c:x.c, d:Date.parse(x.d), e:x.e};
});
var parsedNoColumns = util.duplicate(parsed);
parsed.columns = fields;

var typeAnnotations = {
  a: 'integer',
  b: 'string',
  c: 'boolean',
  d: 'date',
  e: 'number'
};
type.annotation(parsed, typeAnnotations);
type.annotation(parsedNoColumns, typeAnnotations);

function toDelimitedText(data, delimiter) {
  var head = fields.join(delimiter);
  var body = data.map(function(row) {
    return fields.map(function(f) {
      var v = row[f];
      return util.isString(v) ? ('"'+v+'"') : v;
    }).join(delimiter);
  });
  return head + '\n' + body.join('\n');
}

describe('read', function() {

  describe('type checks', function() {
    it('should check nulls', function() {
      assert.equal(null, type([null]));
    });
    it('should check booleans', function() {
      assert.equal('boolean', type([NaN, null, true, false]));
    });
    it('should check numbers', function() {
      assert.equal('number', type([NaN, null, 1, 2]));
      assert.equal('number', type([NaN, null, 1.4, 2.3]));
    });
    it('should check dates', function() {
      assert.equal('date', type([NaN, null, new Date('1/1/2001'), new Date('Jan 5, 2001')]));
    });
    it('should check strings', function() {
      assert.equal('string', type([NaN, null, '', 'a', 'b']));
    });
    it('should support accessor', function() {
      assert.equal('string', type([{a:null}, {a:'a'}, {a:'b'}], util.$('a')));
      assert.equal('string', type([{a:null}, {a:'a'}, {a:'b'}], 'a'));
    });
    it('should recover type annotations', function() {
      assert.isNull(type.annotation([]));
      assert.isUndefined(type.all([]));
      var types = type.all(parsed);
      assert.deepEqual(type.annotation(parsed), types);
    });
    it('should use existing type annotations', function() {
      var d = data.slice();
      var types = type.inferAll(d);
      type.annotation(d, types);
      assert.equal('integer', type(d, 'a'));
      types.a = 12345;
      assert.equal('number', type(d, 'a'));
    });
  });

  describe('type parsers', function() {
    var p = type.parsers;
    it('should parse booleans', function() {
      assert.equal(true, p.boolean('true'));
      assert.equal(false, p.boolean('false'));
      assert.equal(null, p.boolean(null));
    });
    it('should parse numbers', function() {
      assert.equal(1, p.number('1'));
      assert.equal(3.14, p.number('3.14'));
      assert.equal(100, p.number('1e2'));
      assert.equal(null, p.number(null));
    });
    it('should parse date', function() {
      assert.equal(+(new Date(2000, 0, 1)), +p.date('1/1/2000'));
      assert.equal(null, p.date(null));
    });
    it('should parse date with format', function() {
      assert.equal(+(new Date(1990, 6, 18)), +p.date('18/07/1990', '%d/%m/%Y'));
      assert.equal(+(new Date(1990, 6, 18)), +p.date('07/18/1990', '%m/%d/%Y'));
      assert.equal(null, p.date(null, '%d/%m/%Y'));
    });
    it('should parse strings', function() {
      assert.equal('a', p.string('a'));
      assert.equal('bb', p.string('bb'));
      assert.equal(null, p.string(''));
      assert.equal(null, p.string(null));
    });
  });

  describe('type inference', function() {
    it('should infer booleans', function() {
      assert.equal('boolean', type.infer(['true', 'false', NaN, null]));
      assert.equal('boolean', type.infer([true, false, null]));
    });
    it('should infer integers', function() {
      assert.equal('integer', type.infer(['0', '1', null, '3', NaN, undefined, '-5']));
      assert.equal('integer', type.infer([1, 2, 3]));
    });
    it('should infer numbers', function() {
      assert.equal('number', type.infer(['0', '1', null, '3.1415', NaN, 'Infinity', '1e-5']));
      assert.equal('number', type.infer([1, 2.2, 3]));
    });
    it('should infer dates', function() {
      assert.equal('date', type.infer(['1/1/2001', null, NaN, 'Jan 5, 2001']));
      assert.equal('date', type.infer([new Date('1/1/2001'), null, new Date('Jan 5, 2001')]));
    });
    it('should infer strings when all else fails', function() {
      assert.equal('string', type.infer(['hello', '', '1', 'true', null]));
    });
    it('should handle function accessors', function() {
      var data = [
        {a: '1', b: 'true'},
        {a: '2', b: 'false'},
        {a: '3', b: null}
      ];
      assert.equal('integer', type.infer(data, 'a'));
      assert.equal('boolean', type.infer(data, 'b'));
      assert.equal('integer', type.infer(data, util.accessor('a')));
      assert.equal('boolean', type.infer(data, util.accessor('b')));
    });
    it('should infer types for all fields', function() {
      assert.deepEqual(type.annotation(parsed), type.inferAll(data));
      assert.deepEqual(type.annotation(parsed), type.inferAll(strings));
    });
  });

  describe('json', function() {
    var json = JSON.stringify(data);
    it('should read json data', function() {
      assert.deepEqual(read(json), data);
      assert.deepEqual(read(json, {type:'json'}), data);
    });
    it('should parse json fields', function() {
      assert.deepEqual(read(json, {type:'json', parse: type.annotation(parsed)}), parsedNoColumns);
    });
    it('should auto-parse json fields', function() {
      assert.deepEqual(read(json, {type:'json', parse:'auto'}), parsedNoColumns);
    });
    it('should read json from property', function() {
      var json = JSON.stringify({foo: data});
      assert.deepEqual(read(json, {type:'json', property:'foo'}), data);
    });
    it('should parse date with format', function() {
      var json = [{foo: '18/07/1990'}];

      assert.deepEqual(
        read(json, {type:'json', parse: {foo: 'date:%d/%m/%Y'}})[0],
        {foo: new Date(1990, 6, 18)});

      json = [{foo: '07/18/1990'}];
      assert.deepEqual(
        read(json, {type:'json', parse: {foo: 'date:%m/%d/%Y'}})[0],
        {foo: new Date(1990, 6, 18)});
    });
  });

  describe('csv', function() {
    var csv = toDelimitedText(data, ',');
    it('should read csv data', function() {
      assert.deepEqual(read(csv, {type:'csv'}), strings);
    });
    it('should parse csv fields', function() {
      assert.deepEqual(read(csv, {type:'csv', parse:type.annotation(parsed)}), parsed);
    });
    it('should auto-parse csv fields', function() {
      assert.deepEqual(read(csv, {type:'csv', parse:'auto'}), parsed);
    });
  });

  describe('tsv', function() {
    var tsv = toDelimitedText(data, '\t');
    it('should read tsv data', function() {
      assert.deepEqual(read(tsv, {type:'tsv'}), strings);
    });
    it('should parse tsv fields', function() {
      assert.deepEqual(read(tsv, {type:'tsv', parse:type.annotation(parsed)}), parsed);
    });
    it('should auto-parse tsv fields', function() {
      assert.deepEqual(read(tsv, {type:'tsv', parse:'auto'}), parsed);
    });
  });

  describe('dsv', function() {
    var psv = toDelimitedText(data, '|');
    it('should read dsv data', function() {
      assert.deepEqual(read(psv, {type:'dsv', delimiter:'|'}), strings);
      assert.equal(read('', {type:'dsv', delimiter:'|'}), '');
    });
    it('should support delimiter constructor', function() {
      var reader = read.formats.dsv.delimiter('|');
      assert.deepEqual(reader(psv), strings);
    });
    it('should accept header parameter', function() {
      var body = psv.slice(psv.indexOf('\n')+1);
      assert.deepEqual(read(body, {
        type: 'dsv',
        delimiter: '|',
        header: fields
      }), strings);
    });
    it('should parse dsv fields', function() {
      assert.deepEqual(read(psv, {type:'dsv', delimiter:'|', parse:type.annotation(parsed)}), parsed);
    });
    it('should auto-parse dsv fields', function() {
      assert.deepEqual(read(psv, {type:'dsv', delimiter:'|', parse:'auto'}), parsed);
    });
  });

  describe('topojson', function() {
    var world = fs.readFileSync('./test/data/world-110m.json', 'utf8');
    var json = JSON.parse(world);

    it('should read topojson mesh', function() {
      var mesh = read(world, {type:'topojson', mesh: 'countries'});
      var tj = topojson.mesh(json, json.objects['countries']);
      assert.equal(JSON.stringify(tj), JSON.stringify(mesh[0]));
    });

    it('should read topojson feature', function() {
      var feature = read(world, {type:'topojson', feature: 'countries'});
      var tj = topojson.feature(json, json.objects['countries']).features;
      assert.equal(JSON.stringify(tj), JSON.stringify(feature));
    });

    it('should throw error if topojson library unavailable', function() {
      read.formats.topojson.topojson = null;
      assert.throws(function() {
        read(world, {type:'topojson', mesh: 'countries'});
      });
      read.formats.topojson.topojson = topojson;
    });

    it('should throw error if topojson is invalid', function() {
      var data = {objects: {}};
      assert.throws(function() {
        read(data, {type:'topojson', feature: 'countries'});
      });
      assert.throws(function() {
        read(data, {type:'topojson', mesh: 'countries'});
      });
    });

    it('should throw error if topojson parameters are missing', function() {
      assert.throws(function() { read(world, {type:'topojson'}); });
    });
  });

  describe('treejson', function() {
    var flare = fs.readFileSync('./test/data/flare.json', 'utf8');
    var json = JSON.parse(flare);

    it('should read treejson data', function() {
      var data = null;
      assert.doesNotThrow(function() { data = read(flare, {type:'treejson'}); });
      assert.equal(json.name, data[0].name);
      assert.equal(data[0].hasOwnProperty('parent'), true);
      assert.equal(data[0].parent, null);
    });
  });
});
<commit_msg>Use annotated data for comparison<commit_after>'use strict';

var chai = require('chai');
var assert = chai.assert;
var util = require('../src/util');
var read = require('../src/import/read');
var type = require('../src/import/type');

var fs = require('fs');
var topojson = require('topojson');

chai.config.truncateThreshold = 0;

var fields = ['a', 'b', 'c', 'd', 'e'];
var data = [
  {a:1, b:'aaa', c:true,  d:'1/1/2001', e:1.2},
  {a:2, b:'bbb', c:false, d:'1/2/2001', e:3.4},
  {a:3, b:'ccc', c:false, d:'1/3/2001', e:5.6},
  {a:4, b:'ddd', c:true,  d:'1/4/2001', e:7.8},
];
var strings = data.map(function(x) {
  return {a:String(x.a), b:x.b, c:String(x.c), d:x.d, e:String(x.e)};
});
strings.columns = fields;

// d3-dsv includes "columns" annotation, json parse does not
// so create two versions of parsed columns for testing
var parsed = data.map(function(x) {
  return {a:x.a, b:x.b, c:x.c, d:Date.parse(x.d), e:x.e};
});
var parsedNoColumns = util.duplicate(parsed);
parsed.columns = fields;

var typeAnnotations = {
  a: 'integer',
  b: 'string',
  c: 'boolean',
  d: 'date',
  e: 'number'
};
type.annotation(parsed, typeAnnotations);
type.annotation(parsedNoColumns, typeAnnotations);

function toDelimitedText(data, delimiter) {
  var head = fields.join(delimiter);
  var body = data.map(function(row) {
    return fields.map(function(f) {
      var v = row[f];
      return util.isString(v) ? ('"'+v+'"') : v;
    }).join(delimiter);
  });
  return head + '\n' + body.join('\n');
}

describe('read', function() {

  describe('type checks', function() {
    it('should check nulls', function() {
      assert.equal(null, type([null]));
    });
    it('should check booleans', function() {
      assert.equal('boolean', type([NaN, null, true, false]));
    });
    it('should check numbers', function() {
      assert.equal('number', type([NaN, null, 1, 2]));
      assert.equal('number', type([NaN, null, 1.4, 2.3]));
    });
    it('should check dates', function() {
      assert.equal('date', type([NaN, null, new Date('1/1/2001'), new Date('Jan 5, 2001')]));
    });
    it('should check strings', function() {
      assert.equal('string', type([NaN, null, '', 'a', 'b']));
    });
    it('should support accessor', function() {
      assert.equal('string', type([{a:null}, {a:'a'}, {a:'b'}], util.$('a')));
      assert.equal('string', type([{a:null}, {a:'a'}, {a:'b'}], 'a'));
    });
    it('should recover type annotations', function() {
      assert.isNull(type.annotation([]));
      assert.isUndefined(type.all([]));
      var types = type.all(parsed);
      assert.deepEqual(type.annotation(parsed), types);
    });
    it('should use existing type annotations', function() {
      var d = data.slice();
      var types = type.inferAll(d);
      type.annotation(d, types);
      assert.equal('integer', type(d, 'a'));
      types.a = 12345;
      assert.equal('number', type(d, 'a'));
    });
  });

  describe('type parsers', function() {
    var p = type.parsers;
    it('should parse booleans', function() {
      assert.equal(true, p.boolean('true'));
      assert.equal(false, p.boolean('false'));
      assert.equal(null, p.boolean(null));
    });
    it('should parse numbers', function() {
      assert.equal(1, p.number('1'));
      assert.equal(3.14, p.number('3.14'));
      assert.equal(100, p.number('1e2'));
      assert.equal(null, p.number(null));
    });
    it('should parse date', function() {
      assert.equal(+(new Date(2000, 0, 1)), +p.date('1/1/2000'));
      assert.equal(null, p.date(null));
    });
    it('should parse date with format', function() {
      assert.equal(+(new Date(1990, 6, 18)), +p.date('18/07/1990', '%d/%m/%Y'));
      assert.equal(+(new Date(1990, 6, 18)), +p.date('07/18/1990', '%m/%d/%Y'));
      assert.equal(null, p.date(null, '%d/%m/%Y'));
    });
    it('should parse strings', function() {
      assert.equal('a', p.string('a'));
      assert.equal('bb', p.string('bb'));
      assert.equal(null, p.string(''));
      assert.equal(null, p.string(null));
    });
  });

  describe('type inference', function() {
    it('should infer booleans', function() {
      assert.equal('boolean', type.infer(['true', 'false', NaN, null]));
      assert.equal('boolean', type.infer([true, false, null]));
    });
    it('should infer integers', function() {
      assert.equal('integer', type.infer(['0', '1', null, '3', NaN, undefined, '-5']));
      assert.equal('integer', type.infer([1, 2, 3]));
    });
    it('should infer numbers', function() {
      assert.equal('number', type.infer(['0', '1', null, '3.1415', NaN, 'Infinity', '1e-5']));
      assert.equal('number', type.infer([1, 2.2, 3]));
    });
    it('should infer dates', function() {
      assert.equal('date', type.infer(['1/1/2001', null, NaN, 'Jan 5, 2001']));
      assert.equal('date', type.infer([new Date('1/1/2001'), null, new Date('Jan 5, 2001')]));
    });
    it('should infer strings when all else fails', function() {
      assert.equal('string', type.infer(['hello', '', '1', 'true', null]));
    });
    it('should handle function accessors', function() {
      var data = [
        {a: '1', b: 'true'},
        {a: '2', b: 'false'},
        {a: '3', b: null}
      ];
      assert.equal('integer', type.infer(data, 'a'));
      assert.equal('boolean', type.infer(data, 'b'));
      assert.equal('integer', type.infer(data, util.accessor('a')));
      assert.equal('boolean', type.infer(data, util.accessor('b')));
    });
    it('should infer types for all fields', function() {
      assert.deepEqual(type.annotation(parsed), type.inferAll(data));
      assert.deepEqual(type.annotation(parsed), type.inferAll(strings));
    });
  });

  describe('json', function() {
    var json = JSON.stringify(data);
    it('should read json data', function() {
      assert.deepEqual(read(json), data);
      assert.deepEqual(read(json, {type:'json'}), data);
    });
    it('should parse json fields', function() {
      assert.deepEqual(read(json, {type:'json', parse: type.annotation(parsed)}), parsedNoColumns);
    });
    it('should auto-parse json fields', function() {
      assert.deepEqual(read(json, {type:'json', parse:'auto'}), parsedNoColumns);
    });
    it('should read json from property', function() {
      var json = JSON.stringify({foo: data});
      assert.deepEqual(read(json, {type:'json', property:'foo'}), data);
    });

    it('should parse date with format %d/%m/%Y', function() {
      var expected = [{foo: new Date(1990, 6, 18)}];
      var json = [{foo: '18/07/1990'}];
      var types = {foo: 'date:%d/%m/%Y'};
      type.annotation(expected, types);
      assert.deepEqual(
        read(json, {type:'json', parse: types}),
        expected);
    });
    it('should parse date with format %m/%d/%Y', function() {
      var expected = [{foo: new Date(1990, 6, 18)}];
      var json = [{foo: '07/18/1990'}];
      var types = {foo: 'date:%m/%d/%Y'};
      type.annotation(expected, types);
      assert.deepEqual(
        read(json, {type:'json', parse: types}),
        expected);
    });
  });

  describe('csv', function() {
    var csv = toDelimitedText(data, ',');
    it('should read csv data', function() {
      assert.deepEqual(read(csv, {type:'csv'}), strings);
    });
    it('should parse csv fields', function() {
      assert.deepEqual(read(csv, {type:'csv', parse:type.annotation(parsed)}), parsed);
    });
    it('should auto-parse csv fields', function() {
      assert.deepEqual(read(csv, {type:'csv', parse:'auto'}), parsed);
    });
  });

  describe('tsv', function() {
    var tsv = toDelimitedText(data, '\t');
    it('should read tsv data', function() {
      assert.deepEqual(read(tsv, {type:'tsv'}), strings);
    });
    it('should parse tsv fields', function() {
      assert.deepEqual(read(tsv, {type:'tsv', parse:type.annotation(parsed)}), parsed);
    });
    it('should auto-parse tsv fields', function() {
      assert.deepEqual(read(tsv, {type:'tsv', parse:'auto'}), parsed);
    });
  });

  describe('dsv', function() {
    var psv = toDelimitedText(data, '|');
    it('should read dsv data', function() {
      assert.deepEqual(read(psv, {type:'dsv', delimiter:'|'}), strings);
      assert.equal(read('', {type:'dsv', delimiter:'|'}), '');
    });
    it('should support delimiter constructor', function() {
      var reader = read.formats.dsv.delimiter('|');
      assert.deepEqual(reader(psv), strings);
    });
    it('should accept header parameter', function() {
      var body = psv.slice(psv.indexOf('\n')+1);
      assert.deepEqual(read(body, {
        type: 'dsv',
        delimiter: '|',
        header: fields
      }), strings);
    });
    it('should parse dsv fields', function() {
      assert.deepEqual(read(psv, {type:'dsv', delimiter:'|', parse:type.annotation(parsed)}), parsed);
    });
    it('should auto-parse dsv fields', function() {
      assert.deepEqual(read(psv, {type:'dsv', delimiter:'|', parse:'auto'}), parsed);
    });
  });

  describe('topojson', function() {
    var world = fs.readFileSync('./test/data/world-110m.json', 'utf8');
    var json = JSON.parse(world);

    it('should read topojson mesh', function() {
      var mesh = read(world, {type:'topojson', mesh: 'countries'});
      var tj = topojson.mesh(json, json.objects['countries']);
      assert.equal(JSON.stringify(tj), JSON.stringify(mesh[0]));
    });

    it('should read topojson feature', function() {
      var feature = read(world, {type:'topojson', feature: 'countries'});
      var tj = topojson.feature(json, json.objects['countries']).features;
      assert.equal(JSON.stringify(tj), JSON.stringify(feature));
    });

    it('should throw error if topojson library unavailable', function() {
      read.formats.topojson.topojson = null;
      assert.throws(function() {
        read(world, {type:'topojson', mesh: 'countries'});
      });
      read.formats.topojson.topojson = topojson;
    });

    it('should throw error if topojson is invalid', function() {
      var data = {objects: {}};
      assert.throws(function() {
        read(data, {type:'topojson', feature: 'countries'});
      });
      assert.throws(function() {
        read(data, {type:'topojson', mesh: 'countries'});
      });
    });

    it('should throw error if topojson parameters are missing', function() {
      assert.throws(function() { read(world, {type:'topojson'}); });
    });
  });

  describe('treejson', function() {
    var flare = fs.readFileSync('./test/data/flare.json', 'utf8');
    var json = JSON.parse(flare);

    it('should read treejson data', function() {
      var data = null;
      assert.doesNotThrow(function() { data = read(flare, {type:'treejson'}); });
      assert.equal(json.name, data[0].name);
      assert.equal(data[0].hasOwnProperty('parent'), true);
      assert.equal(data[0].parent, null);
    });
  });
});
<|endoftext|>


<commit_before>// These are the test files in this dir to be run.
var tests = [
  { path: "simple.pde", tags: ["2D"] },
  { path: "arc-tangent.pde",  tags: ["2D"] },
  { path: "bezier.pde", tags: ["2D"] },
  { path: "ellipse.pde", tags: ["2D"] },
  { path: "piechart.pde", tags: ["2D"] },
  { path: "point-stroke-array-2d.pde", tags: ["2D"] },
  { path: "bezier-ellipse.pde", tags: ["2D"] },
  { path: "curves.pde", tags: ["2D"] },
  { path: "curve.pde", tags: ["2D"] },
  { path: "continuous-curve.pde", tags: ["2D"] },
  { path: "points-lines.pde", tags: ["2D"] },
  { path: "rect-quad.pde", tags: ["2D"] },
  { path: "size-fill-rect.pde", tags: ["2D"] },
  { path: "triangle.pde", tags: ["2D"] },
  { path: "box.pde", tags: ["3D"] },
  { path: "ambientLight_1.pde", tags: ["3D"] },
  { path: "ambientLight_p5test_1.pde", tags: ["3D"] },
  { path: "ambientLight_p5test_2.pde", tags: ["3D"] },
  { path: "ambient_p5test.pde", tags: ["3D"] },
  { path: "directionalLight_p5test_1.pde", tags: ["3D"] },
  { path: "directionalLight_p5test_2.pde", tags: ["3D"] },
  { path: "emissive_p5test.pde", tags: ["3D"] },
  { path: "lightSpecular_p5test.pde", tags: ["3D"] },
  { path: "pointLight_p5test.pde", tags: ["3D"] },
  { path: "shininess_p5test.pde", tags: ["3D"] },
  { path: "specular_p5test.pde", tags: ["3D"] },
  { path: "spotLight_p5test.pde", tags: ["3D"] },
  { path: "createimage.pde", tags: ["2D"] },
  { path: "self-1-success.pde", tags: ["Calibration"] },
  { path: "self-2-fail.pde", tags: ["Calibration"] },
  { path: "self-3-fail.pde", tags: ["Calibration"] },
  { path: "self-4-fail.pde", tags: ["Calibration"] },
  { path: "self-5-success.pde", tags: ["Calibration"] },
  { path: "beginEndShape-2dlines.pde", tags:["endShape2D"] },
  { path: "beginEndShape-2dnoclose.pde", tags:["endShape2D"] },
  { path: "beginEndShape-2dnomod.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dnomodnofill.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dpoints.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dpolygon.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dquads1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dquads2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dquadstrip1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dquadstrip2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtrianglefan1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtrianglefan2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtriangles1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtriangles2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtrianglestrip1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtrianglestrip2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-3dlines.pde", tags:["endShape3D"] },
  { path: "beginEndShape-3dnoclose.pde", tags:["endShape3D"] },
  { path: "beginEndShape-3dnomod.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dnomodnofill.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dpoints.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dquads1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dquads2.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dquadstrip1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dquadstrip2.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtrianglefan1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtrianglefan2.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtriangles1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtriangles2.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtrianglestrip1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtrianglestrip2.pde", tags:["endShape3D"]}
];
<commit_msg>updated ref test to run 3D point tests.<commit_after>// These are the test files in this dir to be run.
var tests = [
  { path: "simple.pde", tags: ["2D"] },
  { path: "arc-tangent.pde",  tags: ["2D"] },
  { path: "bezier.pde", tags: ["2D"] },
  { path: "ellipse.pde", tags: ["2D"] },
  { path: "piechart.pde", tags: ["2D"] },
  { path: "point-stroke-array-2d.pde", tags: ["2D"] },
  { path: "bezier-ellipse.pde", tags: ["2D"] },
  { path: "curves.pde", tags: ["2D"] },
  { path: "curve.pde", tags: ["2D"] },
  { path: "continuous-curve.pde", tags: ["2D"] },
  { path: "points-lines.pde", tags: ["2D"] },
  { path: "rect-quad.pde", tags: ["2D"] },
  { path: "size-fill-rect.pde", tags: ["2D"] },
  { path: "triangle.pde", tags: ["2D"] },
  { path: "point_3D_stroke.pde", tags: ["3D"] },
  { path: "point_3D_strokeWeight.pde", tags: ["3D"] },
  { path: "box.pde", tags: ["3D"] },
  { path: "ambientLight_1.pde", tags: ["3D"] },
  { path: "ambientLight_p5test_1.pde", tags: ["3D"] },
  { path: "ambientLight_p5test_2.pde", tags: ["3D"] },
  { path: "ambient_p5test.pde", tags: ["3D"] },
  { path: "directionalLight_p5test_1.pde", tags: ["3D"] },
  { path: "directionalLight_p5test_2.pde", tags: ["3D"] },
  { path: "emissive_p5test.pde", tags: ["3D"] },
  { path: "lightSpecular_p5test.pde", tags: ["3D"] },
  { path: "pointLight_p5test.pde", tags: ["3D"] },
  { path: "shininess_p5test.pde", tags: ["3D"] },
  { path: "specular_p5test.pde", tags: ["3D"] },
  { path: "spotLight_p5test.pde", tags: ["3D"] },
  { path: "createimage.pde", tags: ["2D"] },
  { path: "self-1-success.pde", tags: ["Calibration"] },
  { path: "self-2-fail.pde", tags: ["Calibration"] },
  { path: "self-3-fail.pde", tags: ["Calibration"] },
  { path: "self-4-fail.pde", tags: ["Calibration"] },
  { path: "self-5-success.pde", tags: ["Calibration"] },
  { path: "beginEndShape-2dlines.pde", tags:["endShape2D"] },
  { path: "beginEndShape-2dnoclose.pde", tags:["endShape2D"] },
  { path: "beginEndShape-2dnomod.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dnomodnofill.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dpoints.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dpolygon.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dquads1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dquads2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dquadstrip1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dquadstrip2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtrianglefan1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtrianglefan2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtriangles1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtriangles2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtrianglestrip1.pde", tags:["endShape2D"]},
  { path: "beginEndShape-2dtrianglestrip2.pde", tags:["endShape2D"]},
  { path: "beginEndShape-3dlines.pde", tags:["endShape3D"] },
  { path: "beginEndShape-3dnoclose.pde", tags:["endShape3D"] },
  { path: "beginEndShape-3dnomod.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dnomodnofill.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dpoints.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dquads1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dquads2.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dquadstrip1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dquadstrip2.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtrianglefan1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtrianglefan2.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtriangles1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtriangles2.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtrianglestrip1.pde", tags:["endShape3D"]},
  { path: "beginEndShape-3dtrianglestrip2.pde", tags:["endShape3D"]}
];
<|endoftext|>