<commit_before>var fs = require("fs")
var createShader = require("gl-shader")

var mat4 = require('gl-matrix').mat4

module.exports = function(game, opts) {
  return new ShaderPlugin(game, opts);
};
module.exports.pluginInfo = {
  clientOnly: true,
  loadAfter: ['voxel-stitch', 'voxel-mesher'],
};

function ShaderPlugin(game, opts) {
  this.shell = game.shell;

  this.stitcher = game.plugins.get('voxel-stitch');
  if (!this.stitcher) throw new Error('voxel-shader requires voxel-stitch plugin'); // for tileCount uniform and updateTexture event

  this.mesher = game.plugins.get('voxel-mesher');
  if (!this.mesher) throw new Error('voxel-shader requires voxel-mesher plugin'); // for meshes array TODO: ~ voxel module

  this.perspectiveResize = opts.perspectiveResize !== undefined ? opts.perspectiveResize : true;

  this.enable();
}

ShaderPlugin.prototype.enable = function() {
  this.shell.on('gl-init', this.onInit = this.ginit.bind(this));
  this.shell.on('gl-render', this.onRender = this.render.bind(this));
  if (this.perspectiveResize) this.shell.on('gl-resize', this.onResize = this.resize.bind(this));
  this.stitcher.on('updateTexture', this.onUpdateTexture = this.updateTexture.bind(this));
};

ShaderPlugin.prototype.disable = function() {
  this.shell.removeListener('gl-init', this.onInit);
  this.shell.removeListener('gl-render', this.onRender);
  if (this.onResize) this.shell.removeListener('gl-resize', this.onResize);
  this.stitcher.removeListener('updateTexture', this.onUpdateTexture);
};

ShaderPlugin.prototype.updateTexture = function(texture) {
  this.texture = texture; // used in tileMap uniform
}

ShaderPlugin.prototype.ginit = function() {
  this.shader = this.createAOShader();
  this.resize();
  this.modelMatrix = mat4.identity(new Float32Array(16)) // TODO: merge with view into modelView? or leave for flexibility?
};

ShaderPlugin.prototype.resize = function() {
  //Calculation projection matrix
  this.projectionMatrix = mat4.perspective(new Float32Array(16), Math.PI/4.0, this.shell.width/this.shell.height, 1.0, 1000.0)
};

ShaderPlugin.prototype.render = function() {
  var gl = this.shell.gl

  this.viewMatrix = this.shell.camera.view() // TODO: expose camera through a plugin instead?

  gl.enable(gl.CULL_FACE)
  gl.enable(gl.DEPTH_TEST)

  // TODO: is this right? see https://github.com/mikolalysenko/ao-shader/issues/2
  //gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
  //gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  gl.enable(gl.BLEND)
  // premultiply alpha when loading textures, so can use gl.ONE blending, see http://stackoverflow.com/questions/11521035/blending-with-html-background-in-webgl
  // TODO: move to gl-texture2d?
  gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true)

  //Bind the shader
  var shader = this.shader
  shader.bind()
  shader.attributes.attrib0.location = 0
  shader.attributes.attrib1.location = 1
  shader.uniforms.projection = this.projectionMatrix
  shader.uniforms.view = this.viewMatrix
  shader.uniforms.model = this.modelMatrix
  shader.uniforms.tileCount = this.stitcher.tileCount

  if (this.texture) shader.uniforms.tileMap = this.texture.bind() // texture might not have loaded yet

  for (var i = 0; i < this.mesher.meshes.length; ++i) {
    var mesh = this.mesher.meshes[i];
    mesh.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, mesh.triangleVertexCount)
    mesh.triangleVAO.unbind()
  }
};

ShaderPlugin.prototype.createAOShader = function() {
  return createShader(this.shell.gl,
    fs.readFileSync(__dirname+"/lib/ao.vsh"),
    fs.readFileSync(__dirname+"/lib/ao.fsh"))
};
<commit_msg>Create viewMatrix only once instead of on each gl-render<commit_after>var fs = require("fs")
var createShader = require("gl-shader")

var mat4 = require('gl-matrix').mat4

module.exports = function(game, opts) {
  return new ShaderPlugin(game, opts);
};
module.exports.pluginInfo = {
  clientOnly: true,
  loadAfter: ['voxel-stitch', 'voxel-mesher', 'voxel-camera'],
};

function ShaderPlugin(game, opts) {
  this.shell = game.shell;

  this.stitcher = game.plugins.get('voxel-stitch');
  if (!this.stitcher) throw new Error('voxel-shader requires voxel-stitch plugin'); // for tileCount uniform and updateTexture event

  this.mesher = game.plugins.get('voxel-mesher');
  if (!this.mesher) throw new Error('voxel-shader requires voxel-mesher plugin'); // for meshes array TODO: ~ voxel module

  this.camera = game.plugins.get('voxel-camera');
  if (!this.camera) throw new Error('voxel-shader requires voxel-camera plugin'); // for camera view matrix

  this.perspectiveResize = opts.perspectiveResize !== undefined ? opts.perspectiveResize : true;

  this.enable();
}

ShaderPlugin.prototype.enable = function() {
  this.shell.on('gl-init', this.onInit = this.ginit.bind(this));
  this.shell.on('gl-render', this.onRender = this.render.bind(this));
  if (this.perspectiveResize) this.shell.on('gl-resize', this.onResize = this.resize.bind(this));
  this.stitcher.on('updateTexture', this.onUpdateTexture = this.updateTexture.bind(this));
};

ShaderPlugin.prototype.disable = function() {
  this.shell.removeListener('gl-init', this.onInit);
  this.shell.removeListener('gl-render', this.onRender);
  if (this.onResize) this.shell.removeListener('gl-resize', this.onResize);
  this.stitcher.removeListener('updateTexture', this.onUpdateTexture);
};

ShaderPlugin.prototype.updateTexture = function(texture) {
  this.texture = texture; // used in tileMap uniform
}

ShaderPlugin.prototype.ginit = function() {
  this.shader = this.createAOShader();
  this.resize();
  this.viewMatrix = mat4.create();
  this.modelMatrix = mat4.identity(new Float32Array(16)) // TODO: merge with view into modelView? or leave for flexibility?
};

ShaderPlugin.prototype.resize = function() {
  //Calculation projection matrix
  this.projectionMatrix = mat4.perspective(new Float32Array(16), Math.PI/4.0, this.shell.width/this.shell.height, 1.0, 1000.0)
};

ShaderPlugin.prototype.render = function() {
  var gl = this.shell.gl

  this.camera.view(this.viewMatrix)

  gl.enable(gl.CULL_FACE)
  gl.enable(gl.DEPTH_TEST)

  // TODO: is this right? see https://github.com/mikolalysenko/ao-shader/issues/2
  //gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
  //gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  gl.enable(gl.BLEND)
  // premultiply alpha when loading textures, so can use gl.ONE blending, see http://stackoverflow.com/questions/11521035/blending-with-html-background-in-webgl
  // TODO: move to gl-texture2d?
  gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true)

  //Bind the shader
  var shader = this.shader
  shader.bind()
  shader.attributes.attrib0.location = 0
  shader.attributes.attrib1.location = 1
  shader.uniforms.projection = this.projectionMatrix
  shader.uniforms.view = this.viewMatrix
  shader.uniforms.model = this.modelMatrix
  shader.uniforms.tileCount = this.stitcher.tileCount

  if (this.texture) shader.uniforms.tileMap = this.texture.bind() // texture might not have loaded yet

  for (var i = 0; i < this.mesher.meshes.length; ++i) {
    var mesh = this.mesher.meshes[i];
    mesh.triangleVAO.bind()
    gl.drawArrays(gl.TRIANGLES, 0, mesh.triangleVertexCount)
    mesh.triangleVAO.unbind()
  }
};

ShaderPlugin.prototype.createAOShader = function() {
  return createShader(this.shell.gl,
    fs.readFileSync(__dirname+"/lib/ao.vsh"),
    fs.readFileSync(__dirname+"/lib/ao.fsh"))
};
<|endoftext|>


<commit_before>var glslify = require("glslify")
var fs = require("fs")

var mat4 = require('gl-matrix').mat4

module.exports = function(game, opts) {
  return new ShaderPlugin(game, opts);
};
module.exports.pluginInfo = {
  clientOnly: true,
  loadAfter: ['voxel-stitch', 'game-shell-fps-camera'],
};

function ShaderPlugin(game, opts) {
  this.shell = game.shell;

  this.stitcher = game.plugins.get('voxel-stitch');
  if (!this.stitcher) throw new Error('voxel-shader requires voxel-stitch plugin'); // for tileCount uniform and updateTexture event

  this.meshes = opts.meshes || game.voxels.meshes
  if (!this.meshes) throw new Error('voxel-shader requires "meshes" option or game.voxels.meshes set to array of voxel-mesher meshes')

  this.camera = game.plugins.get('game-shell-fps-camera');
  if (!this.camera) throw new Error('voxel-shader requires game-shell-fps-camera plugin'); // for camera view matrix

  this.perspectiveResize = opts.perspectiveResize !== undefined ? opts.perspectiveResize : true;
  this.cameraNear = opts.cameraNear !== undefined ? opts.cameraNear : 0.1;
  this.cameraFar = opts.cameraFar !== undefined ? opts.cameraFar : 200.0;
  this.cameraFOV = opts.cameraFOV !== undefined ? opts.cameraFOV : 45.0;

  this.projectionMatrix = mat4.create();

  this.enable();
}

ShaderPlugin.prototype.enable = function() {
  this.shell.on('gl-init', this.onInit = this.ginit.bind(this));
  this.shell.on('gl-render', this.onRender = this.render.bind(this));
  if (this.perspectiveResize) this.shell.on('gl-resize', this.onResize = this.updateProjectionMatrix.bind(this));
  this.stitcher.on('updateTexture', this.onUpdateTexture = this.texturesReady.bind(this));
};

ShaderPlugin.prototype.disable = function() {
  this.shell.removeListener('gl-init', this.onInit);
  this.shell.removeListener('gl-render', this.onRender);
  if (this.onResize) this.shell.removeListener('gl-resize', this.onResize);
  this.stitcher.removeListener('updateTexture', this.onUpdateTexture);
};

ShaderPlugin.prototype.texturesReady = function(texture) {
  this.texture = texture; // used in tileMap uniform
}

ShaderPlugin.prototype.ginit = function() {
  this.shader = this.createAOShader();
  this.shader2 = this.createCustomModelShader();
  this.updateProjectionMatrix();
  this.viewMatrix = mat4.create();

};

ShaderPlugin.prototype.updateProjectionMatrix = function() {
  mat4.perspective(this.projectionMatrix, this.cameraFOV*Math.PI/180, this.shell.width/this.shell.height, this.cameraNear, this.cameraFar)
};

ShaderPlugin.prototype.render = function() {
  var gl = this.shell.gl

  this.camera.view(this.viewMatrix)

  gl.enable(gl.CULL_FACE)
  gl.enable(gl.DEPTH_TEST)

  // TODO: is this right? see https://github.com/mikolalysenko/ao-shader/issues/2
  //gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
  //gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  gl.enable(gl.BLEND)

  //Bind the shader
  // phase 1 - solid blocks
  var shader = this.shader
  if (!shader) throw new Error('voxel-shader render() called before gl-init, shader=', this.shader)
  shader.bind()
  shader.attributes.attrib0.location = 0
  shader.attributes.attrib1.location = 1
  shader.uniforms.projection = this.projectionMatrix
  shader.uniforms.view = this.viewMatrix
  shader.uniforms.tileCount = this.stitcher.tileCount

  if (this.texture) shader.uniforms.tileMap = this.texture.bind() // if a texture is loaded

  var keys = Object.keys(this.meshes)
  var length = keys.length

  for (var k = 0; k < length; ++k) {
    var chunkIndex = keys[k]
    var mesh = this.meshes[chunkIndex]

    var triangleVAO = mesh.vertexArrayObjects.surface
    if (triangleVAO) {  // if there are triangles to render
      shader.uniforms.model = mesh.modelMatrix
      triangleVAO.bind()
      gl.drawArrays(gl.TRIANGLES, 0, triangleVAO.length)
      triangleVAO.unbind()
    }
  }

  // phase 2 - "porous" blocks
  var shader2 = this.shader2
  shader2.bind()
  shader2.attributes.position.location = 0
  shader2.uniforms.view = this.viewMatrix
  shader2.uniforms.projection = this.projectionMatrix
  if (this.texture) shader2.uniforms.texture = this.texture.bind()

  for (k = 0; k < length; ++k) {
    var chunkIndex = keys[k]
    var mesh = this.meshes[chunkIndex]

    var blockMesh = mesh.vertexArrayObjects.porous
    if (blockMesh) {
      shader2.uniforms.model = this.meshes[chunkIndex].modelMatrix

      blockMesh.bind()
      blockMesh.draw(gl.TRIANGLES, blockMesh.length)
      blockMesh.unbind()
    }
  }
};

ShaderPlugin.prototype.createAOShader = function() {
  return glslify({
    vertex: './lib/ao.vsh',
    fragment: './lib/ao.fsh'
  })(this.shell.gl)
};

ShaderPlugin.prototype.createCustomModelShader = function() {
  // TODO: refactor with voxel-decals, voxel-chunkborder?
  return glslify({
   inline: true,
    vertex: "\
attribute vec3 position;\
attribute vec2 uv;\
\
uniform mat4 projection;\
uniform mat4 view;\
uniform mat4 model;\
varying vec2 vUv;\
\
void main() {\
  gl_Position = projection * view * model * vec4(position, 1.0);\
  vUv = uv;\
}",

  fragment: "\
precision highp float;\
\
uniform sampler2D texture;\
varying vec2 vUv;\
\
void main() {\
  gl_FragColor = texture2D(texture, vUv);\
}"})(this.shell.gl);
};
<commit_msg>Only enable blending in second shader<commit_after>var glslify = require("glslify")
var fs = require("fs")

var mat4 = require('gl-matrix').mat4

module.exports = function(game, opts) {
  return new ShaderPlugin(game, opts);
};
module.exports.pluginInfo = {
  clientOnly: true,
  loadAfter: ['voxel-stitch', 'game-shell-fps-camera'],
};

function ShaderPlugin(game, opts) {
  this.shell = game.shell;

  this.stitcher = game.plugins.get('voxel-stitch');
  if (!this.stitcher) throw new Error('voxel-shader requires voxel-stitch plugin'); // for tileCount uniform and updateTexture event

  this.meshes = opts.meshes || game.voxels.meshes
  if (!this.meshes) throw new Error('voxel-shader requires "meshes" option or game.voxels.meshes set to array of voxel-mesher meshes')

  this.camera = game.plugins.get('game-shell-fps-camera');
  if (!this.camera) throw new Error('voxel-shader requires game-shell-fps-camera plugin'); // for camera view matrix

  this.perspectiveResize = opts.perspectiveResize !== undefined ? opts.perspectiveResize : true;
  this.cameraNear = opts.cameraNear !== undefined ? opts.cameraNear : 0.1;
  this.cameraFar = opts.cameraFar !== undefined ? opts.cameraFar : 200.0;
  this.cameraFOV = opts.cameraFOV !== undefined ? opts.cameraFOV : 45.0;

  this.projectionMatrix = mat4.create();

  this.enable();
}

ShaderPlugin.prototype.enable = function() {
  this.shell.on('gl-init', this.onInit = this.ginit.bind(this));
  this.shell.on('gl-render', this.onRender = this.render.bind(this));
  if (this.perspectiveResize) this.shell.on('gl-resize', this.onResize = this.updateProjectionMatrix.bind(this));
  this.stitcher.on('updateTexture', this.onUpdateTexture = this.texturesReady.bind(this));
};

ShaderPlugin.prototype.disable = function() {
  this.shell.removeListener('gl-init', this.onInit);
  this.shell.removeListener('gl-render', this.onRender);
  if (this.onResize) this.shell.removeListener('gl-resize', this.onResize);
  this.stitcher.removeListener('updateTexture', this.onUpdateTexture);
};

ShaderPlugin.prototype.texturesReady = function(texture) {
  this.texture = texture; // used in tileMap uniform
}

ShaderPlugin.prototype.ginit = function() {
  this.shader = this.createAOShader();
  this.shader2 = this.createCustomModelShader();
  this.updateProjectionMatrix();
  this.viewMatrix = mat4.create();

};

ShaderPlugin.prototype.updateProjectionMatrix = function() {
  mat4.perspective(this.projectionMatrix, this.cameraFOV*Math.PI/180, this.shell.width/this.shell.height, this.cameraNear, this.cameraFar)
};

ShaderPlugin.prototype.render = function() {
  var gl = this.shell.gl

  this.camera.view(this.viewMatrix)

  gl.enable(gl.CULL_FACE)
  gl.enable(gl.DEPTH_TEST)

  //Bind the shader
  // phase 1 - solid blocks
  gl.disable(gl.BLEND)
  var shader = this.shader
  if (!shader) throw new Error('voxel-shader render() called before gl-init, shader=', this.shader)
  shader.bind()
  shader.attributes.attrib0.location = 0
  shader.attributes.attrib1.location = 1
  shader.uniforms.projection = this.projectionMatrix
  shader.uniforms.view = this.viewMatrix
  shader.uniforms.tileCount = this.stitcher.tileCount

  if (this.texture) shader.uniforms.tileMap = this.texture.bind() // if a texture is loaded

  var keys = Object.keys(this.meshes)
  var length = keys.length

  for (var k = 0; k < length; ++k) {
    var chunkIndex = keys[k]
    var mesh = this.meshes[chunkIndex]

    var triangleVAO = mesh.vertexArrayObjects.surface
    if (triangleVAO) {  // if there are triangles to render
      shader.uniforms.model = mesh.modelMatrix
      triangleVAO.bind()
      gl.drawArrays(gl.TRIANGLES, 0, triangleVAO.length)
      triangleVAO.unbind()
    }
  }

  // phase 2 - "porous" blocks
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)  // TODO: premult alpha? https://github.com/deathcap/voxel-stitch/issues/6
  gl.enable(gl.BLEND)
  var shader2 = this.shader2
  shader2.bind()
  shader2.attributes.position.location = 0
  shader2.uniforms.view = this.viewMatrix
  shader2.uniforms.projection = this.projectionMatrix
  if (this.texture) shader2.uniforms.texture = this.texture.bind()

  for (k = 0; k < length; ++k) {
    var chunkIndex = keys[k]
    var mesh = this.meshes[chunkIndex]

    var blockMesh = mesh.vertexArrayObjects.porous
    if (blockMesh) {
      shader2.uniforms.model = this.meshes[chunkIndex].modelMatrix

      blockMesh.bind()
      blockMesh.draw(gl.TRIANGLES, blockMesh.length)
      blockMesh.unbind()
    }
  }
};

ShaderPlugin.prototype.createAOShader = function() {
  return glslify({
    vertex: './lib/ao.vsh',
    fragment: './lib/ao.fsh'
  })(this.shell.gl)
};

ShaderPlugin.prototype.createCustomModelShader = function() {
  // TODO: refactor with voxel-decals, voxel-chunkborder?
  return glslify({
   inline: true,
    vertex: "\
attribute vec3 position;\
attribute vec2 uv;\
\
uniform mat4 projection;\
uniform mat4 view;\
uniform mat4 model;\
varying vec2 vUv;\
\
void main() {\
  gl_Position = projection * view * model * vec4(position, 1.0);\
  vUv = uv;\
}",

  fragment: "\
precision highp float;\
\
uniform sampler2D texture;\
varying vec2 vUv;\
\
void main() {\
  gl_FragColor = texture2D(texture, vUv);\
}"})(this.shell.gl);
};
<|endoftext|>


<commit_before>// Initialize crafty and a sprite component
Crafty.init(650, 74);
Crafty.sprite(64, 'numbers.png', { 'numbers': [0, 0] });

// Add an animation to the stage
spriteAnimation = Crafty.e('2D, DOM, numbers, SpriteAnimation');
spriteAnimation.attr({ x: 10, y: 10 });
spriteAnimation.animate('count', 0, 0, 9);
spriteAnimation.animate('countEven', [[0, 0], [0, 2], [0, 4], [0, 6], [0, 8]]);

// We don't want anything to actually run in an uncontrolled manner during tests
Crafty.pause();
//Crafty.bind("EnterFrame", function() { console.log("In da frame!") });

var eventFrames = [];
spriteAnimation.bind("FrameChange", function(changeData) {
	eventFrames.push(changeData.frameNumber);
});

module("Sprite Animation", {
	setup: function() {
		eventFrames = [];
		spriteAnimation.reset();
	}
});

test("Play an animation", function() {
	// Play for 10 frames, each sprite will show up for one frame
	spriteAnimation.play('count', 10);
	for (var i = 0; i < 10; i++) {
		activeReel = spriteAnimation.getActiveReel();
		equal(activeReel.frame, i, "Frame " + i + " should be displayed");
		Crafty.timer.simulateFrames(1);
	}

	deepEqual(eventFrames, [1, 2, 3, 4, 5, 6, 7, 8, 9], "Expected events for frames 1 through 9");
});

test("Show the last frame after an animation ends", function() {
	// Play for 10 frames, each sprite will show up for one frame
	spriteAnimation.play('count', 10);
	Crafty.timer.simulateFrames(20);
	activeReel = spriteAnimation.getActiveReel();
	equal(activeReel.frame, 9, "Frame 9 should be displayed after the animation ends");

	deepEqual(eventFrames, [1, 2, 3, 4, 5, 6, 7, 8, 9], "Expected events for frames 1 through 9");
});

Crafty.pause();
<commit_msg>More tests<commit_after>// Initialize crafty and a sprite component
Crafty.init(650, 74);
Crafty.sprite(64, 'numbers.png', { 'numbers': [0, 0] });

// Add an animation to the stage
spriteAnimation = Crafty.e('2D, DOM, numbers, SpriteAnimation');
spriteAnimation.attr({ x: 10, y: 10 });
spriteAnimation.animate('count', 0, 0, 9);
spriteAnimation.animate('countEven', [[0, 0], [2, 0], [4, 0], [6, 0], [8, 0]]);
spriteAnimation.animate('short', 0, 0, 2);

// We don't want anything to actually run in an uncontrolled manner during tests
Crafty.pause();
//Crafty.bind("EnterFrame", function() { console.log("In da frame!") });

var eventFrames = [];
spriteAnimation.bind("FrameChange", function(changeData) {
	eventFrames.push(changeData.frameNumber);
});

var finishedAnimations = []
spriteAnimation.bind("AnimationEnd", function(endData) {
	finishedAnimations.push(endData.reelId);
});

module("Sprite Animation", {
	setup: function() {
		eventFrames = [];
		finishedAnimations = [];
		spriteAnimation.reset();
	}
});

test("Play an animation", function() {
	// Play for 10 frames, each sprite will show up for one frame
	spriteAnimation.play('count', 10);
	for (var i = 0; i < 10; i++) {
		activeReel = spriteAnimation.getActiveReel();
		equal(activeReel.frame, i, "Frame " + i + " should be displayed");
		Crafty.timer.simulateFrames(1);
	}
});

test("Play an animation defined using an array", function() {
	// Play for 5 frames, each sprite will show up for one frame
	spriteAnimation.play('countEven', 5);
	for (var i = 0; i < 5; i++) {
		activeReel = spriteAnimation.getActiveReel();
		equal(activeReel.frame, i, "Frame " + i + " should be displayed");
		Crafty.timer.simulateFrames(1);
	}
});

test("Play an animation where sprites are displayed for more than one frame", function() {
	// Play for 60 frames, each sprite will show up for six frames
	spriteAnimation.play('count', 60);
	for (var i = 0; i < 10; i++) {
		activeReel = spriteAnimation.getActiveReel();
		equal(activeReel.frame, i, "Frame " + i + " should be displayed");
		Crafty.timer.simulateFrames(6);
	}
});

test("Show the last frame after an animation ends", function() {
	spriteAnimation.play('count', 10);
	Crafty.timer.simulateFrames(20);
	activeReel = spriteAnimation.getActiveReel();
	equal(activeReel.frame, 9, "Frame 9 should be displayed after the animation ends");
});

test("Get events for each frame change", function() {
	spriteAnimation.play('count', 10);
	Crafty.timer.simulateFrames(20);

	deepEqual(eventFrames, [1, 2, 3, 4, 5, 6, 7, 8, 9], "Expected events for frames 1 through 9");
});

test("Get an event when an animation ends", function() {
	spriteAnimation.play('count', 10);
	Crafty.timer.simulateFrames(20);

	deepEqual(finishedAnimations, ['count'], "Should have received an event for the 'count' animation's end");
});

test("Play an animation with a repeat count", function() {
	spriteAnimation.play('short', 3, 2);
	Crafty.timer.simulateFrames(10);

	deepEqual(eventFrames, [1, 2, 0, 1, 2, 0, 1, 2], "Expected events for frames 1 through 3, 3 times");
	deepEqual(finishedAnimations, ['short'], "Expected a single animation end event");
});

Crafty.pause();
<|endoftext|>


<commit_before>/*!
 * benchmark.js
 * Copyright Mathias Bynens <http://mths.be/>
 * Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
 * Modified by John-David Dalton <http://allyoucanleet.com/>
 * Available under MIT license <http://mths.be/mit>
 */

/*jslint browser: true, forin: true, es5: false, onevar: true, eqeqeq: true, immed: true*/

(function(global) {

  function Benchmark(fn, options) {
    options = extend({ }, options);
    extend(this, options);
    this.fn = fn;
    this.options = options;
  }

  function Calibration(fn) {
    Benchmark.call(this, fn);
  }

  function Klass() { }

  Klass.prototype = Benchmark.prototype;

  (function(proto) {
    // bypass calibrating the Calibration tests when they are run
    function run(count, synchronous) {
      var me = this;
      me.running = true;
      me.count = count || me.INIT_COUNT;
      me.onStart(me);
      _run(me, synchronous);
    }
    proto.constructor = Calibration;
    proto.run = run;
  }(Calibration.prototype = new Klass()));

  /*--------------------------------------------------------------------------*/

  // one time calibration test
  // returns true if not calibrated, in which case the deferred test is called after calibration
  function calibrate(deferredTest) {
    var cal = Benchmark.CALIBRATION;
    if (!cal.count) {
      cal.onStop = deferredTest;
      cal.bestOf(3, 7e3); // 7000 * 3
      return true;
    }
    return false;
  }

  // copy properties
  function extend(destination, source) {
    source || (source = { });
    for (var key in source) {
      destination[key] = source[key];
    }
  }

  /*--------------------------------------------------------------------------*/

  function getPlatform() {
    var result,
        token,
        description = [],
        ua = navigator.userAgent,
        oses = '(?:Windows 98;|Windows |iPhone OS|(?:Intel |PPC )?Mac OS X|Linux)',
        os = (ua.match(RegExp(oses + '(?:[^ );]| )*')) || [])[0],
        name = (ua.match(/Chrome|MSIE|Safari|Opera|Firefox|Minefield/) || [])[0],
        version = global.opera && typeof opera.version === 'function' && opera.version(),
        mses = { '6.1': '7', '6.0': 'Vista', '5.2': 'Server 2003 / XP x64', '5.1': 'XP', '5.0': '2000', '4.0': 'NT', '4.9': 'Me' };

    // IE platform tokens defined
    // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
    if (os && os.indexOf('Windows') > -1) {
      token = mses[(os.match(/[456]\.\d/) || [])[0]];
      if (token) {
        os = 'Windows ' + token;
      }
    }
    if (!version) {
      version = name && (ua.match(RegExp('(?:Version|' + name + ')[ /]([^ ;]*)')) || [])[1];
    }
    result = {
      'name':        name ? description.push(name) && name : null,
      'version':     version ? description.push(version) && version : null,
      'os':          os ? description.push('on ' + (os = os.replace(/_/g, '.'))) && os : null,
      'description': description.length ? description.join(' ') : 'unknown platform',
      'toString':    function() { return this.description; }
    };

    // lazy defined
    function getPlatform() { return result; }
    this.getPlatform = getPlatform;
    return result;
  }

  function noop() { }

  /*--------------------------------------------------------------------------*/

  function bestOf(times, count, synchronous) {
    var best,
        finished = 0,
        i = times,
        me = this;
    me.reset();
    me.running = true;
    me.onStart(me);

    while (i--) {
      (function() {
        var clone = me.clone();
        clone.onCycle =
        clone.onStart = me.onCycle || noop;
        clone.onStop = function() {
          if (!best || clone.period < best.period) {
            best = clone;
          }
          if (++finished === times) {
            if (best.error) {
              me.error = best.error;
            }
            me.count = best.count;
            me.hz = best.hz;
            me.period = best.period;
            me.running = false;
            me.time = best.time;
            me.onStop(me);
          }
        };
        clone.run(count, synchronous);
      }());
    }
  }

  function clone() {
    var key,
        me = this,
        result = new me.constructor(me.fn, me.options);

    for (key in me) {
      if (!result[key]) {
        result[key] = me[key];
      }
    }
    result.reset();
    return result;
  }

  function reset() {
    var me = this;
    delete me.count;
    delete me.error;
    delete me.hz;
    delete me.period;
    delete me.running;
    delete me.time;
  }

  function run(count, synchronous) {
    var me = this;
    // ensure calibration test has run
    if (!calibrate(function() {
          if (synchronous) {
            me.run(count, synchronous);
          } else {
            setTimeout(function() {
              me.run(count);
            }, me.CYCLE_DELAY * 1e3);
          }
        })) {
      me.reset();
      me.running = true;
      me.count = count || me.INIT_COUNT;
      me.onStart(me);
      _run(me, synchronous);
    }
  }

  function _run(me, synchronous) {
    var start,
        fn = me.fn,
        i = me.count,
     calPeriod = Benchmark.CALIBRATION.period;

    try {
      // test execution loop
      start = new Date();
      while (i--) {
        fn();
      }

      // get time test took (in secs)
      me.time = Math.max(0,
        // avoid Infinity values if there is 0ms between start
        // and end times by forcing at least 1ms
        (Math.max(1, new Date() - start) / 1e3) -
        // subtract the base loop time
        (calPeriod ? calPeriod * me.count : 0));

      // per-operation time taken
      me.period = me.time / me.count;

      // ops per second
      me.hz = Math.round(1 / me.period);

      // do we need to do another run?
      me.running = me.time < me.MIN_TIME;

      // if so, compute how many times we should iterate
      if (me.running) {
        me.count += Math.ceil((me.MIN_TIME - me.time) / me.period);
        // stop running if the next cycle would exceed the max count allowed
        if (me.count > me.MAX_COUNT) {
          me.running = false;
        }
      }
    }
    catch (e) {
      me.reset();
      me.error = e;
    }

    me.onCycle(me);

    // figure out what to do next
    if (me.running) {
      // use a timeout to make sure the browser has a chance to finish rendering
      // any UI changes made, like updating the status message
      if (synchronous) {
        _run(me, synchronous);
      } else {
        setTimeout(function() {
          _run(me);
        }, me.CYCLE_DELAY * 1e3);
      }
    }
    else {
      me.onStop(me);
    }
  }

  /*--------------------------------------------------------------------------*/

  // test to establish iteration loop overhead
  Benchmark.CALIBRATION = new Calibration(noop);

  Benchmark.getPlatform = getPlatform;

  Benchmark.noop = noop;

  extend(Benchmark.prototype, {
    // delay between test cycles (secs)
    'CYCLE_DELAY' : 0.2,

    // initial number of iterations
    'INIT_COUNT' : 10,

    // max iterations allowed per cycle (used avoid locking up the browser)
    'MAX_COUNT' : 2e7, // 20 million

    // minimum time a test should take to get valid results (secs)
    'MIN_TIME' : 0.96,

    // callback invoked when one test cycle ends
    'onCycle' : noop,

    // callback invoked when test is started
    'onStart' : noop,

    // callback invoked when test is finished
    'onStop' : noop,

    // runs the test accepting the best of `n` attempts
    'bestOf' : bestOf,

    // create new benchmark with the same test and options
    'clone' : clone,

    // reset test state
    'reset' : reset,

    // run the test
    'run' : run
  });

  // expose
  global.Benchmark = Benchmark;

}(this));<commit_msg>benchmark.js: Cleanup platform info for iOS. [jddalton]<commit_after>/*!
 * benchmark.js
 * Copyright Mathias Bynens <http://mths.be/>
 * Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
 * Modified by John-David Dalton <http://allyoucanleet.com/>
 * Available under MIT license <http://mths.be/mit>
 */

/*jslint browser: true, forin: true, es5: false, onevar: true, eqeqeq: true, immed: true*/

(function(global) {

  function Benchmark(fn, options) {
    options = extend({ }, options);
    extend(this, options);
    this.fn = fn;
    this.options = options;
  }

  function Calibration(fn) {
    Benchmark.call(this, fn);
  }

  function Klass() { }

  Klass.prototype = Benchmark.prototype;

  (function(proto) {
    // bypass calibrating the Calibration tests when they are run
    function run(count, synchronous) {
      var me = this;
      me.running = true;
      me.count = count || me.INIT_COUNT;
      me.onStart(me);
      _run(me, synchronous);
    }
    proto.constructor = Calibration;
    proto.run = run;
  }(Calibration.prototype = new Klass()));

  /*--------------------------------------------------------------------------*/

  // one time calibration test
  // returns true if not calibrated, in which case the deferred test is called after calibration
  function calibrate(deferredTest) {
    var cal = Benchmark.CALIBRATION;
    if (!cal.count) {
      cal.onStop = deferredTest;
      cal.bestOf(3, 7e3); // 7000 * 3
      return true;
    }
    return false;
  }

  // copy properties
  function extend(destination, source) {
    source || (source = { });
    for (var key in source) {
      destination[key] = source[key];
    }
  }

  /*--------------------------------------------------------------------------*/

  function getPlatform() {
    var result,
        description = [],
        ua = navigator.userAgent,
        os = (ua.match(/(?:Windows 98;|Windows |iPhone OS|(?:Intel |PPC )?Mac OS X|Linux)(?:[^);]| )*/) || [])[0],
        name = (ua.match(/Chrome|MSIE|Safari|Opera|Firefox|Minefield/) || [])[0],
        version = global.opera && typeof opera.version === 'function' && opera.version(),
        mses = { '6.1': '7', '6.0': 'Vista', '5.2': 'Server 2003 / XP x64', '5.1': 'XP', '5.0': '2000', '4.0': 'NT', '4.9': 'ME' };

    // cleanup iOS
    os = (os || '').split(' like ')[0].replace(/_/g, '.');

    // IE platform tokens
    // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
    mses = os.indexOf('Windows') > -1 && mses[(os.match(/[456]\.\d/) || [])[0]];
    if (mses) {
      os = 'Windows ' + mses;
    }
    if (!version) {
      version = name && (ua.match(RegExp('(?:Version|' + name + ')[ /]([^ ;]*)')) || [])[1];
    }
    result = {
      'name':        name ? description.push(name) && name : null,
      'version':     version ? description.push(version) && version : null,
      'os':          os ? description.push('on ' + os) && os : null,
      'description': description.length ? description.join(' ') : 'unknown platform',
      'toString':    function() { return this.description; }
    };

    // lazy defined
    function getPlatform() { return result; }
    this.getPlatform = getPlatform;
    return result;
  }

  function noop() { }

  /*--------------------------------------------------------------------------*/

  function bestOf(times, count, synchronous) {
    var best,
        finished = 0,
        i = times,
        me = this;

    me.reset();
    me.running = true;
    me.onStart(me);

    while (i--) {
      (function() {
        var clone = me.clone();
        clone.onCycle =
        clone.onStart = me.onCycle || noop;
        clone.onStop = function() {
          if (!best || clone.period < best.period) {
            best = clone;
          }
          if (++finished === times) {
            if (best.error) {
              me.error = best.error;
            }
            me.count = best.count;
            me.hz = best.hz;
            me.period = best.period;
            me.running = false;
            me.time = best.time;
            me.onStop(me);
          }
        };
        clone.run(count, synchronous);
      }());
    }
  }

  function clone() {
    var key,
        me = this,
        result = new me.constructor(me.fn, me.options);

    for (key in me) {
      if (!result[key]) {
        result[key] = me[key];
      }
    }
    result.reset();
    return result;
  }

  function reset() {
    var me = this;
    delete me.count;
    delete me.error;
    delete me.hz;
    delete me.period;
    delete me.running;
    delete me.time;
  }

  function run(count, synchronous) {
    var me = this;
    // ensure calibration test has run
    if (!calibrate(function() {
          if (synchronous) {
            me.run(count, synchronous);
          } else {
            setTimeout(function() {
              me.run(count);
            }, me.CYCLE_DELAY * 1e3);
          }
        })) {
      me.reset();
      me.running = true;
      me.count = count || me.INIT_COUNT;
      me.onStart(me);
      _run(me, synchronous);
    }
  }

  function _run(me, synchronous) {
    var start,
        fn = me.fn,
        i = me.count,
     calPeriod = Benchmark.CALIBRATION.period;

    try {
      // test execution loop
      start = new Date();
      while (i--) {
        fn();
      }

      // get time test took (in secs)
      me.time = Math.max(0,
        // avoid Infinity values if there is 0ms between start
        // and end times by forcing at least 1ms
        (Math.max(1, new Date() - start) / 1e3) -
        // subtract the base loop time
        (calPeriod ? calPeriod * me.count : 0));

      // per-operation time taken
      me.period = me.time / me.count;

      // ops per second
      me.hz = Math.round(1 / me.period);

      // do we need to do another run?
      me.running = me.time < me.MIN_TIME;

      // if so, compute how many times we should iterate
      if (me.running) {
        me.count += Math.ceil((me.MIN_TIME - me.time) / me.period);
        // stop running if the next cycle would exceed the max count allowed
        if (me.count > me.MAX_COUNT) {
          me.running = false;
        }
      }
    }
    catch (e) {
      me.reset();
      me.error = e;
    }

    me.onCycle(me);

    // figure out what to do next
    if (me.running) {
      // use a timeout to make sure the browser has a chance to finish rendering
      // any UI changes made, like updating the status message
      if (synchronous) {
        _run(me, synchronous);
      } else {
        setTimeout(function() {
          _run(me);
        }, me.CYCLE_DELAY * 1e3);
      }
    }
    else {
      me.onStop(me);
    }
  }

  /*--------------------------------------------------------------------------*/

  // test to establish iteration loop overhead
  Benchmark.CALIBRATION = new Calibration(noop);

  Benchmark.getPlatform = getPlatform;

  Benchmark.noop = noop;

  extend(Benchmark.prototype, {
    // delay between test cycles (secs)
    'CYCLE_DELAY' : 0.2,

    // initial number of iterations
    'INIT_COUNT' : 10,

    // max iterations allowed per cycle (used avoid locking up the browser)
    'MAX_COUNT' : 2e7, // 20 million

    // minimum time a test should take to get valid results (secs)
    'MIN_TIME' : 0.96,

    // callback invoked when one test cycle ends
    'onCycle' : noop,

    // callback invoked when test is started
    'onStart' : noop,

    // callback invoked when test is finished
    'onStop' : noop,

    // runs the test accepting the best of `n` attempts
    'bestOf' : bestOf,

    // create new benchmark with the same test and options
    'clone' : clone,

    // reset test state
    'reset' : reset,

    // run the test
    'run' : run
  });

  // expose
  global.Benchmark = Benchmark;

}(this));<|endoftext|>


<commit_before>import VDatePicker from '~components/VDatePicker'
import { test } from '~util/testing'
import { mount } from 'avoriaz'

const persianMonths = ['حمل', 'ثور', 'جوزا', 'سرطان',' اسد', 'سنبله' ,'میزان' ,'عقرب' ,'قوس', 'جدی' ,'دلو', 'حوت']

test('VDatePicker.js', ({ mount }) => {
  it('should display the correct date in title and header', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: new Date('November 1 2005')
      }
    })

    const title = wrapper.find('.picker--date__title-date div')[0]
    const header = wrapper.find('.picker--date__header-selector-date strong')[0]

    expect(title.text()).toBe('Tue, Nov 1')
    expect(header.text()).toBe('November 2005')
  })

  it('should match snapshot with default settings', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07'
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with pick-month prop', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        type: 'month'
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with dark theme', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        dark: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with allowed dates', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        allowedDates: { min: '2013-05-03', max: '2013-05-19' }
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with allowed dates and pick-month prop', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05',
        type: 'month',
        allowedDates: ['2013-01', '2013-03', '2013-05', '2013-07', '2013-09']
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with no title', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        noTitle: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with first day of week', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        firstDayOfWeek: 2
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  // Avoriaz/Jsdom (?) doesn't fully support date formatting using locale
  // This should be tested in browser env
  it('should match snapshot with locale', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        locale: 'fa-AF'
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with title/header formatting functions', () => {
    const dateFormat = date => `${date.getFullYear() * 2} ${persianMonths[11 - date.getMonth()]}`
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: new Date('November 1 2005'),
        headerDateFormat: dateFormat,
        titleDateFormat: dateFormat
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with month formatting functions', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: new Date('November 1 2005'),
        type: 'month',
        monthFormat: date => {
          return persianMonths[11 - date.getMonth()]
        }
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })
})
<commit_msg>Skip randomly failing VDatePicker test (#1854)<commit_after>import VDatePicker from '~components/VDatePicker'
import { test } from '~util/testing'
import { mount } from 'avoriaz'

const persianMonths = ['حمل', 'ثور', 'جوزا', 'سرطان',' اسد', 'سنبله' ,'میزان' ,'عقرب' ,'قوس', 'جدی' ,'دلو', 'حوت']

test('VDatePicker.js', ({ mount }) => {
  it('should display the correct date in title and header', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: new Date('November 1 2005')
      }
    })

    const title = wrapper.find('.picker--date__title-date div')[0]
    const header = wrapper.find('.picker--date__header-selector-date strong')[0]

    expect(title.text()).toBe('Tue, Nov 1')
    expect(header.text()).toBe('November 2005')
  })

  it('should match snapshot with default settings', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07'
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with pick-month prop', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        type: 'month'
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with dark theme', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        dark: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with allowed dates', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        allowedDates: { min: '2013-05-03', max: '2013-05-19' }
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with allowed dates and pick-month prop', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05',
        type: 'month',
        allowedDates: ['2013-01', '2013-03', '2013-05', '2013-07', '2013-09']
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with no title', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        noTitle: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with first day of week', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        firstDayOfWeek: 2
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  // TODO: This fails in different ways for multiple people
  // Avoriaz/Jsdom (?) doesn't fully support date formatting using locale
  // This should be tested in browser env
  it.skip('should match snapshot with locale', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: '2013-05-07',
        locale: 'fa-AF'
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with title/header formatting functions', () => {
    const dateFormat = date => `${date.getFullYear() * 2} ${persianMonths[11 - date.getMonth()]}`
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: new Date('November 1 2005'),
        headerDateFormat: dateFormat,
        titleDateFormat: dateFormat
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should match snapshot with month formatting functions', () => {
    const wrapper = mount(VDatePicker, {
      propsData: {
        value: new Date('November 1 2005'),
        type: 'month',
        monthFormat: date => {
          return persianMonths[11 - date.getMonth()]
        }
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
  })
})
<|endoftext|>


<commit_before>/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:false, strict:true, undef:true, unused:true, curly:true, node:true, indent:4, maxerr:50, globalstrict:true */

"use strict";

var fishback = require("../lib/fishback");
var http = require("http");

var PORT = 8080;

var client = new fishback.Client("www.bbc.co.uk", "80");
client.on('newRequest', function (req) {
    console.info("CLIENT.newRequest " + req.method + " " + req.url);
});
client.on('newResponse', function (res) {
    console.info("CLIENT.newResponse " + res.method + " " + res.url);
});

var proxy = fishback.createProxy(client);
proxy.on('newRequest', function (req) {
    console.info("PROXY.newRequest " + req.method + " " + req.url);
});
proxy.on('newResponse', function (res) {
    console.info("PROXY.newResponse " + res.method + " " + res.url);
});

var server = new http.Server();
server.on('request', proxy.request.bind(proxy));
server.listen(PORT, function () {
    console.info("Listening on port " + PORT);
    console.info();
    console.info("Try:");
    console.info();
    console.info("  $ curl -s -i http://localhost:" + PORT + "/");
});
<commit_msg>Extract constants<commit_after>/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:false, strict:true, undef:true, unused:true, curly:true, node:true, indent:4, maxerr:50, globalstrict:true */

"use strict";

var fishback = require("../lib/fishback");
var http = require("http");

var PORT = 8080;
var BACKEND_HOST = "www.bbc.co.uk";
var BACKEND_PORT = "80";

var client = new fishback.Client(BACKEND_HOST, BACKEND_PORT);
client.on('newRequest', function (req) {
    console.info("CLIENT.newRequest " + req.method + " " + req.url);
});
client.on('newResponse', function (res) {
    console.info("CLIENT.newResponse " + res.method + " " + res.url);
});

var proxy = fishback.createProxy(client);
proxy.on('newRequest', function (req) {
    console.info("PROXY.newRequest " + req.method + " " + req.url);
});
proxy.on('newResponse', function (res) {
    console.info("PROXY.newResponse " + res.method + " " + res.url);
});

var server = new http.Server();
server.on('request', proxy.request.bind(proxy));
server.listen(PORT, function () {
    console.info("Listening on port " + PORT);
    console.info();
    console.info("Try:");
    console.info();
    console.info("  $ curl -s -i http://localhost:" + PORT + "/");
});
<|endoftext|>


<commit_before>'use strict'

import fs from 'fs'
import test from 'ava'
import postcss from 'postcss'
import isPresent from 'is-present'
import getVariables from '..'

test('postcss-get-variables', t => {
  t.plan(2)

  postcss()
    .use(getVariables(variables => {
      t.true(isPresent(variables))
      t.true(isPresent(variables['primary-color']))
    }))
    .process(fixture('basic'))
    .catch(error => {
      console.log(error)
    })
})

function fixture (name) {
  return fs.readFileSync(`./test/fixtures/${name}.css`, 'utf8').toString()
}
<commit_msg>add: more test case<commit_after>'use strict'

import fs from 'fs'
import test from 'ava'
import postcss from 'postcss'
import isPresent from 'is-present'
import getVariables from '..'

test('postcss-get-variables', t => {
  t.plan(3)

  postcss()
    .use(getVariables(variables => {
      t.true(isPresent(variables))
      t.true(isPresent(variables['primary-color']))
      t.true(Object.keys(variables).length === 3)
    }))
    .process(fixture('basic'))
    .catch(error => {
      console.log(error)
    })
})

function fixture (name) {
  return fs.readFileSync(`./test/fixtures/${name}.css`, 'utf8').toString()
}
<|endoftext|>


<commit_before>const test = require('./');
const db = require('../models');
const User = require('../models/user');
const Badge = require('../models/badge');
const BadgeInstance = require('../models/badge-instance');
const util = require('../lib/util');

const TESTUSER = 'brian@example.org';

test.applyFixtures({
  'pure-science': new Badge({
    shortname: 'pure-science',
    categories: ['science'],
    name: 'Pure Science',
    description: 'for sciencing',
    image: Buffer(1),
  }),
  'pure-math': new Badge({
    shortname: 'pure-math',
    categories: ['math'],
    name: 'Math',
    description: 'for mathing',
    image: Buffer(1),
  }),
  'science-and-math': new Badge({
    shortname: 'science-and-math',
    categories: ['science', 'math'],
    name: 'Science and Math',
    description: 'for sciencing and mathing',
    image: Buffer(1),
  }),
  'earned-badge': new Badge({
    _id: '1234',
    shortname: 'earned',
    categories: ['science', 'math'],
    name: 'Earned',
    description: 'should not come up',
    image: Buffer(1),
  }),
  'instance': new BadgeInstance({
    user: TESTUSER,
    badge: '1234',
  }),
}, function (fx) {

  test('Recommendation, no user', function (t) {
    const pureScience = fx['pure-science'];
    pureScience.getSimilar(function (err, badges) {
      const shortnames = badges.map(util.prop('shortname'));
      const hasMath = shortnames.some(has('pure-math'));
      const hasSelf = shortnames.some(has('pure-science'));
      const hasScienceAndMath = shortnames.some(has('science-and-math'));
      t.same(hasMath, false, 'should not have math');
      t.same(hasSelf, false, 'should not have self');
      t.same(hasScienceAndMath, true, 'should have science-and-math');
      t.end();
    });
  });

  test('Recommendation, with user', function (t) {
    const pureScience = fx['pure-science'];
    pureScience.getSimilar(TESTUSER, function (err, badges) {
      const names = badges.map(util.prop('shortname'));
      const hasMath = badges.some(has('pure-math'));
      const hasEarned = badges.some(has('earned'));

      t.same(hasMath, false, 'should not have math');
      t.same(hasEarned, false, 'should not have the earned badge');
      t.end();
    });
  });

  test('finish #', function (t) {
    db.close(); t.end();
  });

})

function has(name) {
  return function (n) {
    return n == name;
  };
}
<commit_msg>Start adding more fixtures for testing.<commit_after>const test = require('./');
const db = require('../models');
const User = require('../models/user');
const Badge = require('../models/badge');
const BadgeInstance = require('../models/badge-instance');
const util = require('../lib/util');

const TESTUSER = 'brian@example.org';

test.applyFixtures({
  'city-science': new Badge({
    shortname: 'city-science',
    categories: ['science'],
    name: 'City Science Badge',
    description: 'For earning a bunch of science badges',
    categoryAward: 'on',
    image: Buffer(1),
  }),
  'participation-science': new Badge({
    shortname: 'participation-science',
    categories: ['science'],
    name: 'Participation Science Badge',
    description: 'For participating in science',
    type: 'participation',
    activityType: 'online',
    image: Buffer(1),
  }),
  'offline-science': new Badge({
    shortname: 'offline-science',
    categories: ['science'],
    name: 'Offline Science Badge',
    description: 'For participating in offline science',
    type: 'achievement',
    activityType: 'offline',
    image: Buffer(1),
  }),
  'pure-science': new Badge({
    shortname: 'pure-science',
    categories: ['science'],
    name: 'Pure Science',
    description: 'for sciencing',
    type: 'skill',
    activityType: 'online',
    image: Buffer(1),
  }),
  'pure-math': new Badge({
    shortname: 'pure-math',
    categories: ['math'],
    name: 'Math',
    description: 'for mathing',
    type: 'skill',
    activityType: 'online',
    image: Buffer(1),
  }),
  'science-and-math': new Badge({
    shortname: 'science-and-math',
    categories: ['science', 'math'],
    name: 'Science and Math',
    type: 'skill',
    activityType: 'online',
    description: 'for sciencing and mathing',
    image: Buffer(1),
  }),
  'earned-badge': new Badge({
    _id: '1234',
    shortname: 'earned',
    categories: ['science', 'math'],
    name: 'Earned',
    type: 'skill',
    activityType: 'online',
    description: 'should not come up',
    image: Buffer(1),
  }),
  'instance': new BadgeInstance({
    user: TESTUSER,
    badge: '1234',
  }),
}, function (fx) {

  test('Recommendation, no user', function (t) {
    const pureScience = fx['pure-science'];
    pureScience.getSimilar(function (err, badges) {
      const shortnames = badges.map(util.prop('shortname'));
      const hasMath = shortnames.some(has('pure-math'));
      const hasSelf = shortnames.some(has('pure-science'));
      const hasScienceAndMath = shortnames.some(has('science-and-math'));
      t.same(hasMath, false, 'should not have math');
      t.same(hasSelf, false, 'should not have self');
      t.same(hasScienceAndMath, true, 'should have science-and-math');
      t.end();
    });
  });

  test('Recommendation, with user', function (t) {
    const pureScience = fx['pure-science'];
    pureScience.getSimilar(TESTUSER, function (err, badges) {
      const names = badges.map(util.prop('shortname'));
      const hasMath = badges.some(has('pure-math'));
      const hasEarned = badges.some(has('earned'));

      t.same(hasMath, false, 'should not have math');
      t.same(hasEarned, false, 'should not have the earned badge');
      t.end();
    });
  });

  test('finish #', function (t) {
    db.close(); t.end();
  });

})

function has(name) {
  return function (n) {
    return n == name;
  };
}
<|endoftext|>


<commit_before>/*global afterEach, beforeEach, describe, it */
'use strict';

var assert = require('assert');
var binCheck = require('bin-check');
var BinBuild = require('bin-build');
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var rm = require('rimraf');

describe('jpegoptim()', function () {
  afterEach(function (callback) {
    rm(path.join(__dirname, 'tmp'), callback);
  });

  beforeEach(function (callback) {
    fs.mkdir(path.join(__dirname, 'tmp'), callback);
  });

  it('should rebuild the jpegoptim binaries', function (callback) {
    var tmp = path.join(__dirname, 'tmp');
    var builder = new BinBuild()
      .src('https://github.com/tjko/jpegoptim/archive/RELEASE.1.3.1.tar.gz')
      .cfg('./configure --prefix="' + tmp + '"')
      .make('make install');

    builder.build(function (error) {
      assert(!error);
      assert(fs.existsSync(path.join(tmp, 'bin/jpegoptim')));
      callback();
    });
  });

  it('should return path to binary and verify that it is working', function (callback) {
      var binPath = require('../').path;

      binCheck(binPath, ['--version'], function (error, works) {
      callback(assert.equal(works, true));
    });
  });

  it('should minify a JPEG', function (callback) {
    var binPath = require('../').path;
    var args = [
      '--strip-all',
      '--all-progressive',
      '--dest=' + path.join(__dirname, 'tmp'),
      path.join(__dirname, 'fixtures/test.jpg')
    ];

    spawn(binPath, args).on('close', function () {
      var src = fs.statSync(path.join(__dirname, 'fixtures/test.jpg')).size;
      var dest = fs.statSync(path.join(__dirname, 'tmp/test.jpg')).size;

      callback(assert(dest < src));
    });
  });
});
<commit_msg>mkdir > mkdirSync<commit_after>/*global afterEach, beforeEach, describe, it */
'use strict';

var assert = require('assert');
var binCheck = require('bin-check');
var BinBuild = require('bin-build');
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var rm = require('rimraf');

describe('jpegoptim()', function () {
  afterEach(function (callback) {
    rm(path.join(__dirname, 'tmp'), callback);
  });

  beforeEach(function () {
    fs.mkdirSync(path.join(__dirname, 'tmp'));
  });

  it('should rebuild the jpegoptim binaries', function (callback) {
    var tmp = path.join(__dirname, 'tmp');
    var builder = new BinBuild()
      .src('https://github.com/tjko/jpegoptim/archive/RELEASE.1.3.1.tar.gz')
      .cfg('./configure --prefix="' + tmp + '"')
      .make('make install');

    builder.build(function (error) {
      assert(!error);
      assert(fs.existsSync(path.join(tmp, 'bin/jpegoptim')));
      callback();
    });
  });

  it('should return path to binary and verify that it is working', function (callback) {
      var binPath = require('../').path;

      binCheck(binPath, ['--version'], function (error, works) {
      callback(assert.equal(works, true));
    });
  });

  it('should minify a JPEG', function (callback) {
    var binPath = require('../').path;
    var args = [
      '--strip-all',
      '--all-progressive',
      '--dest=' + path.join(__dirname, 'tmp'),
      path.join(__dirname, 'fixtures/test.jpg')
    ];

    spawn(binPath, args).on('close', function () {
      var src = fs.statSync(path.join(__dirname, 'fixtures/test.jpg')).size;
      var dest = fs.statSync(path.join(__dirname, 'tmp/test.jpg')).size;

      callback(assert(dest < src));
    });
  });
});
<|endoftext|>


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

var child_process = require('child_process');
var fs            = require('fs');
var request       = require('request');
var rmrf          = require('rimraf');

/******************************************** HELPER METHODS **********************************************************/

var procs = [];

function run(command, args, opts, callback){
 var proc = child_process.spawn(command, args || [], opts || {});
 procs.push(proc);
 proc.stdout.once('data', function (data) {
  var done = function (){ proc.kill('SIGHUP'); };
  callback(data, done);
 });
}

function open(url, callback){
 request(url, function (error, res, body){
  if(error){ throw error; }
  res.body = body;
  callback(res);
 }).end();
}

function run_and_open(command, args, opts, url, mocha_done, callback){
 run(command, args, opts, function (data, child_done){
  open(url, function (res){
   callback(res, function (){
    child_done();
    if(mocha_done) mocha_done();
   });
  });
 });
}

/******************************************** TEST CASES **********************************************************/

describe('Swank', function (){

  after(function (){
    //Failures can leave some servers still running, so kill any existing processes
    procs.forEach(function (proc){
      proc.kill('SIGHUP');
    });
  });

  describe('file serve', function (){

    var stop_proc;

    before(function (done){
      this.timeout(5000);
      run('bin/swank', ['test/fixtures'], null, function (data, run_done){
        stop_proc = run_done;
        done();
      });
    });

    it('should serve files in the given directory', function (done){
     open('http://localhost:8000', function (res){

      expect(res.statusCode).to.equal(200);
      expect(res.body).to.contain('Hello, World');
      done();

     });
    });

    it('should not serve files not in the given directory', function (done){
     open('http://localhost:8000/nonsense.html', function (res){

      expect(res.statusCode).to.equal(404);
      done();

     });
    });

    it('should serve files with the correct content type', function (done){
     open('http://localhost:8000/peppers.png', function (res){

      expect(res.statusCode).to.equal(200);
      var content_type = res.headers['content-type'];
      expect(content_type).to.equal('image/png');
      done();

     });
    });

    after(function (){
      stop_proc();
    });

  });

  describe('arguments', function (){

    it('should use PORT environment variable if available', function (done){
     var env = Object.create( process.env );
     env.PORT = '1234';
     run_and_open('bin/swank', ['test/fixtures'], {env: env}, 'http://localhost:1234', done, function (res, done){

      expect(res.statusCode).to.equal(200);
      expect(res.body).to.contain('Hello, World');
      done();

     });
    });

    it('should display a help message', function (mocha_done){
     run('bin/swank', ['--help'], null, function (data, child_done){

      expect(data.toString()).to.contain('Usage: ');

      child_done();
      mocha_done();
     });
    });

    it('should serve files in the current directory by default', function (done){
     run_and_open('bin/swank', null, null, 'http://localhost:8000/test/fixtures', done, function (res, done){

      expect(res.statusCode).to.equal(200);
      expect(res.body).to.contain('Hello, World');
      done();

     });
    });

    it('should allow user-specified port', function (done){
     run_and_open('bin/swank',['--port=1234', 'test/fixtures'], null, 'http://localhost:1234', done, function (res, done){

      expect(res.statusCode).to.equal(200);
      expect(res.body).to.contain('Hello, World');
      done();

     });
    });

    it('should allow ngrok tunnelling', function (mocha_done){
      this.timeout(10000);
      run('bin/swank', ['--ngrok', 'test/fixtures/'], null, function (data, child_done){
        //url of ngrok server. implicit testing that url is valid
        var url = data.toString().match(/https?:\/\/[a-z0-9]+.ngrok.com/)[0].replace('https', 'http');
        open(url, function (res){
          expect(res.statusCode).to.equal(200);
          expect(res.body).to.contain('Hello, World');

          child_done();
          mocha_done();
        });
      });
    });
  });

  describe('modular', function (){
    it('should be usable as a module as well', function (done){

     var serve = require('../swank.js');
     serve({
      path: 'test/fixtures',
      port: 1234
     }, function (err, warn, url){
      expect(err).not.to.exist;
      expect(warn).not.to.exist;
      open(url, function (res){
       expect(res.statusCode).to.equal(200);
       expect(res.body).to.contain('Hello, World');
       done();
      });
     });

    });
  });

  describe('watch', function (){
    var proc, stop_watching;

    //start watch server
    before(function(done){
      //make a bunch of files
      fs.mkdirSync('test/fixtures/many');
      for(var i = 0; i<100; i++){
        fs.writeFileSync('test/fixtures/many/'+i+'.txt', '');
      }
      run('bin/swank', ['--watch', '--path', 'test/fixtures'], null, function (data, run_done){
        proc = data;
        stop_watching = run_done;
        done();
      });
    });

    it('should insert livereload.js', function(mocha_done){
      open({url: 'http://localhost:8000', headers: {'accept': 'text/html'}}, function (res){

        expect(res.statusCode).to.equal(200);
        expect(res.body).to.contain('livereload.js');
        mocha_done();

      });
    });

    it('should be running a livereload server', function (mocha_done){

      open('http://localhost:35729', function (res){
        expect(res.statusCode).to.equal(200);
        mocha_done();
      });

    });

    it('shouldn\'t crash when changing many files', function (mocha_done){
      this.timeout(8000);
      rmrf.sync('test/fixtures/many');
      setTimeout(function(){ //give the server a chance to die
        open('http://localhost:35729', function (res){
          //livereload server should still be running
          expect(res.statusCode).to.equal(200);
          mocha_done();
        });
      }, 7000);
    });

    //cleanup and stop watch server
    after(function (){
      rmrf.sync('test/fixtures/many');
      stop_watching();
    });
  });
});<commit_msg>wrote test<commit_after>var expect = require('chai').expect;

var child_process = require('child_process');
var fs            = require('fs');
var request       = require('request');
var rmrf          = require('rimraf');

/******************************************** HELPER METHODS **********************************************************/

var procs = [];

function run(command, args, opts, callback){
 var proc = child_process.spawn(command, args || [], opts || {});
 procs.push(proc);
 proc.stdout.once('data', function (data) {
  var done = function (){ proc.kill('SIGHUP'); };
  callback(data, done);
 });
}

function open(url, callback){
 request(url, function (error, res, body){
  if(error){ throw error; }
  res.body = body;
  callback(res);
 }).end();
}

function run_and_open(command, args, opts, url, mocha_done, callback){
 run(command, args, opts, function (data, child_done){
  open(url, function (res){
   callback(res, function (){
    child_done();
    if(mocha_done) mocha_done();
   });
  });
 });
}

/******************************************** TEST CASES **********************************************************/

describe('Swank', function (){

  after(function (){
    //Failures can leave some servers still running, so kill any existing processes
    procs.forEach(function (proc){
      proc.kill('SIGHUP');
    });
  });

  describe('file serve', function (){

    var stop_proc;

    before(function (done){
      this.timeout(5000);
      run('bin/swank', ['test/fixtures'], null, function (data, run_done){
        stop_proc = run_done;
        done();
      });
    });

    it('should serve files in the given directory', function (done){
     open('http://localhost:8000', function (res){

      expect(res.statusCode).to.equal(200);
      expect(res.body).to.contain('Hello, World');
      done();

     });
    });

    it('should not serve files not in the given directory', function (done){
     open('http://localhost:8000/nonsense.html', function (res){

      expect(res.statusCode).to.equal(404);
      done();

     });
    });

    it('should serve files with the correct content type', function (done){
     open('http://localhost:8000/peppers.png', function (res){

      expect(res.statusCode).to.equal(200);
      var content_type = res.headers['content-type'];
      expect(content_type).to.equal('image/png');
      done();

     });
    });

    after(function (){
      stop_proc();
    });

  });

  describe('arguments', function (){

    it('should use PORT environment variable if available', function (done){
     var env = Object.create( process.env );
     env.PORT = '1234';
     run_and_open('bin/swank', ['test/fixtures'], {env: env}, 'http://localhost:1234', done, function (res, done){

      expect(res.statusCode).to.equal(200);
      expect(res.body).to.contain('Hello, World');
      done();

     });
    });

    it('should display a help message', function (mocha_done){
     run('bin/swank', ['--help'], null, function (data, child_done){

      expect(data.toString()).to.contain('Usage: ');

      child_done();
      mocha_done();
     });
    });

    it('should serve files in the current directory by default', function (done){
     run_and_open('bin/swank', null, null, 'http://localhost:8000/test/fixtures', done, function (res, done){

      expect(res.statusCode).to.equal(200);
      expect(res.body).to.contain('Hello, World');
      done();

     });
    });

    it('should allow user-specified port', function (done){
     run_and_open('bin/swank',['--port=1234', 'test/fixtures'], null, 'http://localhost:1234', done, function (res, done){

      expect(res.statusCode).to.equal(200);
      expect(res.body).to.contain('Hello, World');
      done();

     });
    });

    it('should allow ngrok tunnelling', function (mocha_done){
      this.timeout(10000);
      run('bin/swank', ['--ngrok', 'test/fixtures/'], null, function (data, child_done){
        //url of ngrok server. implicit testing that url is valid
        var url = data.toString().match(/https?:\/\/[a-z0-9]+.ngrok.com/)[0].replace('https', 'http');
        open(url, function (res){
          expect(res.statusCode).to.equal(200);
          expect(res.body).to.contain('Hello, World');

          child_done();
          mocha_done();
        });
      });
    });

  });

  describe('modular', function (){
    it('should be usable as a module as well', function (done){

     var serve = require('../swank.js');
     serve({
      path: 'test/fixtures',
      port: 1234
     }, function (err, warn, url){
      expect(err).not.to.exist;
      expect(warn).not.to.exist;
      open(url, function (res){
       expect(res.statusCode).to.equal(200);
       expect(res.body).to.contain('Hello, World');
       done();
      });
     });

    });
  });

  describe('watch', function (){
    var proc, stop_watching;

    //start watch server
    before(function(done){
      //make a bunch of files
      fs.mkdirSync('test/fixtures/many');
      for(var i = 0; i<100; i++){
        fs.writeFileSync('test/fixtures/many/'+i+'.txt', '');
      }
      run('bin/swank', ['--watch', '--path', 'test/fixtures'], null, function (data, run_done){
        proc = data;
        stop_watching = run_done;
        done();
      });
    });

    it('should insert livereload.js', function(mocha_done){
      open({url: 'http://localhost:8000', headers: {'accept': 'text/html'}}, function (res){

        expect(res.statusCode).to.equal(200);
        expect(res.body).to.contain('livereload.js');
        mocha_done();

      });
    });

    it('should be running a livereload server', function (mocha_done){

      open('http://localhost:35729', function (res){
        expect(res.statusCode).to.equal(200);
        mocha_done();
      });

    });

    it('shouldn\'t crash when changing many files', function (mocha_done){
      this.timeout(8000);
      rmrf.sync('test/fixtures/many');
      setTimeout(function(){ //give the server a chance to die
        open('http://localhost:35729', function (res){
          //livereload server should still be running
          expect(res.statusCode).to.equal(200);
          mocha_done();
        });
      }, 7000);
    });

    //cleanup and stop watch server
    after(function (){
      rmrf.sync('test/fixtures/many');
      stop_watching();
    });
  });

  describe('watch+ngrok', function(){

    it('should allow ngrok tunnelling AND a watch server', function(mocha_done){
      this.timeout(10000);
      run('bin/swank', ['--ngrok', '--watch', '--path', 'test/fixtures/'], null, function (data, child_done){
        //url of ngrok server. implicit testing that url is valid
        var nrok_url = data.toString().match(/https?:\/\/[a-z0-9]+.ngrok.com/)[0].replace('https', 'http');

        open(nrok_url, function (res){
          expect(res.statusCode).to.equal(200);
          expect(res.body).to.contain('Hello, World');

          expect(res.body).to.contain('livereload.js');
          expect(res.body).to.contain('ngrok.com');

          child_done();
          mocha_done();
        });
      });
    });

  });
});<|endoftext|>


<commit_before>var pmModule = require("../lib/proxmox")('root@pam', 'j2x4y7S5', '10.32.5.24');
var assert = require("assert");

pmModule.qemu.getStatusCurrent('proxmoxTestbak',100,function(err, response){
  if (err) throw err;
  else {
    data = JSON.parse(response);
  console.log(data);
  }
});
<commit_msg>quick fix<commit_after>var pmModule = require("../lib/proxmox")('user', 'pass', 'ip');
var assert = require("assert");

pmModule.qemu.getStatusCurrent('proxmoxTestbak',100,function(err, response){
  if (err) throw err;
  else {
    data = JSON.parse(response);
  console.log(data);
  }
});
<|endoftext|>


<commit_before>/* global require, describe, it */
'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	CONST = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'compute-const-max-safe-integer', function tests() {

	it( 'should export a number', function test() {
		expect( CONST ).to.be.a( 'number' );
	});

});
<commit_msg>Update tests<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var pow = require( 'math-power' );
var MAX_SAFE_INTEGER = require( './../lib' );

// TESTS //

tape( 'main export is a number', function test( t ) {
	t.equal( typeof MAX_SAFE_INTEGER, 'number', 'main export is a number' );
	t.end();
});

tape( 'the exported value is 2**53-1', function test( t ) {
	t.equal( MAX_SAFE_INTEGER, pow(2,53)-1, 'returns 2**53-1' );
	t.end();
});
<|endoftext|>