<commit_before>'use strict';

const common = require('../common');
const expect = common.expect;
const faker = common.faker;

const _ = require('lodash');
const moment = require('moment');
const models = require('../../models');

function invokeMethod(instanceParams, method, methodArguments) {
    return models.Task.create(instanceParams).then(function(value) {
        return value[method].apply(value, methodArguments || []);
    }).then(function(value) {
        return value.reload();
    });
}

describe('#fail', function() {

    let task = null;
    let attempts = faker.random.number(10);

    before(function() {
        return invokeMethod({
            queue: faker.lorem.word(),
            body: {},
            attempts: attempts
        }, 'fail').then(function(value) {
            task = value;
        });
    });

    it('should increase number of attempts', function() {
        return expect(task.attempts).to.be.eq(attempts + 1);
    });

    it('should change status', function() {
        return expect(task.status).to.be.eq('failure');
    });

    it('should not change start_at', function() {
        return expect(task.start_at).to.be.null;
    });

    describe('with delay', function() {

        let delay = faker.random.number({min: 100000, max: 999999});

        before(function() {
            return invokeMethod({
                queue: faker.lorem.word(),
                body: {},
                attempts: attempts
            }, 'fail', [delay]).then(function(value) {
                task = value;
            });
        });

        it('should change start_at', function() {
            return expect(task.start_at).to.be.ok;
        });

        it('should change start_at correctly', function() {
            return [
                expect(task.start_at).to.beforeTime(moment().add(delay + 3000, 'ms').toDate()),
                expect(task.start_at).to.afterTime(moment().add(delay - 3000, 'ms').toDate())
            ];
        });

    });

});

describe('#complete', function() {

    let task = null;

    before(function() {
        return invokeMethod({
            queue: faker.lorem.word(),
            body: {}
        }, 'complete').then(function(value) {
            task = value;
        });
    });

    it('should change status', function() {
        return expect(task.status).to.be.eq('done');
    });

});

describe('#work', function() {

    let task = null;
    let nodeId = faker.random.number();

    before(function() {
        return invokeMethod({
            queue: faker.lorem.word(),
            body: {}
        }, 'work', [nodeId]).then(function(value) {
            task = value;
        });
    });

    it('should change status', function() {
        return expect(task.status).to.be.eq('working');
    });

    it('should assign worker_node_id', function() {
        return expect(task.worker_node_id).to.be.eq(nodeId);
    });

    it('should change worker_started_at', function() {
        return expect(task.worker_started_at).to.be.ok;
    });

});

describe('#check', function() {

    let task = null;

    before(function() {
        return invokeMethod({
            queue: faker.lorem.word(),
            body: {}
        }, 'check').then(function(value) {
            task = value;
        });
    });

    it('should change checked_at correctly', function() {
        return [
            expect(task.checked_at).to.beforeTime(moment().add(3000, 'ms').toDate()),
            expect(task.checked_at).to.afterTime(moment().subtract(3000, 'ms').toDate())
        ];
    });

});

describe('.scope', function() {

    describe('.forWork', function() {

        let queue = 'fw-' + faker.lorem.word();
        let nodeId = faker.random.number();
        let otherTasks = [
            // another queue
            {queue: faker.lorem.word(), body: {}},
            // another node
            {queue: queue, node_id: nodeId + 1, body: {}},
            // not pending tasks
            {queue: queue, status: 'done', body: {}},
            {queue: queue, status: 'working', body: {}},
            {queue: queue, status: 'failure', body: {}},
            // future tasks
            {queue: queue, start_at: moment().add(10, 'm').toDate(), body: {}},
            // past tasks
            {queue: queue, finish_at: moment().subtract(10, 'm').toDate(), body: {}}
        ];
        let actualTasks = [
            {queue: queue, body: {}},
            {queue: queue, node_id: nodeId, body: {}},
            {queue: queue, start_at: moment().subtract(10, 'm').toDate(), body: {}},
            {queue: queue, finish_at: moment().add(10, 'm').toDate(), body: {}}
        ];

        before(function() {
            return models.Task.bulkCreate(_.shuffle(_.concat(otherTasks, actualTasks))).then(function() {
                //
            });
        });

        it('should return right tasks', function() {
            return models.Task.scope({
                method: ['forWork', queue, nodeId]
            }).findAll().then(function(rows) {
                expect(rows.length).to.be.eq(actualTasks.length);
                expect(_.map(rows, 'queue')).to.eql(_.times(actualTasks.length, _.constant(queue)));
                expect(_.map(rows, 'status')).to.eql(_.times(actualTasks.length, _.constant('pending')));
            });
        });

    });

});<commit_msg>Remove unnecessary code<commit_after>'use strict';

const common = require('../common');
const expect = common.expect;
const faker = common.faker;

const _ = require('lodash');
const moment = require('moment');
const models = require('../../models');

function invokeMethod(instanceParams, method, methodArguments) {
    return models.Task.create(instanceParams).then(function(value) {
        return value[method].apply(value, methodArguments || []);
    }).then(function(value) {
        return value.reload();
    });
}

describe('#fail', function() {

    let task = null;
    let attempts = faker.random.number(10);

    before(function() {
        return invokeMethod({
            queue: faker.lorem.word(),
            body: {},
            attempts: attempts
        }, 'fail').then(function(value) {
            task = value;
        });
    });

    it('should increase number of attempts', function() {
        return expect(task.attempts).to.be.eq(attempts + 1);
    });

    it('should change status', function() {
        return expect(task.status).to.be.eq('failure');
    });

    it('should not change start_at', function() {
        return expect(task.start_at).to.be.null;
    });

    describe('with delay', function() {

        let delay = faker.random.number({min: 100000, max: 999999});

        before(function() {
            return invokeMethod({
                queue: faker.lorem.word(),
                body: {},
                attempts: attempts
            }, 'fail', [delay]).then(function(value) {
                task = value;
            });
        });

        it('should change start_at', function() {
            return expect(task.start_at).to.be.ok;
        });

        it('should change start_at correctly', function() {
            return [
                expect(task.start_at).to.beforeTime(moment().add(delay + 3000, 'ms').toDate()),
                expect(task.start_at).to.afterTime(moment().add(delay - 3000, 'ms').toDate())
            ];
        });

    });

});

describe('#complete', function() {

    let task = null;

    before(function() {
        return invokeMethod({
            queue: faker.lorem.word(),
            body: {}
        }, 'complete').then(function(value) {
            task = value;
        });
    });

    it('should change status', function() {
        return expect(task.status).to.be.eq('done');
    });

});

describe('#work', function() {

    let task = null;
    let nodeId = faker.random.number();

    before(function() {
        return invokeMethod({
            queue: faker.lorem.word(),
            body: {}
        }, 'work', [nodeId]).then(function(value) {
            task = value;
        });
    });

    it('should change status', function() {
        return expect(task.status).to.be.eq('working');
    });

    it('should assign worker_node_id', function() {
        return expect(task.worker_node_id).to.be.eq(nodeId);
    });

    it('should change worker_started_at', function() {
        return expect(task.worker_started_at).to.be.ok;
    });

});

describe('#check', function() {

    let task = null;

    before(function() {
        return invokeMethod({
            queue: faker.lorem.word(),
            body: {}
        }, 'check').then(function(value) {
            task = value;
        });
    });

    it('should change checked_at correctly', function() {
        return [
            expect(task.checked_at).to.beforeTime(moment().add(3000, 'ms').toDate()),
            expect(task.checked_at).to.afterTime(moment().subtract(3000, 'ms').toDate())
        ];
    });

});

describe('.scope', function() {

    describe('.forWork', function() {

        let queue = 'fw-' + faker.lorem.word();
        let nodeId = faker.random.number();
        let otherTasks = [
            // another queue
            {queue: faker.lorem.word(), body: {}},
            // another node
            {queue: queue, node_id: nodeId + 1, body: {}},
            // not pending tasks
            {queue: queue, status: 'done', body: {}},
            {queue: queue, status: 'working', body: {}},
            {queue: queue, status: 'failure', body: {}},
            // future tasks
            {queue: queue, start_at: moment().add(10, 'm').toDate(), body: {}},
            // past tasks
            {queue: queue, finish_at: moment().subtract(10, 'm').toDate(), body: {}}
        ];
        let actualTasks = [
            {queue: queue, body: {}},
            {queue: queue, node_id: nodeId, body: {}},
            {queue: queue, start_at: moment().subtract(10, 'm').toDate(), body: {}},
            {queue: queue, finish_at: moment().add(10, 'm').toDate(), body: {}}
        ];

        before(function() {
            return models.Task.bulkCreate(_.shuffle(_.concat(otherTasks, actualTasks)));
        });

        it('should return right tasks', function() {
            return models.Task.scope({
                method: ['forWork', queue, nodeId]
            }).findAll().then(function(rows) {
                expect(rows.length).to.be.eq(actualTasks.length);
                expect(_.map(rows, 'queue')).to.eql(_.times(actualTasks.length, _.constant(queue)));
                expect(_.map(rows, 'status')).to.eql(_.times(actualTasks.length, _.constant('pending')));
            });
        });

    });

});
<|endoftext|>


<commit_before>var tap = require('tap');
var Offset = require('../src/offset');

// CCW
var points = [
  [0,0], [0,100],
  [100,100], [100,0], [0,0]
];
var x = -10;

tap.test('polygon.offset', function(t) {

  t.test('data', function(t) {
    t.strictSame(new Offset(points).vertices, points.slice(0, points.length - 1), 'read');
    //t.strictSame(new Offset(points).vertices, points, 'stored');
    t.end();
  });

  t.test('margin', function(t) {
    t.strictSame(new Offset(points).arcSegments(1).margin(5), [[[-5,0],[0,0],[0,-5],[100,-5],[100,0],[105,0],[105,100],[100,100],[100,105],[0,105],[0,100],[-5,100],[-5,0]]], 'normal');
    t.strictSame(new Offset(points).arcSegments(0).margin(5), [ [ [ -5, 0 ],[ 0, 0 ],[ 0, -5 ],[ 100, -5 ],[ 100, 0 ],[ 105, 0 ],[ 105, 100 ],[ 100, 100 ],[ 100, 105 ],[ 0, 105 ],[ 0, 100 ],[ -5, 100 ],[ -5, 0 ] ] ], '0 additional segs');
    t.strictSame(new Offset(points).margin(0), points, 'zero');
    t.end();
  });

  t.test('padding', function(t) {
    t.strictSame(new Offset(points).padding(5), [[[5,5],[95,5],[95,95],[5,95],[5,5]]], 'padding');
    t.strictSame(new Offset(points).padding(0), points, 'zero');
    t.end();
  });

  t.test('adaptive', function(t) {
    t.strictSame(new Offset(points).arcSegments(1).offset(5), [[[-5,0],[0,0],[0,-5],[100,-5],[100,0],[105,0],[105,100],[100,100],[100,105],[0,105],[0,100],[-5,100],[-5,0]]], 'normal');
    t.strictSame(new Offset(points).offset(-5), [[[5,5],[95,5],[95,95],[5,95],[5,5]]], 'padding');
    t.end();
  });

  t.test('line', function(t) {
    t.strictSame(new Offset(points.slice(1,3)).arcSegments(2).offsetLine(5), [ [ [ 0, 95 ], [ 0, 105 ], [ 100, 105 ], [ 100, 95 ], [ 0, 95 ] ] ], 'segment');
    t.strictSame(new Offset(points.slice(1,3)).arcSegments(2).offsetLine(0), points.slice(1, 3), 'segment');
    t.strictSame(new Offset(points.slice(1)).arcSegments(2).offsetLine(5), [[[0,-5],[100,-5],[100,0],[105,0],[105,100],[100,100],[100,105],[0,105],[0,95],[95,95],[95,5],[0,5],[0,-5]]] , 'polyline');
    t.strictSame(new Offset(points.slice(1)).offsetLine(0), points.slice(1), 'zero');
    t.end();
  });

  t.test('point', function(t) {
    t.strictSame(new Offset([0, 0]).offset(5), [[4.045084971874737,2.938926261462366],[1.5450849718747373,4.755282581475767],[-1.5450849718747368,4.755282581475768],[-4.045084971874737,2.9389262614623664],[-5,6.123233995736766e-16],[-4.045084971874737,-2.938926261462365],[-1.5450849718747377,-4.755282581475767],[1.5450849718747361,-4.755282581475768],[4.045084971874736,-2.938926261462367]], 'circle');
    t.strictSame(new Offset([[0, 0]]).offset(5), [[4.045084971874737,2.938926261462366],[1.5450849718747373,4.755282581475767],[-1.5450849718747368,4.755282581475768],[-4.045084971874737,2.9389262614623664],[-5,6.123233995736766e-16],[-4.045084971874737,-2.938926261462365],[-1.5450849718747377,-4.755282581475767],[1.5450849718747361,-4.755282581475768],[4.045084971874736,-2.938926261462367]], 'circle');
    t.end();
  });

  t.end();
});
<commit_msg>platform precision in tests<commit_after>var tap = require('tap');
var Offset = require('../src/offset');

// CCW
var points = [
  [0,0], [0,100],
  [100,100], [100,0], [0,0]
];
var x = -10;

tap.test('polygon.offset', function(t) {

  t.test('data', function(t) {
    t.strictSame(new Offset(points).vertices, points.slice(0, points.length - 1), 'read');
    //t.strictSame(new Offset(points).vertices, points, 'stored');
    t.end();
  });

  t.test('margin', function(t) {
    t.strictSame(new Offset(points).arcSegments(1).margin(5), [[[-5,0],[0,0],[0,-5],[100,-5],[100,0],[105,0],[105,100],[100,100],[100,105],[0,105],[0,100],[-5,100],[-5,0]]], 'normal');
    t.strictSame(new Offset(points).arcSegments(0).margin(5), [ [ [ -5, 0 ],[ 0, 0 ],[ 0, -5 ],[ 100, -5 ],[ 100, 0 ],[ 105, 0 ],[ 105, 100 ],[ 100, 100 ],[ 100, 105 ],[ 0, 105 ],[ 0, 100 ],[ -5, 100 ],[ -5, 0 ] ] ], '0 additional segs');
    t.strictSame(new Offset(points).margin(0), points, 'zero');
    t.end();
  });

  t.test('padding', function(t) {
    t.strictSame(new Offset(points).padding(5), [[[5,5],[95,5],[95,95],[5,95],[5,5]]], 'padding');
    t.strictSame(new Offset(points).padding(0), points, 'zero');
    t.end();
  });

  t.test('adaptive', function(t) {
    t.strictSame(new Offset(points).arcSegments(1).offset(5), [[[-5,0],[0,0],[0,-5],[100,-5],[100,0],[105,0],[105,100],[100,100],[100,105],[0,105],[0,100],[-5,100],[-5,0]]], 'normal');
    t.strictSame(new Offset(points).offset(-5), [[[5,5],[95,5],[95,95],[5,95],[5,5]]], 'padding');
    t.end();
  });

  t.test('line', function(t) {
    t.strictSame(new Offset(points.slice(1,3)).arcSegments(2).offsetLine(5), [ [ [ 0, 95 ], [ 0, 105 ], [ 100, 105 ], [ 100, 95 ], [ 0, 95 ] ] ], 'segment');
    t.strictSame(new Offset(points.slice(1,3)).arcSegments(2).offsetLine(0), points.slice(1, 3), 'segment');
    t.strictSame(new Offset(points.slice(1)).arcSegments(2).offsetLine(5), [[[0,-5],[100,-5],[100,0],[105,0],[105,100],[100,100],[100,105],[0,105],[0,95],[95,95],[95,5],[0,5],[0,-5]]] , 'polyline');
    t.strictSame(new Offset(points.slice(1)).offsetLine(0), points.slice(1), 'zero');
    t.end();
  });

  t.test('point', function(t) {
    t.same(new Offset([0, 0]).offset(5), [[4.045084971874737,2.938926261462366],[1.5450849718747373,4.755282581475767],[-1.5450849718747368,4.755282581475768],[-4.045084971874737,2.9389262614623664],[-5,6.123233995736766e-16],[-4.045084971874737,-2.938926261462365],[-1.5450849718747377,-4.755282581475767],[1.5450849718747361,-4.755282581475768],[4.045084971874736,-2.938926261462367]], 'circle');
    t.same(new Offset([[0, 0]]).offset(5), [[4.045084971874737,2.938926261462366],[1.5450849718747373,4.755282581475767],[-1.5450849718747368,4.755282581475768],[-4.045084971874737,2.9389262614623664],[-5,6.123233995736766e-16],[-4.045084971874737,-2.938926261462365],[-1.5450849718747377,-4.755282581475767],[1.5450849718747361,-4.755282581475768],[4.045084971874736,-2.938926261462367]], 'circle');
    t.end();
  });

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


<commit_before>'use strict';

var vows = require('vows');
var assert = require('assert');

var fs = require('fs');
var ffs = require('final-fs');

var XQLint = require('../lib/XQLint').XQLint;

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

var batch = {};
var files = ffs.readdirRecursiveSync('test/queries', true);
files.forEach(function(file){
    batch[file] = function(){
        var linter = new XQLint(file, fs.readFileSync('test/queries/' + file, 'UTF-8'));
        var syntaxError = linter.hasSyntaxError();
        assert.equal(syntaxError, false);
        if(syntaxError) {
            console.error(linter.getMarkers()[0].message);
        }
    };
});
vows.describe('Test Parser').addBatch(batch).export(module);
<commit_msg>Update test suite.<commit_after>'use strict';

var vows = require('vows');
var assert = require('assert');

var fs = require('fs');
var ffs = require('final-fs');

var XQLint = require('../lib/XQLint').XQLint;

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

var batch = {};
var files = ffs.readdirRecursiveSync('test/queries', true);
files.forEach(function(file){
    batch[file] = function(){
        var linter = new XQLint(file, fs.readFileSync('test/queries/' + file, 'UTF-8'));
        var syntaxError = linter.hasSyntaxError();
        if(syntaxError) {
            assert.equal(syntaxError, false, linter.getMarkers()[0].message);
        }
    };
});
vows.describe('Test Parser').addBatch(batch).export(module);
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var it = require('mocha').it;

var Collision = require('../index.js');
var Response = require('../index.js').Response;
var Circle = require('gm2-circle');
var Vector2 = require('gm2-vector2');

module.exports = function () {

    it('detects collisions', function () {

        var point = new Vector2(5,5);
        var circle = new Circle(10);

        var collision = Collision.pointCircle(point, circle);

        expect(collision).to.be.true;
    });

    it('detects non collisions', function () {

        var point = new Vector2(10,10);
        var circle = new Circle(10);

        var collision = Collision.pointCircle(point, circle);

        expect(collision).to.be.false;
    });

    it('sets response properties', function () {

        var point = new Vector2(5,5);
        var circle = new Circle(10);

        var response = new Response();

        var collided = Collision.pointCircle(point, circle, response);

        expect(collided).to.be.true;
        expect(response.point.x).to.equal(7.071067811865475);
        expect(response.point.y).to.equal(7.071067811865475);
        expect(response.normal.x).to.equal(0.7071067811865475);
        expect(response.normal.y).to.equal(0.7071067811865475);
        expect(response.depth).to.equal(2.9289321881345245);
    });

};
<commit_msg>update pointCircle<commit_after>var expect = require('chai').expect;
var it = require('mocha').it;

var Collision = require('../index.js');
var Response = require('../index.js').Response;
var Circle = require('gm2-circle');
var Vector2 = require('gm2-vector2');

module.exports = function () {

    it('detects collisions', function () {

        var point = new Vector2(5,5);
        var circle = new Circle(10);

        var collision = Collision.pointCircle(point, circle);

        expect(collision).to.be.true;
    });

    it('detects non collisions', function () {

        var point = new Vector2(10,10);
        var circle = new Circle(10);

        var collision = Collision.pointCircle(point, circle);

        expect(collision).to.be.false;
    });

    // 'on the edge' is false
    it('handles edge cases', function () {

        var point = new Vector2(5,0);
        var circle = new Circle(5);

        var collision = Collision.pointCircle(point, circle);

        expect(collision).to.be.false;
    });

    it('sets response properties', function () {

        var point = new Vector2(5,5);
        var circle = new Circle(10);

        var response = new Response();

        var collided = Collision.pointCircle(point, circle, response);

        expect(collided).to.be.true;
        expect(response.point.x).to.equal(7.071067811865475);
        expect(response.point.y).to.equal(7.071067811865475);
        expect(response.normal.x).to.equal(0.7071067811865475);
        expect(response.normal.y).to.equal(0.7071067811865475);
        expect(response.depth).to.equal(2.9289321881345245);
    });

};
<|endoftext|>


<commit_before>var test = require('tape')

var CHR = require('chr')

test('a ==> b', function (t) {
  var chr = new CHR()
  chr('a ==> b')

  chr.a()
  t.equal(chr.Store.length, 2)

  t.end()
})

test('a ==> b, c', function (t) {
  var chr = new CHR()
  chr('a ==> b, c')

  chr.a()
  t.equal(chr.Store.length, 3)

  t.end()
})

test('a, b ==> c', function (t) {
  var chr = new CHR()
  chr('a, b ==> c')

  chr.a()
  t.equal(chr.Store.length, 1)

  chr.c()
  t.equal(chr.Store.length, 2)

  chr.b()
  t.equal(chr.Store.length, 4)

  t.end()
})

test('a ==> b', function (t) {
  var chr = new CHR()
  chr('a ==> b')

  chr.a()
  chr.a()
  t.equal(chr.Store.length, 4)

  t.end()
})
<commit_msg>Fetch tests from fnogatz/CHR.js<commit_after>var test = require('tape')

var CHR = require('chr')

test('a ==> b', function (t) {
  var chr = new CHR()
  chr('a ==> b')

  chr.a()
  t.equal(chr.Store.length, 2)

  t.end()
})

test('a ==> b, c', function (t) {
  var chr = new CHR()
  chr('a ==> b, c')

  chr.a()
  t.equal(chr.Store.length, 3)

  t.end()
})

test('a, b ==> c', function (t) {
  var chr = new CHR()
  chr('a, b ==> c')

  chr.a()
  t.equal(chr.Store.length, 1)

  chr.c()
  t.equal(chr.Store.length, 2)

  chr.b()
  t.equal(chr.Store.length, 4)

  t.end()
})

test('a ==> b', function (t) {
  var chr = new CHR()
  chr('a ==> b')

  chr.a()
  chr.a()
  t.equal(chr.Store.length, 4)

  t.end()
})

test('a(N) ==> b(N+1,N+2)', function (t) {
  var chr = new CHR()
  chr('a(N) ==> b(N+1,N+2)')

  chr.a(1)
  chr.a(2)
  t.equal(chr.Store.length, 4)

  t.end()
})

test('a(N) ==> N <= 4 | a(N+1)', function (t) {
  var chr = new CHR()
  chr('a(N) ==> N <= 4 | a(N+1)')

  chr.a(1)
  t.equal(chr.Store.length, 5)

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


<commit_before>describe('reword.js', function() {
	var messages = {
		'msg1': 'Test message 1',
		'msg2': 'Test message 2',
		'msg-alt': 'Test alt message',
		'msg-title': 'Test title message'
	};
	var options = {
		'messages': messages
	};

	describe('static content', function() {
		beforeEach(function() {
			$(document.body).append('
');
		});

		afterEach(function() {
			$('.test-element').remove();
		});

		describe('reword', function() {
			it('jquery plugin', function() {
				expect(typeof $.fn.reword).toBe('function');
			});

			it('jquery chaining', function() {
				expect($('.test-element').reword(options).hasClass('test-element')).toBe(true);
			});

			it('no options', function() {
				expect($('.test-element').reword().hasClass('test-element')).toBe(true);
			});
		});

		describe('place messages', function() {
			it('Puts data-i18n with text', function() {
				$(document.body).reword(options);
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('alt text', function() {
				$(document.body).append('');
				$(document.body).reword(options);
				expect($('img.test-element').attr('alt')).toEqual('Test alt message');
			});

			it('title text', function() {
				$(document.body).append('');
				$(document.body).reword(options);
				expect($('img.test-element').attr('title')).toEqual('Test title message');
			});

			it('on specific element places text', function() {
				$('.test-element').reword(options);
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('Two languages message', function() {
				var frOptions = $.extend(options);
				frOptions.messages = {
					'msg1': {
						'en': 'Test message 1',
						'fr': 'Essai Message 1'
					}
				};
				$('.test-element').attr('lang', 'fr').reword(frOptions);
				expect($('.test-element').text()).toEqual('Essai Message 1');
			});

			it('falls back to default - not an object', function() {
				var frOptions = $.extend(options);
				frOptions.messages = {
					'msg1': 'Test message 1'
				};
				$('.test-element').attr('lang', 'fr');
				$('.test-element').reword(frOptions);
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('falls back to default - no object property', function() {
				var newOptions = $.extend(options);
				newOptions.messages = {
					'msg1': {
						'en': 'Test message 1'
					}
				};
				$('.test-element').attr('lang', 'fr');
				$('.test-element').reword(newOptions);
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('data-alt-i18n languages', function() {
				var frOptions = $.extend(options);
				frOptions.messages = {
					'msg1': {
						'en': 'Test message 1',
						'fr': 'Essai Message 1'
					}
				};
				$('.test-element').attr('lang', 'fr').data('alt-i18n', 'msg1').reword(frOptions);
				expect($('.test-element').attr('alt')).toEqual('Essai Message 1');
			});
		});

		describe('place message dynamically', function() {
			it('changes as data-i18n changes', function() {
				$(document.body).reword(options);
				$('.test-element').data('i18n', 'msg2');
				expect($('.test-element').data('i18n')).toEqual('msg2');
				expect($('.test-element').text()).toEqual('Test message 2');
			});

			it('change to other data-attr does nothing', function() {
				$(document.body).reword(options);
				$('.test-element').data('test', 'msg2');
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('changes as data-alt-i18n changes', function() {
				$(document.body).reword(options);
				$('.test-element').data('alt-i18n', 'msg2');
				expect($('.test-element').data('alt-i18n')).toEqual('msg2');
				expect($('.test-element').attr('alt')).toEqual('Test message 2');
			});
		});
	});

	describe('async tests', function() {
		var originalTimeout, originalAjax;
		beforeEach(function() {
			originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
			jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
			$(document.body).append('
');
			originalAjax = $.ajax;
			$.ajax = function() {
				defer = $.Deferred();
				defer.promise({});
				defer.resolve({
					"msg1": "Test ajax message 1",
					"msg2": "Test ajax message 2",
					"msg-alt": "Test ajax alt message"
				});
				return defer;
			};
		});

		afterEach(function() {
			jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
			$('.async-test-element').remove();
			$.ajax = originalAjax;
		});

		describe('MutationObserver - ', function() {
			it('appending html places messages', function(done) {
				$(document.body).reword(options)
					.on('reword', function appendCallback(event, element) {
						if ($(element).attr('id') == 'appendedDiv') {
							expect($('#appendedDiv').text()).toEqual('Test message 2');
							done();
							$(document.body).off('reword', appendCallback);
						}
					})
					.append('
');
			});

			it('prepending html places messages', function(done) {
				$(document.body).reword(options)
					.on('reword', function prependCallback(event, element) {
						if ($(element).attr('id') == 'prependedDiv') {
							expect($('#prependedDiv').text()).toEqual('Test message 2');
							done();
							$(document.body).off('reword', prependCallback);
						}
					})
					.prepend('
');
			});
		});

		describe('AJAX JSON messages - ', function() {
			it('load messages via AJAX', function(done) {
				$(document.body).reword({
					'url': 'messages.json'
				}).on('reword', function rewordCallback(event, element) {
					expect($('.async-test-element').text()).toEqual('Test ajax message 1');
					done();
					$(document.body).off('reword', rewordCallback);
				});
			});
		});
	});
});
<commit_msg>fixed missing html lang attr in karma<commit_after>describe('reword.js', function() {
	var messages = {
		'msg1': 'Test message 1',
		'msg2': 'Test message 2',
		'msg-alt': 'Test alt message',
		'msg-title': 'Test title message'
	};
	var options = {
		'messages': messages
	};

	describe('static content', function() {
		beforeEach(function() {
			$(document.body).append('
');
			$('html').attr('lang', 'en');
		});

		afterEach(function() {
			$('.test-element').remove();
		});

		describe('reword', function() {
			it('jquery plugin', function() {
				expect(typeof $.fn.reword).toBe('function');
			});

			it('jquery chaining', function() {
				expect($('.test-element').reword(options).hasClass('test-element')).toBe(true);
			});

			it('no options', function() {
				expect($('.test-element').reword().hasClass('test-element')).toBe(true);
			});
		});

		describe('place messages', function() {
			it('Puts data-i18n with text', function() {
				$(document.body).reword(options);
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('alt text', function() {
				$(document.body).append('');
				$(document.body).reword(options);
				expect($('img.test-element').attr('alt')).toEqual('Test alt message');
			});

			it('title text', function() {
				$(document.body).append('');
				$(document.body).reword(options);
				expect($('img.test-element').attr('title')).toEqual('Test title message');
			});

			it('on specific element places text', function() {
				$('.test-element').reword(options);
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('Two languages message', function() {
				var frOptions = $.extend(options);
				frOptions.messages = {
					'msg1': {
						'en': 'Test message 1',
						'fr': 'Essai Message 1'
					}
				};
				$('.test-element').attr('lang', 'fr').reword(frOptions);
				expect($('.test-element').text()).toEqual('Essai Message 1');
			});

			it('falls back to default - not an object', function() {
				var frOptions = $.extend(options);
				frOptions.messages = {
					'msg1': 'Test message 1'
				};
				$('.test-element').attr('lang', 'fr');
				$('.test-element').reword(frOptions);
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('falls back to default - no object property', function() {
				var newOptions = $.extend(options);
				newOptions.messages = {
					'msg1': {
						'en': 'Test message 1'
					}
				};
				$('.test-element').attr('lang', 'fr');
				$('.test-element').reword(newOptions);
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('data-alt-i18n languages', function() {
				var frOptions = $.extend(options);
				frOptions.messages = {
					'msg1': {
						'en': 'Test message 1',
						'fr': 'Essai Message 1'
					}
				};
				$('.test-element').attr('lang', 'fr').data('alt-i18n', 'msg1').reword(frOptions);
				expect($('.test-element').attr('alt')).toEqual('Essai Message 1');
			});
		});

		describe('place message dynamically', function() {
			it('changes as data-i18n changes', function() {
				$(document.body).reword(options);
				$('.test-element').data('i18n', 'msg2');
				expect($('.test-element').data('i18n')).toEqual('msg2');
				expect($('.test-element').text()).toEqual('Test message 2');
			});

			it('change to other data-attr does nothing', function() {
				$(document.body).reword(options);
				$('.test-element').data('test', 'msg2');
				expect($('.test-element').text()).toEqual('Test message 1');
			});

			it('changes as data-alt-i18n changes', function() {
				$(document.body).reword(options);
				$('.test-element').data('alt-i18n', 'msg2');
				expect($('.test-element').data('alt-i18n')).toEqual('msg2');
				expect($('.test-element').attr('alt')).toEqual('Test message 2');
			});
		});
	});

	describe('async tests', function() {
		var originalTimeout, originalAjax;
		beforeEach(function() {
			originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
			jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
			$(document.body).append('
');
			originalAjax = $.ajax;
			$.ajax = function() {
				defer = $.Deferred();
				defer.promise({});
				defer.resolve({
					"msg1": "Test ajax message 1",
					"msg2": "Test ajax message 2",
					"msg-alt": "Test ajax alt message"
				});
				return defer;
			};
		});

		afterEach(function() {
			jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
			$('.async-test-element').remove();
			$.ajax = originalAjax;
		});

		describe('MutationObserver - ', function() {
			it('appending html places messages', function(done) {
				$(document.body).reword(options)
					.on('reword', function appendCallback(event, element) {
						if ($(element).attr('id') == 'appendedDiv') {
							expect($('#appendedDiv').text()).toEqual('Test message 2');
							done();
							$(document.body).off('reword', appendCallback);
						}
					})
					.append('
');
			});

			it('prepending html places messages', function(done) {
				$(document.body).reword(options)
					.on('reword', function prependCallback(event, element) {
						if ($(element).attr('id') == 'prependedDiv') {
							expect($('#prependedDiv').text()).toEqual('Test message 2');
							done();
							$(document.body).off('reword', prependCallback);
						}
					})
					.prepend('
');
			});
		});

		describe('AJAX JSON messages - ', function() {
			it('load messages via AJAX', function(done) {
				$(document.body).reword({
					'url': 'messages.json'
				}).on('reword', function rewordCallback(event, element) {
					expect($('.async-test-element').text()).toEqual('Test ajax message 1');
					done();
					$(document.body).off('reword', rewordCallback);
				});
			});
		});
	});
});
<|endoftext|>


<commit_before><commit_msg>Remove empty label.js<commit_after><|endoftext|>


<commit_before>var buster = require("buster");
var assert = buster.assert;
var refute = buster.refute;

var bCaptureServer = require("../lib/buster-capture-server");
var bCaptureServerSess = require("../lib/session");
var http = require("http");
var h = require("./test-helper");

buster.testCase("server", {
    setUp: function (done) {
        this.httpServer = http.createServer(function (req, res) {
            res.writeHead(h.NO_RESPONSE_STATUS_CODE); res.end();
        });
        this.httpServer.listen(h.SERVER_PORT, done);

        this.s = bCaptureServer.createServer();
        this.s.attach(this.httpServer);

        this.c = bCaptureServer.createServerClient({
            host: "0.0.0.0",
            port: h.SERVER_PORT,
            fayeClient: this.s.bayeuxServer.getClient()
        });
    },

    tearDown: function (done) {
        this.httpServer.on("close", done);
        this.httpServer.close();
        this.c.disconnect();
    },

    "should create new session successfully": function (done) {
        this.c.createSession({}, h.mockFayeAdapter()).then(
            done(function (sess) {
                assertIsSerializedSession(sess);
            })
        );
    },

    "should not create invalid session": function (done) {
        this.c.createSession({unknownProperty: true}, h.mockFayeAdapter()).then(
            function () {},
            done(function (err) {
                assert.match(err.message, "unknown property");
            })
        );
    },

    "emits event when session queue emits slave:captured": function (done) {
        this.c.on("slave:captured", done(function (e) {
            assert.equals(e, "foo");
        }));

        this.s.sessionQueue.emit("slave:captured", "foo");
    },

    "emits event when session queue emits slave:freed": function (done) {
        this.c.on("slave:freed", done(function (e) {
            assert.equals(e, "foo");
        }));

        this.s.sessionQueue.emit("slave:freed", "foo");
    },

    "should create new slave via HTTP": function (done) {
        var slave = {prisonPath: "/foo"};
        this.stub(this.s, "_createSlave").returns(slave);

        h.request({path: "/capture", method: "GET"}, done(function (res, body) {
            assert.equals(res.statusCode, 302);
            assert.equals(res.headers["location"], "/foo");
        })).end();
    },

    "creating new slave adds it to queue and attaches it": function () {
        this.stub(this.s.sessionQueue, "addSlave");
        this.stub(this.s, "_attachSlave");
        this.s._createSlave();
        assert.calledOnce(this.s.sessionQueue.addSlave);
        assert.calledOnce(this.s._attachSlave);
    },

    "attaching slave": function () {
        var slave = {attach: this.spy()};
        this.s._attachSlave(slave);
        assert(slave.attach.calledOnce);
        assert.same(slave.attach.getCall(0).args[0], this.s._httpServer);
    },

    "should list cache via HTTP": function (done) {
        var resources = [{foo: "bar"}]
        this.stub(this.s._resourceCache, "resourceVersions").returns(resources);

        h.request({path: "/resources"}, done(function (res, body) {
            assert.equals(res.statusCode, 200);
            assert.equals(JSON.parse(body), resources);
        })).end();
    },

    "// should fail if attempting to load uncached items": function () {
    },

    "// should not send cached resources to server": function (done) {
    }
});

function assertIsSerializedSession(obj) {
    assert(obj.id);
    assert(obj.resourcesPath);
    assert(obj.messagingPath);
}<commit_msg>No need to pass a daye adapter to createSession anymore.<commit_after>var buster = require("buster");
var assert = buster.assert;
var refute = buster.refute;

var bCaptureServer = require("../lib/buster-capture-server");
var bCaptureServerSess = require("../lib/session");
var http = require("http");
var h = require("./test-helper");

buster.testCase("server", {
    setUp: function (done) {
        this.httpServer = http.createServer(function (req, res) {
            res.writeHead(h.NO_RESPONSE_STATUS_CODE); res.end();
        });
        this.httpServer.listen(h.SERVER_PORT, done);

        this.s = bCaptureServer.createServer();
        this.s.attach(this.httpServer);

        this.c = bCaptureServer.createServerClient({
            host: "0.0.0.0",
            port: h.SERVER_PORT,
            fayeClient: this.s.bayeuxServer.getClient()
        });
    },

    tearDown: function (done) {
        this.httpServer.on("close", done);
        this.httpServer.close();
        this.c.disconnect();
    },

    "should create new session successfully": function (done) {
        this.c.createSession({}).then(
            done(function (sess) {
                assertIsSerializedSession(sess);
            })
        );
    },

    "should not create invalid session": function (done) {
        this.c.createSession({unknownProperty: true}).then(
            function () {},
            done(function (err) {
                assert.match(err.message, "unknown property");
            })
        );
    },

    "emits event when session queue emits slave:captured": function (done) {
        this.c.on("slave:captured", done(function (e) {
            assert.equals(e, "foo");
        }));

        this.s.sessionQueue.emit("slave:captured", "foo");
    },

    "emits event when session queue emits slave:freed": function (done) {
        this.c.on("slave:freed", done(function (e) {
            assert.equals(e, "foo");
        }));

        this.s.sessionQueue.emit("slave:freed", "foo");
    },

    "should create new slave via HTTP": function (done) {
        var slave = {prisonPath: "/foo"};
        this.stub(this.s, "_createSlave").returns(slave);

        h.request({path: "/capture", method: "GET"}, done(function (res, body) {
            assert.equals(res.statusCode, 302);
            assert.equals(res.headers["location"], "/foo");
        })).end();
    },

    "creating new slave adds it to queue and attaches it": function () {
        this.stub(this.s.sessionQueue, "addSlave");
        this.stub(this.s, "_attachSlave");
        this.s._createSlave();
        assert.calledOnce(this.s.sessionQueue.addSlave);
        assert.calledOnce(this.s._attachSlave);
    },

    "attaching slave": function () {
        var slave = {attach: this.spy()};
        this.s._attachSlave(slave);
        assert(slave.attach.calledOnce);
        assert.same(slave.attach.getCall(0).args[0], this.s._httpServer);
    },

    "should list cache via HTTP": function (done) {
        var resources = [{foo: "bar"}]
        this.stub(this.s._resourceCache, "resourceVersions").returns(resources);

        h.request({path: "/resources"}, done(function (res, body) {
            assert.equals(res.statusCode, 200);
            assert.equals(JSON.parse(body), resources);
        })).end();
    },

    "// should fail if attempting to load uncached items": function () {
    },

    "// should not send cached resources to server": function (done) {
    }
});

function assertIsSerializedSession(obj) {
    assert(obj.id);
    assert(obj.resourcesPath);
    assert(obj.messagingPath);
}<|endoftext|>


<commit_before>require('mocha');
require('http');
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const request = chai.request;

const app = require(__dirname + '/../index.js');

describe('testing routes', () => {
  before(() => {
      app.router.get('/sloth', (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write('GET method hit on /sloth');
        res.end();
      })
      .post('/sloth', (req, res) => {
        req.on('data', (data) => {
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.write(data);
          res.end();
        });
      })
      .put('/sloth', (req, res) => {
        req.on('data', (data) => {
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.write(data);
          res.end();
        });
      })
      .patch('/sloth', (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write('PATCH method hit on /sloth');
        res.end();
      })
      .delete('/sloth', (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write('DELETE method hit on /sloth');
        res.end();
      });
      app.server(6265);
  });
  it('Successfully handle GET request', (done) => {
    request('localhost:6265')
      .get('/sloth')
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('GET method hit');
        done();
      });
  });
  it('Successfully handle POST request', (done) => {
    request('localhost:6265')
      .post('/sloth')
      .send({ 'Name': 'Fur' })
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('Fur');
        done();
      });
  });
  it('Successfully handle PUT request', (done) => {
    request('localhost:6265')
      .put('/sloth')
      .send({ 'Name': 'Ball' })
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('Ball');
        done();
      });
  });
  it('Successfully handle PATCH request', (done) => {
    request('localhost:6265')
      .patch('/sloth')
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('PATCH method hit');
        done();
      });
  });
  it('Successfully handle DELETE request', (done) => {
    request('localhost:6265')
      .delete('/sloth')
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('DELETE method hit');
        done();
      });
  });
});
<commit_msg>closing server after testing<commit_after>require('mocha');
require('http');
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const request = chai.request;

const app = require(__dirname + '/../index.js');

describe('testing routes', () => {
  before(() => {
      app.router.get('/sloth', (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write('GET method hit on /sloth');
        res.end();
      })
      .post('/sloth', (req, res) => {
        req.on('data', (data) => {
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.write(data);
          res.end();
        });
      })
      .put('/sloth', (req, res) => {
        req.on('data', (data) => {
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.write(data);
          res.end();
        });
      })
      .patch('/sloth', (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write('PATCH method hit on /sloth');
        res.end();
      })
      .delete('/sloth', (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write('DELETE method hit on /sloth');
        res.end();
      });
      app.server(6265);
  });

  after((done) => {
    app.close();
    done();
  });

  it('Successfully handle GET request', (done) => {
    request('localhost:6265')
      .get('/sloth')
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('GET method hit');
        done();
      });
  });

  it('Successfully handle POST request', (done) => {
    request('localhost:6265')
      .post('/sloth')
      .send({ 'Name': 'Fur' })
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('Fur');
        done();
      });
  });

  it('Successfully handle PUT request', (done) => {
    request('localhost:6265')
      .put('/sloth')
      .send({ 'Name': 'Ball' })
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('Ball');
        done();
      });
  });

  it('Successfully handle PATCH request', (done) => {
    request('localhost:6265')
      .patch('/sloth')
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('PATCH method hit');
        done();
      });
  });

  it('Successfully handle DELETE request', (done) => {
    request('localhost:6265')
      .delete('/sloth')
      .end((req, res) => {
        expect(res).to.have.status(200);
        expect(res.text).to.contain('DELETE method hit');
        done();
      });
  });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var assert = require('assert');
var source = require('../lib/source');

describe('source remote', function() {
    it('loads', function(done) {
        source({id:'mapbox://mapbox.mapbox-streets-v2'}, function(err, source) {
            assert.ifError(err);
            assert.equal('MapBox Streets', source.data.name);
            assert.equal(0, source.data.minzoom);
            assert.equal(14, source.data.maxzoom);
            assert.ok(!!source.project);
            done();
        });
    });
    it('loads legacy mbstreets', function(done) {
        source({id:'mbstreets'}, function(err, source) {
            assert.ifError(err);
            assert.equal('MapBox Streets', source.data.name);
            assert.equal(0, source.data.minzoom);
            assert.equal(14, source.data.maxzoom);
            done();
        });
    });
    it('error bad protocol', function(done) {
        source({id:'http://www.google.com'}, function(err, source) {
            assert.ok(err);
            assert.equal('Unsupported source protocol', err.message);
            done();
        });
    });
    it('noop remote write', function(done) {
        source({id:'mapbox://mapbox.mapbox-streets-v2', data:{}}, function(err, source) {
            assert.ifError(err);
            done();
        });
    });
});

describe('source local', function() {
    var tmp = '/tmp/tm2-source-' + (+new Date);
    var data = {
        name: 'Test source',
        attribution: '© John Doe 2013.',
        minzoom: 0,
        maxzoom: 6,
        Layer: [ {
            id: 'box',
            name: 'box',
            description: '',
            srs: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over',
            properties: {
                'buffer-size': 0,
                minzoom: 0,
                maxzoom: 6
            },
            Datasource: {
                file: __dirname + '/fixtures-localsource/10m-900913-bounding-box.shp',
                type: 'shape'
            }
        } ]
    };
    after(function(done) {
        setTimeout(function() {
            ['data.xml','data.yml'].forEach(function(file) {
                try { fs.unlinkSync(tmp + '/' + file) } catch(err) {};
            });
            try { fs.rmdirSync(tmp) } catch(err) {};
            try { fs.unlinkSync(tmp + '.tm2z') } catch(err) {};
            done();
        }, 250);
    });
    it('loads', function(done) {
        source({id:__dirname + '/fixtures-localsource'}, function(err, source) {
            assert.ifError(err);
            assert.equal('Test source', source.data.name);
            assert.equal(0, source.data.minzoom);
            assert.equal(6, source.data.maxzoom);
            assert.ok(!!source.project);
            done();
        });
    });
    it('saves source in memory', function(done) {
        source({id:'tmp-1234', data:data}, function(err, source) {
            assert.ifError(err);
            assert.ok(source);
            done();
        });
    });
    it('saves source to disk', function(done) {
        source({id:tmp, data:data, perm:true}, function(err, source) {
            assert.ifError(err);
            assert.ok(source);
            assert.ok(/maxzoom: 6/.test(fs.readFileSync(tmp + '/data.yml', 'utf8')), 'saves data.yml');
            assert.ok(/<Map srs/.test(fs.readFileSync(tmp + '/data.xml', 'utf8')), 'saves data.xml');
            // This setTimeout is here because thumbnail generation on save
            // is an optimistic operation (e.g. callback does not wait for it
            // to complete).
            setTimeout(function() {
                assert.ok(fs.existsSync(tmp + '/.thumb.png'), 'saves thumb');
                done();
            }, 1000);
        });
    });
});
<commit_msg>Update tests.<commit_after>var fs = require('fs');
var path = require('path');
var assert = require('assert');
var source = require('../lib/source');

describe('source remote', function() {
    it('loads', function(done) {
        source({id:'mapbox://mapbox.mapbox-streets-v2'}, function(err, source) {
            assert.ifError(err);
            assert.equal('MapBox Streets V2', source.data.name);
            assert.equal(0, source.data.minzoom);
            assert.equal(14, source.data.maxzoom);
            assert.ok(!!source.project);
            done();
        });
    });
    it('loads legacy mbstreets', function(done) {
        source({id:'mbstreets'}, function(err, source) {
            assert.ifError(err);
            assert.equal('MapBox Streets V2', source.data.name);
            assert.equal(0, source.data.minzoom);
            assert.equal(14, source.data.maxzoom);
            done();
        });
    });
    it('error bad protocol', function(done) {
        source({id:'http://www.google.com'}, function(err, source) {
            assert.ok(err);
            assert.equal('Unsupported source protocol', err.message);
            done();
        });
    });
    it('noop remote write', function(done) {
        source({id:'mapbox://mapbox.mapbox-streets-v2', data:{}}, function(err, source) {
            assert.ifError(err);
            done();
        });
    });
});

describe('source local', function() {
    var tmp = '/tmp/tm2-source-' + (+new Date);
    var data = {
        name: 'Test source',
        attribution: '© John Doe 2013.',
        minzoom: 0,
        maxzoom: 6,
        Layer: [ {
            id: 'box',
            name: 'box',
            description: '',
            srs: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over',
            properties: {
                'buffer-size': 0,
                minzoom: 0,
                maxzoom: 6
            },
            Datasource: {
                file: __dirname + '/fixtures-localsource/10m-900913-bounding-box.shp',
                type: 'shape'
            }
        } ]
    };
    after(function(done) {
        setTimeout(function() {
            ['data.xml','data.yml'].forEach(function(file) {
                try { fs.unlinkSync(tmp + '/' + file) } catch(err) {};
            });
            try { fs.rmdirSync(tmp) } catch(err) {};
            try { fs.unlinkSync(tmp + '.tm2z') } catch(err) {};
            done();
        }, 250);
    });
    it('loads', function(done) {
        source({id:__dirname + '/fixtures-localsource'}, function(err, source) {
            assert.ifError(err);
            assert.equal('Test source', source.data.name);
            assert.equal(0, source.data.minzoom);
            assert.equal(6, source.data.maxzoom);
            assert.ok(!!source.project);
            done();
        });
    });
    it('saves source in memory', function(done) {
        source({id:'tmp-1234', data:data}, function(err, source) {
            assert.ifError(err);
            assert.ok(source);
            done();
        });
    });
    it('saves source to disk', function(done) {
        source({id:tmp, data:data, perm:true}, function(err, source) {
            assert.ifError(err);
            assert.ok(source);
            assert.ok(/maxzoom: 6/.test(fs.readFileSync(tmp + '/data.yml', 'utf8')), 'saves data.yml');
            assert.ok(/<Map srs/.test(fs.readFileSync(tmp + '/data.xml', 'utf8')), 'saves data.xml');
            // This setTimeout is here because thumbnail generation on save
            // is an optimistic operation (e.g. callback does not wait for it
            // to complete).
            setTimeout(function() {
                assert.ok(fs.existsSync(tmp + '/.thumb.png'), 'saves thumb');
                done();
            }, 1000);
        });
    });
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var connect = require('connect')
  , assert = require('assert')
  , should = require('should')
  , http = require('http');

/**
 * Path to ./test/fixtures/
 */

var fixturesPath = __dirname + '/fixtures';

var app = connect.createServer(
  connect.static(fixturesPath)
);

module.exports = {
   'test valid file': function(){
     assert.response(app,
       { url: '/user.json' },
       function(res){
         res.statusCode.should.equal(200);
         JSON.parse(res.body).should.eql({ name: 'tj', email: 'tj@vision-media.ca' });
         res.headers.should.have.property('content-length', '55');
         res.headers.should.have.property('cache-control', 'public, max-age=0');
         res.headers.should.have.property('last-modified');
         res.headers.should.have.property('etag');
     });
   },

  'test maxAge': function(){
    var app = connect.createServer(
      connect.static(fixturesPath, { maxAge: 60000 })
    );

    assert.response(app,
      { url: '/user.json' },
      function(res){
        res.statusCode.should.equal(200);
        res.headers.should.have.property('cache-control', 'public, max-age=60');
    });
  },

  'test url encoding': function(){
    assert.response(app,
      { url: '/some%20text.txt' },
      { body: 'whoop', status: 200 });
  },

  'test index.html support': function(){
    assert.response(app,
      { url: '/' },
      { body: '
Wahoo!
'
      , status: 200
      , headers: {
        'Content-Type': 'text/html; charset=UTF-8'
      }});
  },

  'test index.html support when missing': function(){
    var app = connect.createServer(
      connect.static(__dirname)
    );

    assert.response(app,
      { url: '/' },
      { body: 'Cannot GET /', status: 404 });
  },

  'test invalid file': function(){
    assert.response(app,
      { url: '/foo.json' },
      { body: 'Cannot GET /foo.json', status: 404 });
  },

  'test directory': function(){
    assert.response(app,
      { url: '/fixtures' },
      { body: 'Cannot GET /fixtures', status: 404 });
  },

  'test forbidden': function(){
    assert.response(app,
      { url: '/../favicon.test.js' },
      { body: 'Forbidden', status: 403 });
  },

  'test forbidden urlencoded': function(){
    assert.response(app,
      { url: '/%2e%2e/favicon.test.js' },
      { body: 'Forbidden', status: 403 });
  },

  'test 404 on hidden file': function(){
    assert.response(app,
      { url: '/.hidden' },
      { status: 404 });
  },

  'test "hidden" option': function(){
    var app = connect.createServer(
      connect.static(fixturesPath, { hidden: true })
    );

    assert.response(app,
      { url: '/.hidden' },
      { body: 'hidden\n' });
  },

  'test HEAD': function(){
    assert.response(app,
      { url: '/user.json', method: 'HEAD' },
      { status: 200, headers: { 'Content-Length': '55' }});
  },

  'test Range': function(){
    assert.response(app,
      { url: '/list', headers: { Range: 'bytes=0-4' }},
      { body: '12345', status: 206 });
  },

  'test Range 2': function(){
    assert.response(app,
      { url: '/list', headers: { Range: 'bytes=5-9' }},
      { body: '6789', status: 206 });
  },

  'test invalid Range': function(){
    assert.response(app,
      { url: '/list', headers: { Range: 'bytes=RAWR' }},
      { body: 'Requested Range Not Satisfiable', status: 416 });
  },

  'test callback': function(){
    var app = connect.createServer(
      function(req, res, next){
        connect.static.send(req, res, function(err){
          res.end('done');
        }, { path: req.url });
      }
    );

    assert.response(app,
      { url: '/list' },
      { body: 'done' });
  },

  'test If-Modified-Since modified': function(){
    assert.response(app,
      { url: '/list', headers: { 'If-Modified-Since': new Date('2000').toUTCString() }},
      { body: '123456789', status: 200 });
  },

  'test If-Modified-Since unmodified': function(){
    assert.response(app,
      { url: '/list', headers: { 'If-Modified-Since': new Date('2050').toUTCString() }},
      { body: '', status: 304 },
      function(res){
        Object.keys(res.headers).forEach(function(field){
          if (0 == field.indexOf('content')) {
            should.fail('failed to strip ' + field);
          }
        });
      });
  },

  'test ETag unmodified': function(){
    var app = connect.createServer(
      connect.static(fixturesPath)
    );

    app.listen(9898, function(){
      var options = { path: '/list', port: 9898, host: '127.0.0.1' };
      http.get(options, function(res){
        res.statusCode.should.equal(200);
        res.headers.should.have.property('etag');
        var etag = res.headers.etag;
        options.headers = { 'If-None-Match': etag };
        http.get(options, function(res){
          etag.should.equal(res.headers.etag);
          res.statusCode.should.equal(304);
          res.headers.should.not.have.property('content-length');
          res.headers.should.not.have.property('content-type');
          app.close();
        });
      });
    });
  },

  'test ETag multiple given, unmodified': function(){
    var app = connect.createServer(
      connect.static(fixturesPath)
    );

    app.listen(9899, function(){
      var options = { path: '/list', port: 9899, host: '127.0.0.1' };
      http.get(options, function(res){
        res.statusCode.should.equal(200);
        res.headers.should.have.property('etag');
        var etag = res.headers.etag;
        options.headers = { 'If-None-Match': 'foo, bar, ' + etag };
        http.get(options, function(res){
          etag.should.equal(res.headers.etag);
          res.statusCode.should.equal(304);
          res.headers.should.not.have.property('content-length');
          res.headers.should.not.have.property('content-type');
          app.close();
        });
      });
    });
  },

  'test custom mime type definition': function(){
    require('mime').define({ 'application/coffee-script': ['coffee'] });
    assert.response(app,
      { url: '/script.coffee' },
      { headers: { 'Content-Type': 'application/coffee-script' }});
  },

  'test do not override Content-Type header': function(){
     var app = connect.createServer(
       function(req, res, next){
         res.setHeader('Content-Type', 'text/bozo; charset=ISO-8859-1');
         next();
       },
       connect.static(fixturesPath)
     );

     assert.response(app,
       { url: '/' },
       { body: '
Wahoo!
'
       , status: 200
       , headers: {
         'Content-Type': 'text/bozo; charset=ISO-8859-1'
       }});
   },

   'test mime export': function(){
     connect.static.mime.define.should.be.a('function');
   }
};<commit_msg>added test for non-forbidden relative path<commit_after>
/**
 * Module dependencies.
 */

var connect = require('connect')
  , assert = require('assert')
  , should = require('should')
  , http = require('http');

/**
 * Path to ./test/fixtures/
 */

var fixturesPath = __dirname + '/fixtures';

var app = connect.createServer(
  connect.static(fixturesPath)
);

module.exports = {
   'test valid file': function(){
     assert.response(app,
       { url: '/user.json' },
       function(res){
         res.statusCode.should.equal(200);
         JSON.parse(res.body).should.eql({ name: 'tj', email: 'tj@vision-media.ca' });
         res.headers.should.have.property('content-length', '55');
         res.headers.should.have.property('cache-control', 'public, max-age=0');
         res.headers.should.have.property('last-modified');
         res.headers.should.have.property('etag');
     });
   },

  'test maxAge': function(){
    var app = connect.createServer(
      connect.static(fixturesPath, { maxAge: 60000 })
    );

    assert.response(app,
      { url: '/user.json' },
      function(res){
        res.statusCode.should.equal(200);
        res.headers.should.have.property('cache-control', 'public, max-age=60');
    });
  },

  'test url encoding': function(){
    assert.response(app,
      { url: '/some%20text.txt' },
      { body: 'whoop', status: 200 });
  },

  'test index.html support': function(){
    assert.response(app,
      { url: '/' },
      { body: '
Wahoo!
'
      , status: 200
      , headers: {
        'Content-Type': 'text/html; charset=UTF-8'
      }});
  },

  'test index.html support when missing': function(){
    var app = connect.createServer(
      connect.static(__dirname)
    );

    assert.response(app,
      { url: '/' },
      { body: 'Cannot GET /', status: 404 });
  },

  'test invalid file': function(){
    assert.response(app,
      { url: '/foo.json' },
      { body: 'Cannot GET /foo.json', status: 404 });
  },

  'test directory': function(){
    assert.response(app,
      { url: '/fixtures' },
      { body: 'Cannot GET /fixtures', status: 404 });
  },

  'test forbidden': function(){
    assert.response(app,
      { url: '/../favicon.test.js' },
      { body: 'Forbidden', status: 403 });
  },

  'test forbidden urlencoded': function(){
    assert.response(app,
      { url: '/%2e%2e/favicon.test.js' },
      { body: 'Forbidden', status: 403 });
  },

  'test relative': function(){
    assert.response(app,
      { url: '/foo/../foo.log' },
      { body: '127.0.0.1\n' });
  },

  'test 404 on hidden file': function(){
    assert.response(app,
      { url: '/.hidden' },
      { status: 404 });
  },

  'test "hidden" option': function(){
    var app = connect.createServer(
      connect.static(fixturesPath, { hidden: true })
    );

    assert.response(app,
      { url: '/.hidden' },
      { body: 'hidden\n' });
  },

  'test HEAD': function(){
    assert.response(app,
      { url: '/user.json', method: 'HEAD' },
      { status: 200, headers: { 'Content-Length': '55' }});
  },

  'test Range': function(){
    assert.response(app,
      { url: '/list', headers: { Range: 'bytes=0-4' }},
      { body: '12345', status: 206 });
  },

  'test Range 2': function(){
    assert.response(app,
      { url: '/list', headers: { Range: 'bytes=5-9' }},
      { body: '6789', status: 206 });
  },

  'test invalid Range': function(){
    assert.response(app,
      { url: '/list', headers: { Range: 'bytes=RAWR' }},
      { body: 'Requested Range Not Satisfiable', status: 416 });
  },

  'test callback': function(){
    var app = connect.createServer(
      function(req, res, next){
        connect.static.send(req, res, function(err){
          res.end('done');
        }, { path: req.url });
      }
    );

    assert.response(app,
      { url: '/list' },
      { body: 'done' });
  },

  'test If-Modified-Since modified': function(){
    assert.response(app,
      { url: '/list', headers: { 'If-Modified-Since': new Date('2000').toUTCString() }},
      { body: '123456789', status: 200 });
  },

  'test If-Modified-Since unmodified': function(){
    assert.response(app,
      { url: '/list', headers: { 'If-Modified-Since': new Date('2050').toUTCString() }},
      { body: '', status: 304 },
      function(res){
        Object.keys(res.headers).forEach(function(field){
          if (0 == field.indexOf('content')) {
            should.fail('failed to strip ' + field);
          }
        });
      });
  },

  'test ETag unmodified': function(){
    var app = connect.createServer(
      connect.static(fixturesPath)
    );

    app.listen(9898, function(){
      var options = { path: '/list', port: 9898, host: '127.0.0.1' };
      http.get(options, function(res){
        res.statusCode.should.equal(200);
        res.headers.should.have.property('etag');
        var etag = res.headers.etag;
        options.headers = { 'If-None-Match': etag };
        http.get(options, function(res){
          etag.should.equal(res.headers.etag);
          res.statusCode.should.equal(304);
          res.headers.should.not.have.property('content-length');
          res.headers.should.not.have.property('content-type');
          app.close();
        });
      });
    });
  },

  'test ETag multiple given, unmodified': function(){
    var app = connect.createServer(
      connect.static(fixturesPath)
    );

    app.listen(9899, function(){
      var options = { path: '/list', port: 9899, host: '127.0.0.1' };
      http.get(options, function(res){
        res.statusCode.should.equal(200);
        res.headers.should.have.property('etag');
        var etag = res.headers.etag;
        options.headers = { 'If-None-Match': 'foo, bar, ' + etag };
        http.get(options, function(res){
          etag.should.equal(res.headers.etag);
          res.statusCode.should.equal(304);
          res.headers.should.not.have.property('content-length');
          res.headers.should.not.have.property('content-type');
          app.close();
        });
      });
    });
  },

  'test custom mime type definition': function(){
    require('mime').define({ 'application/coffee-script': ['coffee'] });
    assert.response(app,
      { url: '/script.coffee' },
      { headers: { 'Content-Type': 'application/coffee-script' }});
  },

  'test do not override Content-Type header': function(){
     var app = connect.createServer(
       function(req, res, next){
         res.setHeader('Content-Type', 'text/bozo; charset=ISO-8859-1');
         next();
       },
       connect.static(fixturesPath)
     );

     assert.response(app,
       { url: '/' },
       { body: '
Wahoo!
'
       , status: 200
       , headers: {
         'Content-Type': 'text/bozo; charset=ISO-8859-1'
       }});
   },

   'test mime export': function(){
     connect.static.mime.define.should.be.a('function');
   }
};<|endoftext|>


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

var fixtures = __dirname + '/fixtures';

var app = connect();
app.use(connect.staticCache());
app.use(connect.static(fixtures));

describe('connect.staticCache()', function(){
  it('should set X-Cache to MISS when missed', function(done){
    app.request()
    .get('/todo.txt')
    .end(function(res){
      res.should.have.header('x-cache', 'MISS');
      done();
    });
  })

  it('should set Age', function(done){
    app.request()
    .get('/todo.txt')
    .end(function(res){
      res.should.have.header('age');
      done();
    });
  })

  it('should set X-Cache to MISS end-to-end', function(done){
    app.request()
    .get('/todo.txt')
    .set('Cache-Control', 'no-cache')
    .end(function(res){
      res.should.have.header('x-cache', 'MISS');
      done();
    });
  })

  it('should set X-Cache to HIT when hit', function(done){
    app.request()
    .get('/todo.txt')
    .end(function(res){
      res.should.have.header('x-cache', 'HIT');
      done();
    });
  })

  it('should retain header fields', function(done){
    app.request()
    .get('/todo.txt')
    .end(function(res){
      res.should.have.header('content-type', 'text/plain; charset=UTF-8');
      res.should.have.header('content-length', '11');
      done();
    });
  })

  it('should serve the contents on GET', function(done){
    app.request()
    .get('/todo.txt')
    .expect('- groceries', done);
  })

  it('should not serve the contents on HEAD', function(done){
    app.request()
    .head('/todo.txt')
    .expect('', done);
  })

  it('should retain Content-Length on HEAD', function(done){
    app.request()
    .head('/todo.txt')
    .expect('Content-Length', '11', done);
  })
})<commit_msg>more tests<commit_after>
var connect = require('../');

var fixtures = __dirname + '/fixtures';

var app = connect();
app.use(connect.staticCache());
app.use(connect.static(fixtures));

describe('connect.staticCache()', function(){
  it('should set X-Cache to MISS when missed', function(done){
    app.request()
    .get('/todo.txt')
    .end(function(res){
      res.should.have.header('x-cache', 'MISS');
      done();
    });
  })

  it('should set Age', function(done){
    app.request()
    .get('/todo.txt')
    .end(function(res){
      res.should.have.header('age');
      done();
    });
  })

  it('should set X-Cache to MISS end-to-end', function(done){
    app.request()
    .get('/todo.txt')
    .set('Cache-Control', 'no-cache')
    .end(function(res){
      res.should.have.header('x-cache', 'MISS');
      done();
    });
  })

  it('should set X-Cache to HIT when hit', function(done){
    app.request()
    .get('/todo.txt')
    .end(function(res){
      res.should.have.header('x-cache', 'HIT');
      done();
    });
  })

  it('should retain header fields', function(done){
    app.request()
    .get('/todo.txt')
    .end(function(res){
      res.should.have.header('content-type', 'text/plain; charset=UTF-8');
      res.should.have.header('content-length', '11');
      done();
    });
  })

  it('should serve the contents on GET', function(done){
    app.request()
    .get('/todo.txt')
    .expect('- groceries', done);
  })

  it('should not serve the contents on HEAD', function(done){
    app.request()
    .head('/todo.txt')
    .expect('', done);
  })

  it('should retain Content-Length on HEAD', function(done){
    app.request()
    .head('/todo.txt')
    .expect('Content-Length', '11', done);
  })

  it('should not cache private', function(done){
    var app = connect();
    app.use(connect.staticCache());
    app.use(function(req, res, next){
      res.setHeader('Cache-Control', 'private');
      next();
    });
    app.use(connect.static(fixtures));

    app.request()
    .head('/todo.txt')
    .expect('X-Cache', 'MISS', done);
  })
})<|endoftext|>


<commit_before>var nofactor = require("../"),
expect = require("expect.js");

describe("string dom", function() {
  sd = nofactor.string;

  it("can create a text node", function() {
    expect(sd.createTextNode("hello").toString()).to.be("hello");
  });

  it("doesn't encode a text node", function() {
    expect(sd.createTextNode("hello <world").toString()).to.be("hello <world");
  });

  it("can create an element", function() {
    expect(sd.createElement("div").toString()).to.be("

");
  });

  it("can add a comment node", function() {
    var comment = sd.createComment("hello");
    expect(comment.toString()).to.be("");
  });

  it("can create an element with attributes", function() {
    var element = sd.createElement("div");
    element.setAttribute("hello", "world");
    element.setAttribute("nada");
    expect(element.toString()).to.be("

");
  });

  it("doesn't encode attribute values", function() {
    var element = sd.createElement("div");
    element.setAttribute("href", "http://");
    element.setAttribute("abc", "<;");
    expect(element.toString()).to.be("<div href=\"http://\" abc=\"<;\">
");
  });

  it("can create a fragment", function() {
    var frag = sd.createFragment();
    frag.appendChild(sd.createElement("div"));
    frag.appendChild(sd.createTextNode("abc"));
    expect(frag.toString()).to.be("

abc");
  });

  it("can add children to an element", function() {
    var element = sd.createElement("div");
    var text = sd.createTextNode("hello");
    element.appendChild(text);
    expect(element.toString()).to.be("
hello
");
  });

  it("can properly add a document fragment to an element", function() {
    var element = sd.createElement("div"),
    tn, tn2;
    var frag = sd.createFragment(tn = sd.createTextNode("hello"), tn2 = sd.createTextNode("world"));
    element.appendChild(frag);
    expect(element.toString()).to.be("
helloworld
");
    expect(tn.parentNode).to.be(element);
    expect(tn.nextSibling).to.be(tn2);
  });

  it("can properly prepend a fragment", function() {
    var element = sd.createElement("div"),
    tn, tn2, tn3;

    element.appendChild(tn3 = sd.createTextNode("!!!"));

    var frag = sd.createFragment(tn = sd.createTextNode("hello"), tn2 = sd.createTextNode("world"));
    element.insertBefore(frag, tn3);
    expect(element.toString()).to.be("
helloworld!!!
");
    expect(tn.parentNode).to.be(element);
    expect(tn.nextSibling).to.be(tn2);
  })

  it("has the proper siblings", function() {

    var element = sd.createElement("div"),
    tn = sd.createTextNode("hello"),
    tn2 = sd.createTextNode("hello2"),
    tn3 = sd.createTextNode("hello3");

    element.appendChild(tn);
    element.appendChild(tn2);
    element.appendChild(tn3);

    function testThree() {
      expect(tn.nextSibling).to.be(tn2);
      expect(tn2.nextSibling).to.be(tn3);
      expect(tn3.nextSibling).to.be(undefined);
      expect(tn3.previousSibling).to.be(tn2);
      expect(tn2.previousSibling).to.be(tn);
      expect(tn.previousSibling).to.be(undefined);
    }

    testThree();

    element.removeChild(tn2);
    expect(element.toString()).to.be("
hellohello3
")

    expect(tn.nextSibling).to.be(tn3);
    expect(tn3.nextSibling).to.be(undefined);
    expect(tn3.previousSibling).to.be(tn);
    expect(tn.previousSibling).to.be(undefined);

    element.insertBefore(tn2, tn3);

    testThree();
    expect(element.toString()).to.be("
hellohello2hello3
")

    element.removeChild(tn);
    expect(tn2.previousSibling).to.be(undefined);

    element.insertBefore(tn3, tn2);
    expect(tn2.previousSibling).to.be(tn3);

  });

  it("has the proper node attribute info", function() {
    var node = sd.createElement("div");
    node.setAttribute("id", "test");
    expect(node.attributes.length).to.be(1);
    node.setAttribute("id", "test2");
    expect(node.attributes.length).to.be(1);
  });

});<commit_msg>added test<commit_after>var nofactor = require("../"),
expect = require("expect.js");

describe("string dom", function() {
  sd = nofactor.string;

  it("can create a text node", function() {
    expect(sd.createTextNode("hello").toString()).to.be("hello");
  });

  it("doesn't encode a text node", function() {
    expect(sd.createTextNode("hello <world").toString()).to.be("hello <world");
  });

  it("can create an element", function() {
    expect(sd.createElement("div").toString()).to.be("

");
  });

  it("can add a comment node", function() {
    var comment = sd.createComment("hello");
    expect(comment.toString()).to.be("");
  });

  it("can create an element with attributes", function() {
    var element = sd.createElement("div");
    element.setAttribute("hello", "world");
    element.setAttribute("nada");
    expect(element.toString()).to.be("

");
  });

  it("doesn't encode attribute values", function() {
    var element = sd.createElement("div");
    element.setAttribute("href", "http://");
    element.setAttribute("abc", "<;");
    expect(element.toString()).to.be("<div href=\"http://\" abc=\"<;\">
");
  });

  it("can create a fragment", function() {
    var frag = sd.createFragment();
    frag.appendChild(sd.createElement("div"));
    frag.appendChild(sd.createTextNode("abc"));
    expect(frag.toString()).to.be("

abc");
  });

  it("can add children to an element", function() {
    var element = sd.createElement("div");
    var text = sd.createTextNode("hello");
    element.appendChild(text);
    expect(element.toString()).to.be("
hello
");
  });

  it("can properly add a document fragment to an element", function() {
    var element = sd.createElement("div"),
    tn, tn2;
    var frag = sd.createFragment(tn = sd.createTextNode("hello"), tn2 = sd.createTextNode("world"));
    element.appendChild(frag);
    expect(element.toString()).to.be("
helloworld
");
    expect(tn.parentNode).to.be(element);
    expect(tn.nextSibling).to.be(tn2);
  });

  it("can properly prepend a fragment", function() {
    var element = sd.createElement("div"),
    tn, tn2, tn3;

    element.appendChild(tn3 = sd.createTextNode("!!!"));

    var frag = sd.createFragment(tn = sd.createTextNode("hello"), tn2 = sd.createTextNode("world"));
    element.insertBefore(frag, tn3);
    expect(element.toString()).to.be("
helloworld!!!
");
    expect(tn.parentNode).to.be(element);
    expect(tn.nextSibling).to.be(tn2);
  })

  it("has the proper siblings", function() {

    var element = sd.createElement("div"),
    tn = sd.createTextNode("hello"),
    tn2 = sd.createTextNode("hello2"),
    tn3 = sd.createTextNode("hello3");

    element.appendChild(tn);
    element.appendChild(tn2);
    element.appendChild(tn3);

    function testThree() {
      expect(tn.nextSibling).to.be(tn2);
      expect(tn2.nextSibling).to.be(tn3);
      expect(tn3.nextSibling).to.be(undefined);
      expect(tn3.previousSibling).to.be(tn2);
      expect(tn2.previousSibling).to.be(tn);
      expect(tn.previousSibling).to.be(undefined);
    }

    testThree();

    element.removeChild(tn2);
    expect(element.toString()).to.be("
hellohello3
")

    expect(tn.nextSibling).to.be(tn3);
    expect(tn3.nextSibling).to.be(undefined);
    expect(tn3.previousSibling).to.be(tn);
    expect(tn.previousSibling).to.be(undefined);

    element.insertBefore(tn2, tn3);

    testThree();
    expect(element.toString()).to.be("
hellohello2hello3
")

    element.removeChild(tn);
    expect(tn2.previousSibling).to.be(undefined);

    element.insertBefore(tn3, tn2);
    expect(tn2.previousSibling).to.be(tn3);

  });

  it("has the proper node attribute info", function() {
    var node = sd.createElement("div");
    node.setAttribute("id", "test");
    expect(node.attributes.length).to.be(1);
    node.setAttribute("id", "test2");
    expect(node.attributes.length).to.be(1);
    expect(node.getAttribute("id")).to.be("test2");
  });

});<|endoftext|>


<commit_before>var assert, base62;

if (typeof window === 'undefined') {
  assert = require('chai').assert;
  base62 = require('../base62');
} else {
  assert = chai.assert;
  base62 = window.Base62;
}

suite('base62のテスト', function () {

  suite('changeTable関数のテスト', function () {

    test('"09azAZ"テーブルに切り替えられること', function () {
      assert.doesNotThrow(function () {
        base62.changeTable('09azAZ');
      });
    });

    test('"09AZaz"テーブルに切り替えられること', function () {
      assert.doesNotThrow(function () {
        base62.changeTable('09AZaz');
      });
    });

    test('存在しないテーブルに切り替えると例外が投げられること', function () {
      assert.throws(function () {
        base62.changeTable('');
      });
    });

  });

  suite('decode関数のテスト', function () {

    test('空文字を渡してNaNが返ること', function () {
      assert.isTrue(isNaN(base62.decode('')));
    });

    test('"-"を渡してNaNが返ること', function () {
      assert.isTrue(isNaN(base62.decode('-')));
    });

    test('string以外の型を渡してNaNが返ること', function () {
      assert.isTrue(isNaN(base62.decode(null)));
      assert.isTrue(isNaN(base62.decode(void 0)));
      assert.isTrue(isNaN(base62.decode(0)));
      assert.isTrue(isNaN(base62.decode(1)));
      assert.isTrue(isNaN(base62.decode(true)));
      assert.isTrue(isNaN(base62.decode(false)));
    });

    suite('"09azAZ"テーブルの場合', function () {

      setup(function () {
        base62.changeTable('09azAZ');
      });

      test('"0"を渡して0が返ること', function () {
        assert.strictEqual(base62.decode('0'), 0);
      });

      test('"Z"を渡して61が返ること', function () {
        assert.strictEqual(base62.decode('Z'), 61);
      });

      test('"10"を渡して62が返ること', function () {
        assert.strictEqual(base62.decode('10'), 62);
      });

      test('"ZZ"を渡して3843が返ること', function () {
        assert.strictEqual(base62.decode('ZZ'), 3843);
      });

      test('"100"を渡して3844が返ること', function () {
        assert.strictEqual(base62.decode('100'), 3844);
      });

      test('"-0"を渡して0が返ること', function () {
        assert.strictEqual(base62.decode('-0'), 0);
      });

      test('"-Z"を渡して-61が返ること', function () {
        assert.strictEqual(base62.decode('-Z'), -61);
      });

    });

    suite('"09AZaz"テーブルの場合', function () {

      setup(function () {
        base62.changeTable('09AZaz');
      });

      test('"0"を渡して0が返ること', function () {
        assert.strictEqual(base62.decode('0'), 0);
      });

      test('"z"を渡して61が返ること', function () {
        assert.strictEqual(base62.decode('z'), 61);
      });

      test('"10"を渡して62が返ること', function () {
        assert.strictEqual(base62.decode('10'), 62);
      });

      test('"zz"を渡して3843が返ること', function () {
        assert.strictEqual(base62.decode('zz'), 3843);
      });

      test('"100"を渡して3844が返ること', function () {
        assert.strictEqual(base62.decode('100'), 3844);
      });

      test('"-0"を渡して0が返ること', function () {
        assert.strictEqual(base62.decode('-0'), 0);
      });

      test('"-z"を渡して-61が返ること', function () {
        assert.strictEqual(base62.decode('-z'), -61);
      });

    });

  });

  suite('encode関数のテスト', function () {

    test('NaNを渡して空文字が返ること', function () {
      assert.strictEqual(base62.encode(NaN), '');
    });

    test('Infinityを渡して空文字が返ること', function () {
      assert.strictEqual(base62.encode(Infinity), '');
    });

    test('-Infinityを渡して空文字が返ること', function () {
      assert.strictEqual(base62.encode(-Infinity), '');
    });

    test('number以外の型を渡して空文字が返ること', function () {
      assert.strictEqual(base62.encode(null), '');
      assert.strictEqual(base62.encode(void 0), '');
      assert.strictEqual(base62.encode(''), '');
      assert.strictEqual(base62.encode('a'), '');
      assert.strictEqual(base62.encode(true), '');
      assert.strictEqual(base62.encode(false), '');
    });

    suite('"09azAZ"テーブルの場合', function () {

      setup(function () {
        base62.changeTable('09azAZ');
      });

      test('0を渡して"0"が返ること', function () {
        assert.strictEqual(base62.encode(0), '0');
      });

      test('61を渡して"Z"が返ること', function () {
        assert.strictEqual(base62.encode(61), 'Z');
      });

      test('62を渡して"10"が返ること', function () {
        assert.strictEqual(base62.encode(62), '10');
      });

      test('3843を渡して"ZZ"が返ること', function () {
        assert.strictEqual(base62.encode(3843), 'ZZ');
      });

      test('-0を渡して"0"が返ること', function () {
        assert.strictEqual(base62.encode(-0), '0');
      });

      test('-61を渡して"-Z"が返ること', function () {
        assert.strictEqual(base62.encode(-61), '-Z');
      });

      test('10.0, 10.1, 10.9を渡してすべて"a"が返ること', function () {
        assert.strictEqual(base62.encode(10.0), 'a');
        assert.strictEqual(base62.encode(10.1), 'a');
        assert.strictEqual(base62.encode(10.9), 'a');
      });

    });

    suite('"09AZaz"テーブルの場合', function () {

      setup(function () {
        base62.changeTable('09AZaz');
      });

      test('0を渡して"0"が返ること', function () {
        assert.strictEqual(base62.encode(0), '0');
      });

      test('61を渡して"z"が返ること', function () {
        assert.strictEqual(base62.encode(61), 'z');
      });

      test('62を渡して"10"が返ること', function () {
        assert.strictEqual(base62.encode(62), '10');
      });

      test('3843を渡して"zz"が返ること', function () {
        assert.strictEqual(base62.encode(3843), 'zz');
      });

      test('-0を渡して"0"が返ること', function () {
        assert.strictEqual(base62.encode(-0), '0');
      });

      test('-61を渡して"-z"が返ること', function () {
        assert.strictEqual(base62.encode(-61), '-z');
      });

      test('10.0, 10.1, 10.9を渡してすべて"A"が返ること', function () {
        assert.strictEqual(base62.encode(10.0), 'A');
        assert.strictEqual(base62.encode(10.1), 'A');
        assert.strictEqual(base62.encode(10.9), 'A');
      });

    });

  });

});
<commit_msg>テストを修正した<commit_after>var assert, base62;

if (typeof window === 'undefined') {
  assert = require('chai').assert;
  base62 = require('../base62');
} else {
  assert = chai.assert;
  base62 = window.Base62;
}

suite('base62のテスト', function() {

  suite('インスタンス生成のテスト', function() {

    test('引数なしで生成できること', function() {
      assert.doesNotThrow(function() { new base62; }, base62,
        'create new instance with no parameter does not throw');
    });

    test('"09azAZ"テーブルを指定して生成できること', function() {
      assert.doesNotThrow(function() { new base62('09azAZ'); }, base62,
        'create new instance with "09azAZ" does not throw');
    });

    test('"09AZaz"テーブルを指定して生成できること', function() {
      assert.doesNotThrow(function() { new base62('09AZaz'); }, base62,
        'create new instance with "09AZaz" does not throw');
    });

    test('存在しないテーブルを指定すると例外が発生すること', function() {
      assert.throws(function() { new base62('AZaz09'); }, Error,
        'create new instance with "AZaz09" throws Error');

      assert.throws(function() { new base62('azAZ09'); }, Error,
        'create new instance with "azAZ09" throws Error');
    });

    test('string以外の型を渡すと例外が発生すること', function() {
      assert.throws(function() { new base62(1); }, TypeError,
        'create new instance with 1 throws TypeError');

      assert.throws(function() { new base62(true); }, TypeError,
        'create new instance with true throws TypeError');

      // undefined
      assert.throws(function() { new base62(void 0); }, TypeError,
        'create new instance with undefined throws TypeError');

      // null/object
      assert.throws(function() { new base62(null); }, TypeError,
        'create new instance with null throws TypeError');

      // function
      assert.throws(function() { new base62(function() {}); }, TypeError,
        'create new instance with function throws TypeError');
    });

  });

  suite('"09azAZ"テーブルでの関数のテスト', function () {
    var b;

    suiteSetup(function() {
      b = new base62('09azAZ');
    });

    suiteTeardown(function() {
      b = null;
    });

    suite('decode関数のテスト', function() {

      test('空文字を渡すと例外が発生すること', function() {
        assert.throws(function() { b.decode(''); }, Error,
          'call decode() with empty string throws Error');
      });

      test('"-"を渡すと例外が発生すること', function() {
        assert.throws(function() { b.decode('-'); }, Error,
          'call decode() with "-" throws Error');
      });

      test('string以外の型を渡すと例外が発生すること', function() {
        assert.throws(function() { b.decode(1); }, TypeError,
          'call decode() with 1 throws TypeError');

        assert.throws(function() { b.decode(true); }, TypeError,
          'call decode() with true throws TypeError');

        // undefined
        assert.throws(function() { b.decode(void 0); }, TypeError,
          'call decode() with undefined throws TypeError');

        // null/object
        assert.throws(function() { b.decode(null); }, TypeError,
          'call decode() with null throws TypeError');

        // function
        assert.throws(function() { b.decode(function() {}); }, TypeError,
          'call decode() with function throws TypeError');
      });

      test('"0"を0に変換できること', function() {
        assert.strictEqual(b.decode('0'), 0, 'decode("0") should be return 0');
      });

      test('"Z"を61に変換できること', function() {
        assert.strictEqual(b.decode('Z'), 61,
          'decode("Z") should be return 61');
      });

      test('"10"を62に変換できること', function() {
        assert.strictEqual(b.decode('10'), 62,
          'decode("10") should be return 62');
      });

      test('"-0"を0に変換できること', function() {
        assert.strictEqual(b.decode('-0'), 0,
          'decode("-0") should be return 0');
      });

      test('"-Z"を-61に変換できること', function() {
        assert.strictEqual(b.decode('-Z'), -61,
          'decode("-Z") should be return -61');
      });

      test('"-10"を-62に変換できること', function() {
        assert.strictEqual(b.decode('-10'), -62,
          'decode("-10") should be return 62');
      });

      test('"2lkCB1"を2147483647に変換できること', function() {
        assert.strictEqual(b.decode('2lkCB1'), 2147483647,
          'decode("2lkCB1") should be return 2147483647');
      });

      test('"-2lkCB2"を-2147483648に変換できること', function() {
        assert.strictEqual(b.decode('-2lkCB2'), -2147483648,
          'decode("-2lkCB2") should be return -2147483648');
      });

    });

    suite('encode関数のテスト', function() {

      test('NaNを渡すと例外が発生すること', function() {
        assert.throws(function() { b.encode(NaN); }, Error,
          'call encode() with NaN throws Error');
      });

      test('Infinityを渡すと例外が発生すること', function() {
        assert.throws(function() { b.encode(Infinity); }, Error,
          'call encode() with Infinity throws Error');
      });

      test('-Infinityを渡すと例外が発生すること', function() {
        assert.throws(function() { b.encode(-Infinity); }, Error,
          'call encode() with -Infinity throws Error');
      });

      test('number以外の型を渡すと例外が発生すること', function() {
        assert.throws(function() { b.encode('a'); }, TypeError,
          'call encode() with "a" throws TypeError');

        assert.throws(function() { b.encode(true); }, TypeError,
          'call encode() with true throws TypeError');

        // undefined
        assert.throws(function() { b.encode(void 0); }, TypeError,
          'call encode() with undefined throws TypeError');

        // null/object
        assert.throws(function() { b.encode(null); }, TypeError,
          'call encode() with null throws TypeError');

        // function
        assert.throws(function() { b.encode(function() {}); }, TypeError,
          'call encode() with function throws TypeError');
      });

      test('0を"0"に変換できること', function() {
        assert.strictEqual(b.encode(0), '0', 'encode(0) should be return "0"');
      });

      test('61を"Z"に変換できること', function() {
        assert.strictEqual(b.encode(61), 'Z',
          'encode(61) should be return "Z"');
      });

      test('62を"10"に変換できること', function() {
        assert.strictEqual(b.encode(62), '10',
          'encode(62) should be return "10"');
      });

      test('-0を"0"に変換できること', function() {
        assert.strictEqual(b.encode(-0), '0',
          'encode(-0) should be return "0"');
      });

      test('-61を"-Z"に変換できること', function() {
        assert.strictEqual(b.encode(-61), '-Z',
          'encode(-61) should be return "-Z"');
      });

      test('-62を"-10"に変換できること', function() {
        assert.strictEqual(b.encode(-62), '-10',
          'encode(-62) should be return "-10"');
      });

      test('2147483647を"2lkCB1"に変換できること', function() {
        assert.strictEqual(b.encode(2147483647), '2lkCB1',
          'encode(2147483647) should be return "2lkCB1"');
      });

      test('-2147483648を"-2lkCB2"に変換できること', function() {
        assert.strictEqual(b.encode(-2147483648), '-2lkCB2',
          'encode(-2147483648) should be return "-2lkCB2"');
      });

    });
  });

  suite('"09AZaz"テーブルでの関数のテスト', function () {
    var b;

    suiteSetup(function() {
      b = new base62('09AZaz');
    });

    suiteTeardown(function() {
      b = null;
    });

    suite('decode関数のテスト', function() {

      test('空文字を渡すと例外が発生すること', function() {
        assert.throws(function() { b.decode(''); }, Error,
          'call decode() with empty string throws Error');
      });

      test('"-"を渡すと例外が発生すること', function() {
        assert.throws(function() { b.decode('-'); }, Error,
          'call decode() with "-" throws Error');
      });

      test('string以外の型を渡すと例外が発生すること', function() {
        assert.throws(function() { b.decode(1); }, TypeError,
          'call decode() with 1 throws TypeError');

        assert.throws(function() { b.decode(true); }, TypeError,
          'call decode() with true throws TypeError');

        // undefined
        assert.throws(function() { b.decode(void 0); }, TypeError,
          'call decode() with undefined throws TypeError');

        // null/object
        assert.throws(function() { b.decode(null); }, TypeError,
          'call decode() with null throws TypeError');

        // function
        assert.throws(function() { b.decode(function() {}); }, TypeError,
          'call decode() with function throws TypeError');
      });

      test('"0"を0に変換できること', function() {
        assert.strictEqual(b.decode('0'), 0, 'decode("0") should be return 0');
      });

      test('"z"を61に変換できること', function() {
        assert.strictEqual(b.decode('z'), 61,
          'decode("z") should be return 61');
      });

      test('"10"を62に変換できること', function() {
        assert.strictEqual(b.decode('10'), 62,
          'decode("10") should be return 62');
      });

      test('"-0"を0に変換できること', function() {
        assert.strictEqual(b.decode('-0'), 0,
          'decode("-0") should be return 0');
      });

      test('"-z"を-61に変換できること', function() {
        assert.strictEqual(b.decode('-z'), -61,
          'decode("-z") should be return -61');
      });

      test('"-10"を-62に変換できること', function() {
        assert.strictEqual(b.decode('-10'), -62,
          'decode("-10") should be return 62');
      });

      test('"2LKcb1"を2147483647に変換できること', function() {
        assert.strictEqual(b.decode('2LKcb1'), 2147483647,
          'decode("2LKcb1") should be return 2147483647');
      });

      test('"-2LKcb2"を-2147483648に変換できること', function() {
        assert.strictEqual(b.decode('-2LKcb2'), -2147483648,
          'decode("-2LKcb2") should be return -2147483648');
      });

    });

    suite('encode関数のテスト', function() {

      test('NaNを渡すと例外が発生すること', function() {
        assert.throws(function() { b.encode(NaN); }, Error,
          'call encode() with NaN throws Error');
      });

      test('Infinityを渡すと例外が発生すること', function() {
        assert.throws(function() { b.encode(Infinity); }, Error,
          'call encode() with Infinity throws Error');
      });

      test('-Infinityを渡すと例外が発生すること', function() {
        assert.throws(function() { b.encode(-Infinity); }, Error,
          'call encode() with -Infinity throws Error');
      });

      test('number以外の型を渡すと例外が発生すること', function() {
        assert.throws(function() { b.encode('a'); }, TypeError,
          'call encode() with "a" throws TypeError');

        assert.throws(function() { b.encode(true); }, TypeError,
          'call encode() with true throws TypeError');

        // undefined
        assert.throws(function() { b.encode(void 0); }, TypeError,
          'call encode() with undefined throws TypeError');

        // null/object
        assert.throws(function() { b.encode(null); }, TypeError,
          'call encode() with null throws TypeError');

        // function
        assert.throws(function() { b.encode(function() {}); }, TypeError,
          'call encode() with function throws TypeError');
      });

      test('0を"0"に変換できること', function() {
        assert.strictEqual(b.encode(0), '0', 'encode(0) should be return "0"');
      });

      test('61を"z"に変換できること', function() {
        assert.strictEqual(b.encode(61), 'z',
          'encode(61) should be return "z"');
      });

      test('62を"10"に変換できること', function() {
        assert.strictEqual(b.encode(62), '10',
          'encode(62) should be return "10"');
      });

      test('-0を"0"に変換できること', function() {
        assert.strictEqual(b.encode(-0), '0',
          'encode(-0) should be return "0"');
      });

      test('-61を"-z"に変換できること', function() {
        assert.strictEqual(b.encode(-61), '-z',
          'encode(-61) should be return "-z"');
      });

      test('-62を"-10"に変換できること', function() {
        assert.strictEqual(b.encode(-62), '-10',
          'encode(-62) should be return "-10"');
      });

      test('2147483647を"2LKcb1"に変換できること', function() {
        assert.strictEqual(b.encode(2147483647), '2LKcb1',
          'encode(2147483647) should be return "2LKcb1"');
      });

      test('-2147483648を"-2LKcb2"に変換できること', function() {
        assert.strictEqual(b.encode(-2147483648), '-2LKcb2',
          'encode(-2147483648) should be return "-2LKcb2"');
      });

    });
  });

});
<|endoftext|>