<commit_before>module("Absolute animate Test", {
	beforeEach : function() {
		this.egAnimate = eg.invoke("animate",[jQuery,window]);
		this.$el1 = $("#box1");
		this.$el2 = $("#box2");
	},
	afterEach : function() {
		this.$el1.css("transform", "none");
		this.$el2.css("transform", "none");
	}
});

var ABSOLUTE_CASE = [
	{title : "rotate(45deg)", css : "rotate(45deg)", transform: "rotate(45deg)"},
	{title : "skewX(30deg) skewY(10deg)", css : "skewX(30deg) skewY(10deg)", transform: "skewX(30deg) skewY(10deg)"},
	{title : "translate(100px, 10px)", css : "translate(100px, 10px)", transform: "translate(100px, 10px)"},
	{title : "matrix(.5, .433, -.5, 1.033, 50, -10)", css : "matrix(.5, .433, -.5, 1.033, 50, -10)", transform: "matrix(.5, .433, -.5, 1.033, 50, -10)"},
	{title : "rotate(45deg) translate(38px)", css : "rotate(45deg) translate(38px)", transform: "rotate(45deg) translate(38px)"},
	{title : "multiplex transform: rotate & translate & skew & scale & matrix", css : "rotate(45deg) translateY(-68px) skewX(-30deg) scale(1.2) matrix(.5, .433, -.5, 1.033, 50, -10)", transform: "rotate(45deg) translateY(-68px) skewX(-30deg) scale(1.2) matrix(.5, .433, -.5, 1.033, 50, -10)"},
	{title : "translate(50%, 100%)", css : "translate(60px, 120px)", transform: "translate(50%, 100%)"},
	{title : "translate(20, 100%)", css : "translate(20px, 120px)", transform: "translate(20, 100%)"},
	{title : "translate(25%, 100px)", css : "translate(30px, 100px)", transform: "translate(25%, 100px)"}
];

$.each(ABSOLUTE_CASE, function(i, val) {
	//Given
	//ABSOLUTE_CASE

	test(val.title, function(assert) {
		var done = assert.async(),
			self = this;

		//When
		this.$el1
			.css("transform", val.css);

		this.$el2
			.animate({"transform" : val.transform}, function() {
				//Then
				var expected = self.egAnimate.toMatrix(val.css),
					actual = self.egAnimate.toMatrix(self.$el2.css("transform"));

				// Ignore very tiny difference.
				// Because output matrixes can be different with input matrixes.)
				$.each(expected[1], function(i) {
					expected[1][i] = parseFloat(expected[1][i]).toFixed(3);
					actual[1][i] = parseFloat(actual[1][i]).toFixed(3);
				});

				equal(actual[1].toString(), expected[1].toString());
				// setTimeout(function() {
				done();
				// }, 1000);

			});
	});
});

/**
 * On PhantomJS, 'Relative animate Test' case cannot be tested.
 * Because jQuery cannot get a start matrix which is latest position.
 *
 */
if ( navigator.userAgent.indexOf("PhantomJS") == -1 ) {
	module("Relative animate Test", {
		beforeEach : function() {
			this.egAnimate = eg.invoke("animate",[jQuery,window]);
		},
		afterEach : function() {
		}
	});

	var RELATIVE_CASE = [
		{title : "+=translate(100px, 0)", css : "translate(100px, 0)", transform: "+=translate(100px, 0)"},
		{title : "+=translate(0, 100px)", css : "translate(100px, 100px)", transform: "+=translate(0, 100px)"},
		{title : "+=translate(100, 100)", css : "translate(200px, 200px)", transform: "+=translate(100, 100)"},
		{title : "+=scale(2) translate(-100, -100)", css : "scale(2) translate(0px, 0px)", transform: "+=scale(2) translate(-100, -100)"},
		{title : "+=scale(0.5) rotate(30deg)", css : "rotate(30deg)", transform: "+=scale(0.5) rotate(30deg)"},
		{title : "+=rotate(-30deg) translate(10px, 50%)", css : "translate(10px, 60px)", transform: "+=rotate(-30deg) translate(10px, 50%)"}
	];

	$.each( RELATIVE_CASE, function(i, val) {
		//Given
		var $el1 = $("#box1"),
			$el2 = $("#box2");

		var initialTransform = "none";
		$el1.css("transform", initialTransform);
		$el2.css("transform", initialTransform);

		//RELATIVE_CASE
		test(val.title, function(assert) {
			var done = assert.async(),
				self = this;

			//When
			$el1
				.css("transform", val.css);

			$el2
				.animate({"transform" : val.transform},
					function() {
						//Then
						var expected = self.egAnimate.toMatrix(val.css),
						 	result = self.egAnimate.toMatrix($el2.css("transform"));

						// Ignore very tiny difference.
						// Because output matrixes can be different with input matrixes.)
						$.each(expected[1], function(i) {
							expected[1][i] = parseFloat(expected[1][i]).toFixed(3);
							result[1][i] = parseFloat(result[1][i]).toFixed(3);
						});

						equal(result[1].toString(), expected[1].toString());
						//setTimeout(function() {
							done();
						//}, 500);
					}
				);
		});
	});
}

module("3d animate Test", {
	beforeEach : function() {
		this.egAnimate = eg.invoke("animate",[jQuery,window]);
	},
	afterEach : function() {
	}
});

var ANI_3D_CASE = [
	{title : "translate3d(100px, 100px, 100px)", css : "translate3d(100px, 100px, 100px)", transform: "translate3d(100px, 100px, 100px)"}
];

/**
 * On PhantomJS, 'Relative animate Test' case cannot be tested.
 * Because jQuery cannot get a start matrix which is latest position.
 *
 */
if (navigator.userAgent.indexOf("PhantomJS") == -1) {
	ANI_3D_CASE.push({title : "+=translate(0px, 100px)", css : "translate3d(100px, 200px, 100px)", transform: "+=translate(0px, 100px)"});
	ANI_3D_CASE.push({title : "translate3d(100%, 200px, 0)", css : "translate3d(120px, 200px, 0)", transform: "translate3d(100%, 200px, 0)"});
}

$.each( ANI_3D_CASE, function(i, val) {
	//Given
	var $el1 = $("#box1"),
		$el2 = $("#box2");

	$el1.css("transform", "none");
	$el2.css("transform", "none");

	//RELATIVE_CASE
	test(val.title, function(assert) {
		var done = assert.async(),
			self = this;

		//When
		$el1
			.css( "transform", val.css );

		$el2
			.animate({"transform" : val.transform},
				function() {
					//Then
					var t1 = self.egAnimate.toMatrix(val.css),
					 	t2 = self.egAnimate.toMatrix($el2.css("transform"));

					if (t1[1].length < t2[1].length) {
						t1 = self.egAnimate.toMatrix3d(t1);
					} else if (t1[1].length > t2[1].length) {
						t2 = self.egAnimate.toMatrix3d(t2);
					}

					// Ignore very tiny difference.
					// Because output matrixes can be different with input matrixes.)
					$.each(t1[1], function(i) {
						t1[1][i] = parseFloat(t1[1][i]).toFixed(3);
						t2[1][i] = parseFloat(t2[1][i]).toFixed(3);
					});

					equal(t1[1].toString(), t2[1].toString());
					done();
				}
			);
	});
});
<commit_msg>test (animate) : Add more test case<commit_after>module("Absolute animate Test", {
	beforeEach : function() {
		this.egAnimate = eg.invoke("animate",[jQuery,window]);
		this.$el1 = $("#box1");
		this.$el2 = $("#box2");
	},
	afterEach : function() {
		this.$el1.css("transform", "none");
		this.$el2.css("transform", "none");
	}
});

var ABSOLUTE_CASE = [
	{title : "rotate(45deg)", css : "rotate(45deg)", transform: "rotate(45deg)"},
	{title : "skewX(30deg) skewY(10deg)", css : "skewX(30deg) skewY(10deg)", transform: "skewX(30deg) skewY(10deg)"},
	{title : "translate(100px, 10px)", css : "translate(100px, 10px)", transform: "translate(100px, 10px)"},
	{title : "matrix(.5, .433, -.5, 1.033, 50, -10)", css : "matrix(.5, .433, -.5, 1.033, 50, -10)", transform: "matrix(.5, .433, -.5, 1.033, 50, -10)"},
	{title : "rotate(45deg) translate(38px)", css : "rotate(45deg) translate(38px)", transform: "rotate(45deg) translate(38px)"},
	{title : "multiplex transform: rotate & translate & skew & scale & matrix", css : "rotate(45deg) translateY(-68px) skewX(-30deg) scale(1.2) matrix(.5, .433, -.5, 1.033, 50, -10)", transform: "rotate(45deg) translateY(-68px) skewX(-30deg) scale(1.2) matrix(.5, .433, -.5, 1.033, 50, -10)"},
	{title : "translate(50%, 100%)", css : "translate(60px, 120px)", transform: "translate(50%, 100%)"},
	{title : "translate(20, 100%)", css : "translate(20px, 120px)", transform: "translate(20, 100%)"},
	{title : "translate(25%, 100px)", css : "translate(30px, 100px)", transform: "translate(25%, 100px)"}
];

$.each(ABSOLUTE_CASE, function(i, val) {
	//Given
	//ABSOLUTE_CASE

	test(val.title, function(assert) {
		var done = assert.async(),
			self = this;

		//When
		this.$el1
			.css("transform", val.css);

		this.$el2
			.animate({"transform" : val.transform}, function() {
				//Then
				var expected = self.egAnimate.toMatrix(val.css),
					actual = self.egAnimate.toMatrix(self.$el2.css("transform"));

				// Ignore very tiny difference.
				// Because output matrixes can be different with input matrixes.)
				$.each(expected[1], function(i) {
					expected[1][i] = parseFloat(expected[1][i]).toFixed(3);
					actual[1][i] = parseFloat(actual[1][i]).toFixed(3);
				});

				equal(actual[1].toString(), expected[1].toString());
				// setTimeout(function() {
				done();
				// }, 1000);

			});
	});
});

/**
 * On PhantomJS, 'Relative animate Test' case cannot be tested.
 * Because jQuery cannot get a start matrix which is latest position.
 *
 */
if ( navigator.userAgent.indexOf("PhantomJS") == -1 ) {
	module("Relative animate Test", {
		beforeEach : function() {
			this.egAnimate = eg.invoke("animate",[jQuery,window]);
		},
		afterEach : function() {
		}
	});

	var RELATIVE_CASE = [
		{title : "+=translate(100px, 0)", css : "translate(100px, 0)", transform: "+=translate(100px, 0)"},
		{title : "+=translate(0, 100px)", css : "translate(100px, 100px)", transform: "+=translate(0, 100px)"},
		{title : "+=translate(100, 100)", css : "translate(200px, 200px)", transform: "+=translate(100, 100)"},
		{title : "+=scale(2) translate(-100, -100)", css : "scale(2) translate(0px, 0px)", transform: "+=scale(2) translate(-100, -100)"},
		{title : "+=scale(0.5) rotate(30deg)", css : "rotate(30deg)", transform: "+=scale(0.5) rotate(30deg)"},
		{title : "+=rotate(-30deg) translate(10px, 50%)", css : "translate(10px, 60px)", transform: "+=rotate(-30deg) translate(10px, 50%)"}
	];

	$.each( RELATIVE_CASE, function(i, val) {
		//Given
		var $el1 = $("#box1"),
			$el2 = $("#box2");

		var initialTransform = "none";
		$el1.css("transform", initialTransform);
		$el2.css("transform", initialTransform);

		//RELATIVE_CASE
		test(val.title, function(assert) {
			var done = assert.async(),
				self = this;

			//When
			$el1
				.css("transform", val.css);

			$el2
				.animate({"transform" : val.transform},
					function() {
						//Then
						var expected = self.egAnimate.toMatrix(val.css),
						 	result = self.egAnimate.toMatrix($el2.css("transform"));

						// Ignore very tiny difference.
						// Because output matrixes can be different with input matrixes.)
						$.each(expected[1], function(i) {
							expected[1][i] = parseFloat(expected[1][i]).toFixed(3);
							result[1][i] = parseFloat(result[1][i]).toFixed(3);
						});

						equal(result[1].toString(), expected[1].toString());
						//setTimeout(function() {
							done();
						//}, 500);
					}
				);
		});
	});
}

module("3d animate Test", {
	beforeEach : function() {
		this.egAnimate = eg.invoke("animate",[jQuery,window]);
	},
	afterEach : function() {
	}
});

var ANI_3D_CASE = [
	{title : "translate3d(100px, 100px, 100px)", css : "translate3d(100px, 100px, 100px)", transform: "translate3d(100px, 100px, 100px)"}
];

/**
 * On PhantomJS, 'Relative animate Test' case cannot be tested.
 * Because jQuery cannot get a start matrix which is latest position.
 *
 */
if (navigator.userAgent.indexOf("PhantomJS") == -1) {
	ANI_3D_CASE.push({title : "+=translate(0px, 100px)", css : "translate3d(100px, 200px, 100px)", transform: "+=translate(0px, 100px)"});
	ANI_3D_CASE.push({title : "translate3d(100%, 200px, 0)", css : "translate3d(120px, 200px, 0)", transform: "translate3d(100%, 200px, 0)"});
	ANI_3D_CASE.push({title : "translate3d(0, 0, 0)", css : "translate3d(0, 0, 0)", transform: "translate3d(0, 0, 0)"});
	ANI_3D_CASE.push({title : "+=scale(2) translate3d(-100, -100, 100)", css : "scale(2) translate3d(-100px, -100px, 100px)", transform: "+=scale(2) translate3d(-100, -100, 100)"});
}

$.each( ANI_3D_CASE, function(i, val) {
	//Given
	var $el1 = $("#box1"),
		$el2 = $("#box2");

	$el1.css("transform", "none");
	$el2.css("transform", "none");

	//RELATIVE_CASE
	test(val.title, function(assert) {
		var done = assert.async(),
			self = this;

		//When
		$el1
			.css( "transform", val.css );

		$el2
			.animate({"transform" : val.transform},
				function() {
					//Then
					var t1 = self.egAnimate.toMatrix(val.css),
					 	t2 = self.egAnimate.toMatrix($el2.css("transform"));

					if (t1[1].length < t2[1].length) {
						t1 = self.egAnimate.toMatrix3d(t1);
					} else if (t1[1].length > t2[1].length) {
						t2 = self.egAnimate.toMatrix3d(t2);
					}

					// Ignore very tiny difference.
					// Because output matrixes can be different with input matrixes.)
					$.each(t1[1], function(i) {
						t1[1][i] = parseFloat(t1[1][i]).toFixed(3);
						t2[1][i] = parseFloat(t2[1][i]).toFixed(3);
					});

					equal(t1[1].toString(), t2[1].toString());
					done();
				}
			);
	});
});
<|endoftext|>


<commit_before>/**
 * @fileOverview Ensures nsprc is as expected
 */

var expect = require('expect.js'),
    fs = require('fs');

/* global describe, it, before */
describe('nsp', function () {
    var nsprc,
        pkg;

    before(function () {
        nsprc = JSON.parse(fs.readFileSync('./.nsprc').toString());
        pkg = JSON.parse(fs.readFileSync('./package.json').toString());
    });

    it('must be a dev dependency', function () {
        expect(pkg.devDependencies && pkg.devDependencies.nsp).to.be.ok();
    });

    describe('nsprc', function () {
        it('must exist', function () {
            expect(nsprc).to.be.ok();
        });

        it('must not have any exclusion', function () {
            expect(nsprc.exceptions).to.eql([]);
        });

        it('must exclude only a known set of packages', function () {
            expect(nsprc.exclusions).to.eql(['postman-collection', 'postman-runtime']);
        });

        // if you are changing the version here, most probably you are better of removing the exclusion in first place.
        // remove the exclusion and check if nsp passes, else update the version here
        it('on excluded package\'s version change must reconsider removing exclusion', function () {
            expect(pkg.dependencies).to.have.property('postman-collection', '0.4.0');
            expect(pkg.dependencies).to.have.property('postman-runtime', '2.1.0');
        });
    });
});
<commit_msg>updated runtime version in the nsp test<commit_after>/**
 * @fileOverview Ensures nsprc is as expected
 */

var expect = require('expect.js'),
    fs = require('fs');

/* global describe, it, before */
describe('nsp', function () {
    var nsprc,
        pkg;

    before(function () {
        nsprc = JSON.parse(fs.readFileSync('./.nsprc').toString());
        pkg = JSON.parse(fs.readFileSync('./package.json').toString());
    });

    it('must be a dev dependency', function () {
        expect(pkg.devDependencies && pkg.devDependencies.nsp).to.be.ok();
    });

    describe('nsprc', function () {
        it('must exist', function () {
            expect(nsprc).to.be.ok();
        });

        it('must not have any exclusion', function () {
            expect(nsprc.exceptions).to.eql([]);
        });

        it('must exclude only a known set of packages', function () {
            expect(nsprc.exclusions).to.eql(['postman-collection', 'postman-runtime']);
        });

        // if you are changing the version here, most probably you are better of removing the exclusion in first place.
        // remove the exclusion and check if nsp passes, else update the version here
        it('on excluded package\'s version change must reconsider removing exclusion', function () {
            expect(pkg.dependencies).to.have.property('postman-collection', '0.4.0');
            expect(pkg.dependencies).to.have.property('postman-runtime', '2.2.0');
        });
    });
});
<|endoftext|>


<commit_before>/*
 * Copyright IBM Corporation 2017
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict'
var nock = require('nock')
var path = require('path')

exports.mockClientSDKNetworkRequest = function (applicationName) {
  return nock('https://mobilesdkgen.ng.bluemix.net')
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${applicationName}_iOS_SDK/ios_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithFile(
             200,
             path.join(__dirname, '../resources/dummy_iOS_SDK.zip'),
             { 'Content-Type': 'application/zip' }
           )
}

exports.mockClientSDKDownloadFailure = function (applicationName) {
  return nock('https://mobilesdkgen.ng.bluemix.net')
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${applicationName}_iOS_SDK/ios_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithError({ message: 'getaddrinfo ENOTFOUND', code: 'ENOTFOUND' })
}

exports.mockClientSDKGenerationFailure = function (applicationName) {
  return nock('https://mobilesdkgen.ng.bluemix.net')
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${applicationName}_iOS_SDK/ios_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FAILED' })
}

exports.mockClientSDKGenerationTimeout = function (applicationName) {
  return nock('https://mobilesdkgen.ng.bluemix.net')
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${applicationName}_iOS_SDK/ios_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .times(11)
           .reply(200, { status: 'VALIDATING' })
}

exports.mockServerSDKNetworkRequest = function (sdkName) {
  return nock('https://mobilesdkgen.ng.bluemix.net')
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${sdkName}_ServerSDK/server_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithFile(
             200,
             path.join(__dirname, '../resources/dummy_ServerSDK.zip'),
             { 'Content-Type': 'application/zip' }
           )
}

exports.mockServerSDKDownloadFailure = function (sdkName) {
  return nock('https://mobilesdkgen.ng.bluemix.net')
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${sdkName}_ServerSDK/server_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithError({ message: 'getaddrinfo ENOTFOUND', code: 'ENOTFOUND' })
}

exports.mockServerSDKPackageRequest = function (sdkName) {
  return nock('https://mobilesdkgen.ng.bluemix.net')
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${sdkName}_ServerSDK/server_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithFile(
             200,
             path.join(__dirname, '../resources/dummy_PackageSDK.zip'),
             { 'Content-Type': 'application/zip' }
           )
}
<commit_msg>fix: allow mock to use url from config.js (#455)<commit_after>/*
 * Copyright IBM Corporation 2017
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict'
var nock = require('nock')
var path = require('path')
var config = require('../../config')
var sdkGenUrl = config.sdkGenURL.match('^(https?://[^/]+)')[1]

exports.mockClientSDKNetworkRequest = function (applicationName) {
  return nock(sdkGenUrl)
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${applicationName}_iOS_SDK/ios_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithFile(
             200,
             path.join(__dirname, '../resources/dummy_iOS_SDK.zip'),
             { 'Content-Type': 'application/zip' }
           )
}

exports.mockClientSDKDownloadFailure = function (applicationName) {
  return nock(sdkGenUrl)
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${applicationName}_iOS_SDK/ios_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithError({ message: 'getaddrinfo ENOTFOUND', code: 'ENOTFOUND' })
}

exports.mockClientSDKGenerationFailure = function (applicationName) {
  return nock(sdkGenUrl)
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${applicationName}_iOS_SDK/ios_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FAILED' })
}

exports.mockClientSDKGenerationTimeout = function (applicationName) {
  return nock(sdkGenUrl)
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${applicationName}_iOS_SDK/ios_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .times(11)
           .reply(200, { status: 'VALIDATING' })
}

exports.mockServerSDKNetworkRequest = function (sdkName) {
  return nock(sdkGenUrl)
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${sdkName}_ServerSDK/server_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithFile(
             200,
             path.join(__dirname, '../resources/dummy_ServerSDK.zip'),
             { 'Content-Type': 'application/zip' }
           )
}

exports.mockServerSDKDownloadFailure = function (sdkName) {
  return nock(sdkGenUrl)
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${sdkName}_ServerSDK/server_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithError({ message: 'getaddrinfo ENOTFOUND', code: 'ENOTFOUND' })
}

exports.mockServerSDKPackageRequest = function (sdkName) {
  return nock(sdkGenUrl)
           .filteringRequestBody(/.*/, '*')
           .post(`/sdkgen/api/generator/${sdkName}_ServerSDK/server_swift`, '*')
           .reply(200, { job: { id: 'myid' } })
           .get('/sdkgen/api/generator/myid/status')
           .reply(200, { status: 'FINISHED' })
           .get('/sdkgen/api/generator/myid')
           .replyWithFile(
             200,
             path.join(__dirname, '../resources/dummy_PackageSDK.zip'),
             { 'Content-Type': 'application/zip' }
           )
}
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var childProcess = require('child_process');
var del = require('del');
var fs = require('fs');
var gulp = require('gulp');
var path = require('path');
var rewire = require('rewire');
var sinon = require('sinon');
var through = require('through2');

var registerTasks = rewire('../../../lib/tasks/index');

describe('Index Tasks', function() {
	before(function() {
		this.initialCwd_ = process.cwd();
		process.chdir(path.resolve(__dirname, '../../assets'));
	});

	beforeEach(function(done) {
		del('build').then(function() {
			fs.mkdirSync('build');
			fs.writeFileSync('build/temp.js', 'var a = 2;');
			gulp.reset();
			done();
		});
	});

	after(function() {
		process.chdir(this.initialCwd_);
	});

	describe('Clean', function() {
		it('should clean the build directory', function(done) {
			registerTasks();

			gulp.start('clean', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:clean', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				done();
			});
		});
	});

	describe('Build', function() {
		it('should clean the build directory', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should build css files', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build', function() {
				assert.ok(fs.existsSync('build/all.css'));
				done();
			});
		});

		it('should only build js files to globals by default', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build', function() {
				assert.ok(!fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(!fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should run the js build tasks specified by the "mainBuildJsTasks" option', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				mainBuildJsTasks: ['build:amd', 'build:jquery']
			});

			gulp.start('build', function() {
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(!fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:build', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/all.css'));
				done();
			});
		});
	});

	describe('Build JS', function() {
		it('should not clean the build directory', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:js', function() {
				assert.ok(fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should only build js files to globals by default', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:js', function() {
				assert.ok(!fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(!fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should run the js build tasks specified by the "mainBuildJsTasks" option', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				mainBuildJsTasks: ['build:amd', 'build:jquery']
			});

			gulp.start('build:js', function() {
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(!fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:build:js', function() {
				assert.ok(fs.existsSync('build/temp.js'));
				assert.ok(!fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(!fs.existsSync('build/jquery'));
				done();
			});
		});
	});

	describe('Build All', function() {
		it('should clean the build directory', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:all', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should build css files', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:all', function() {
				assert.ok(fs.existsSync('build/all.css'));
				done();
			});
		});

		it('should build js files to all available build formats', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				mainBuildJsTasks: ['build:amd', 'build:jquery']
			});

			gulp.start('build:all', function() {
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:build:all', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				assert.ok(fs.existsSync('build/all.css'));
				done();
			});
		});
	});

	describe('Build All JS', function() {
		it('should not clean the build directory', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:all:js', function() {
				assert.ok(fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should build js files to all available build formats', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				mainBuildJsTasks: ['build:amd', 'build:jquery']
			});

			gulp.start('build:all:js', function() {
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:build:all:js', function() {
				assert.ok(fs.existsSync('build/temp.js'));
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});
	});

	describe('Watch', function() {
		beforeEach(function() {
			sinon.stub(gulp, 'watch');
		});

		afterEach(function() {
			gulp.watch.restore();
		});

		it('should run tasks when source files change', function() {
			registerTasks();
			var doneCallback = sinon.stub();

			var task = gulp.start('watch', doneCallback);
			assert.strictEqual(0, doneCallback.callCount);
			assert.strictEqual(3, gulp.watch.callCount);
			assert.deepEqual(['build:js'], gulp.watch.args[0][1]);
			assert.deepEqual(['soy'], gulp.watch.args[1][1]);
			assert.deepEqual(['css'], gulp.watch.args[2][1]);

			task.stop(null, true);
		});

		it('should use task prefix when it\'s defined', function() {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});
			var doneCallback = sinon.stub();

			var task = gulp.start('myPrefix:watch', doneCallback);
			assert.strictEqual(0, doneCallback.callCount);
			assert.strictEqual(3, gulp.watch.callCount);
			assert.deepEqual(['myPrefix:build:js'], gulp.watch.args[0][1]);
			assert.deepEqual(['myPrefix:soy'], gulp.watch.args[1][1]);
			assert.deepEqual(['myPrefix:css'], gulp.watch.args[2][1]);

			task.stop(null, true);
		});
	});

	describe('Format', function() {
		var stubs = {};

		before(function() {
			stubs.esformatter = getStreamFn();
			sinon.spy(stubs, 'esformatter');
			registerTasks.__set__('esformatter', stubs.esformatter);
		});

		beforeEach(function() {
			stubs.esformatter.callCount = 0;
		});

		it('should call esformatter', function(done) {
			registerTasks();

			gulp.start('format', function() {
				assert.strictEqual(1, stubs.esformatter.callCount);
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:format', function() {
				assert.strictEqual(1, stubs.esformatter.callCount);
				done();
			});
		});
	});

	describe('Lint', function() {
		var stubs = {};

		before(function() {
			stubs.jshint = getStreamFn();
			stubs.jshint.reporter = getStreamFn();
			sinon.spy(stubs, 'jshint');
			registerTasks.__set__('jshint', stubs.jshint);
		});

		beforeEach(function() {
			stubs.jshint.callCount = 0;
		});

		it('should call jshint', function(done) {
			registerTasks();

			gulp.start('lint', function() {
				assert.strictEqual(1, stubs.jshint.callCount);
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:lint', function() {
				assert.strictEqual(1, stubs.jshint.callCount);
				done();
			});
		});
	});

	describe('Docs', function() {
		beforeEach(function() {
			sinon.stub(childProcess, 'execFile');
		});

		afterEach(function() {
			childProcess.execFile.restore();
		});

		it('should call jsdoc cli to generate docs', function(done) {
			registerTasks();

			gulp.start('docs', function() {
				assert.strictEqual(1, childProcess.execFile.callCount);
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:docs', function() {
				assert.strictEqual(1, childProcess.execFile.callCount);
				done();
			});
		});
	});
});

function getStreamFn() {
	return function() {
		return through.obj(function(file, encoding, callback) {
			this.push(file);
			callback();
		});
	};
}
<commit_msg>Fixes docs test<commit_after>'use strict';

var assert = require('assert');
var childProcess = require('child_process');
var del = require('del');
var fs = require('fs');
var gulp = require('gulp');
var path = require('path');
var rewire = require('rewire');
var sinon = require('sinon');
var through = require('through2');

var registerTasks = rewire('../../../lib/tasks/index');

describe('Index Tasks', function() {
	before(function() {
		this.initialCwd_ = process.cwd();
		process.chdir(path.resolve(__dirname, '../../assets'));
	});

	beforeEach(function(done) {
		del('build').then(function() {
			fs.mkdirSync('build');
			fs.writeFileSync('build/temp.js', 'var a = 2;');
			gulp.reset();
			done();
		});
	});

	after(function() {
		process.chdir(this.initialCwd_);
	});

	describe('Clean', function() {
		it('should clean the build directory', function(done) {
			registerTasks();

			gulp.start('clean', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:clean', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				done();
			});
		});
	});

	describe('Build', function() {
		it('should clean the build directory', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should build css files', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build', function() {
				assert.ok(fs.existsSync('build/all.css'));
				done();
			});
		});

		it('should only build js files to globals by default', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build', function() {
				assert.ok(!fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(!fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should run the js build tasks specified by the "mainBuildJsTasks" option', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				mainBuildJsTasks: ['build:amd', 'build:jquery']
			});

			gulp.start('build', function() {
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(!fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:build', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/all.css'));
				done();
			});
		});
	});

	describe('Build JS', function() {
		it('should not clean the build directory', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:js', function() {
				assert.ok(fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should only build js files to globals by default', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:js', function() {
				assert.ok(!fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(!fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should run the js build tasks specified by the "mainBuildJsTasks" option', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				mainBuildJsTasks: ['build:amd', 'build:jquery']
			});

			gulp.start('build:js', function() {
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(!fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:build:js', function() {
				assert.ok(fs.existsSync('build/temp.js'));
				assert.ok(!fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(!fs.existsSync('build/globals-jquery'));
				assert.ok(!fs.existsSync('build/jquery'));
				done();
			});
		});
	});

	describe('Build All', function() {
		it('should clean the build directory', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:all', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should build css files', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:all', function() {
				assert.ok(fs.existsSync('build/all.css'));
				done();
			});
		});

		it('should build js files to all available build formats', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				mainBuildJsTasks: ['build:amd', 'build:jquery']
			});

			gulp.start('build:all', function() {
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:build:all', function() {
				assert.ok(!fs.existsSync('build/temp.js'));
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				assert.ok(fs.existsSync('build/all.css'));
				done();
			});
		});
	});

	describe('Build All JS', function() {
		it('should not clean the build directory', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js'
			});

			gulp.start('build:all:js', function() {
				assert.ok(fs.existsSync('build/temp.js'));
				done();
			});
		});

		it('should build js files to all available build formats', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				mainBuildJsTasks: ['build:amd', 'build:jquery']
			});

			gulp.start('build:all:js', function() {
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				buildSrc: 'src/Bar.js',
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:build:all:js', function() {
				assert.ok(fs.existsSync('build/temp.js'));
				assert.ok(fs.existsSync('build/amd'));
				assert.ok(fs.existsSync('build/globals'));
				assert.ok(fs.existsSync('build/globals-jquery'));
				assert.ok(fs.existsSync('build/jquery'));
				done();
			});
		});
	});

	describe('Watch', function() {
		beforeEach(function() {
			sinon.stub(gulp, 'watch');
		});

		afterEach(function() {
			gulp.watch.restore();
		});

		it('should run tasks when source files change', function() {
			registerTasks();
			var doneCallback = sinon.stub();

			var task = gulp.start('watch', doneCallback);
			assert.strictEqual(0, doneCallback.callCount);
			assert.strictEqual(3, gulp.watch.callCount);
			assert.deepEqual(['build:js'], gulp.watch.args[0][1]);
			assert.deepEqual(['soy'], gulp.watch.args[1][1]);
			assert.deepEqual(['css'], gulp.watch.args[2][1]);

			task.stop(null, true);
		});

		it('should use task prefix when it\'s defined', function() {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});
			var doneCallback = sinon.stub();

			var task = gulp.start('myPrefix:watch', doneCallback);
			assert.strictEqual(0, doneCallback.callCount);
			assert.strictEqual(3, gulp.watch.callCount);
			assert.deepEqual(['myPrefix:build:js'], gulp.watch.args[0][1]);
			assert.deepEqual(['myPrefix:soy'], gulp.watch.args[1][1]);
			assert.deepEqual(['myPrefix:css'], gulp.watch.args[2][1]);

			task.stop(null, true);
		});
	});

	describe('Format', function() {
		var stubs = {};

		before(function() {
			stubs.esformatter = getStreamFn();
			sinon.spy(stubs, 'esformatter');
			registerTasks.__set__('esformatter', stubs.esformatter);
		});

		beforeEach(function() {
			stubs.esformatter.callCount = 0;
		});

		it('should call esformatter', function(done) {
			registerTasks();

			gulp.start('format', function() {
				assert.strictEqual(1, stubs.esformatter.callCount);
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:format', function() {
				assert.strictEqual(1, stubs.esformatter.callCount);
				done();
			});
		});
	});

	describe('Lint', function() {
		var stubs = {};

		before(function() {
			stubs.jshint = getStreamFn();
			stubs.jshint.reporter = getStreamFn();
			sinon.spy(stubs, 'jshint');
			registerTasks.__set__('jshint', stubs.jshint);
		});

		beforeEach(function() {
			stubs.jshint.callCount = 0;
		});

		it('should call jshint', function(done) {
			registerTasks();

			gulp.start('lint', function() {
				assert.strictEqual(1, stubs.jshint.callCount);
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:lint', function() {
				assert.strictEqual(1, stubs.jshint.callCount);
				done();
			});
		});
	});

	describe('Docs', function() {
		beforeEach(function() {
			sinon.stub(childProcess, 'execFile').yields();
		});

		afterEach(function() {
			childProcess.execFile.restore();
		});

		it('should call jsdoc cli to generate docs', function(done) {
			registerTasks();

			gulp.start('docs', function() {
				assert.strictEqual(1, childProcess.execFile.callCount);
				done();
			});
		});

		it('should use task prefix when it\'s defined', function(done) {
			registerTasks({
				taskPrefix: 'myPrefix:'
			});

			gulp.start('myPrefix:docs', function() {
				assert.strictEqual(1, childProcess.execFile.callCount);
				done();
			});
		});
	});
});

function getStreamFn() {
	return function() {
		return through.obj(function(file, encoding, callback) {
			this.push(file);
			callback();
		});
	};
}
<|endoftext|>


<commit_before>var test = require('tape');
var _ = require('underscore');
var os = require('os');
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var tilelive = require('tilelive');
var yaml = require('js-yaml');

var tm = require('../lib/tm');
var middleware = require('../lib/middleware');
var style = require('../lib/style');
var source = require('../lib/source');
var mockOauth = require('../lib/mapbox-mock')(require('express')());
var tmp = os.tmpdir();
var tmppath = path.join(tmp, 'tm2-middleware-' + (+new Date));

var tmpId = path.join(tmp, 'tm2-middlewareProject-' + (+new Date));
var sourceId = 'tmsource://' + path.resolve(path.join(__dirname, 'fixtures-localsource'));
var styleId = 'tmstyle://' + path.resolve(path.join(__dirname, 'fixtures-localsource'));
var server;

test('setup: config', function(t) {
    tm.config({
        db: path.join(tmppath, 'app.db'),
        cache: path.join(tmppath, 'cache'),
        fonts: path.join(tmppath, 'fonts'),
        mapboxauth: 'http://localhost:3001'
    }, t.end);
});

test('setup: mockserver', function(t) {
    tm.db.set('oauth', {
        account: 'test',
        accesstoken: 'testaccesstoken'
    });
    tm._config.mapboxtile = 'http://localhost:3001/v4';
    server = mockOauth.listen(3001, t.end);
});

test('history: loads', function(t) {
    var req = {};
    middleware.history(req, {}, function() {
        t.ok(req.history, 'has history');
        t.ok(req.history.source, 'history object includes a source');
        t.ok(req.history.source['mapbox:///mapbox.mapbox-streets-v5'], 'default source is listed');
        t.end();
    });
});

test('history: gets style/source info', function(t) {
    tm.history(sourceId);
    tm.history(styleId);

    var req = {};
    middleware.history(req, {}, function() {
        var sourceInfo = req.history.source[sourceId];
        var styleInfo = req.history.style[styleId];
        t.equal('Test source', sourceInfo.name, 'source info was loaded');
        t.equal('Test style', styleInfo.name, 'style info was loaded');
        t.end();
    });
});

test('history: removes dead source/styles', function(t) {
    tm.history('tmstyle:///foo');
    tm.history('tmsource:///bar');
    var req = {};
    middleware.history(req, {}, function() {
        t.ok(!req.history.source.foo, 'source `foo` was removed');
        if (req.history.style) t.ok(!req.history.style.bar, 'style `bar` was removed');
        t.end();
    });
});

test('writeStyle: makes tmp styles', function(t) {
    var req = { body: {} };
    middleware.writeStyle(req, {}, function() {
        t.ok(req.style, 'appends style to req');
        t.ok(style.tmpid(req.style.data.id), 'creates a valid tmp id');
        var history = tm.history();
        if (history.style) {
            t.ok(history.style.indexOf(req.style.data.id) === -1, 'does not write to history');
        }

        style.info('tmstyle://' + path.dirname(require.resolve('mapbox-studio-default-style')), function(err, defaultInfo) {
            delete req.style.data.id;
            delete req.style.data.mtime;
            delete req.style.data._tmp;
            delete req.style.data.background;
            delete defaultInfo.id;
            delete defaultInfo.mtime;

            t.deepEqual(req.style.data, defaultInfo, 'mimics default style');
            t.end();
        });
    });
});

test('writeStyle: makes persistent styles', function(t) {
    var data = {
        id:'tmstyle://' + tmpId,
        name:'tmp-1234',
        source:'mapbox:///mapbox.mapbox-streets-v2',
        styles:{ 'a.mss': '#water { polygon-fill:#fff }' }
    };
    var req = { body: data };
    middleware.writeStyle(req, {}, function() {
        t.ok(req.style, 'appends style to req');
        t.ok(!style.tmpid(req.style.data.id), 'does not create a tmp id');
        t.ok(tm.history().indexOf(req.style.data.id) !== -1, 'writes to history');
        t.equal(req.style.data.name, data.name, 'has correct info');
        t.ok(/maxzoom: 22/.test(fs.readFileSync(tmpId + '/project.yml', 'utf8')), 'saves project.yml');
        t.equal(data.styles['a.mss'], fs.readFileSync(tmpId + '/a.mss', 'utf8'), 'saves a.mss');
        t.end();
    });
});

test('writeStyle: cleanup', function(t) {
    setTimeout(function() {
        ['project.xml','project.yml','a.mss','.thumb.png'].forEach(function(file) {
            try { fs.unlinkSync(path.join(tmpId,file)) } catch(err) {};
        });
        try { fs.rmdirSync(tmpId) } catch(err) {};
        t.end();
    }, 250);
});

test('loadStyle: loads a tmp style', function(t) {
    var writeReq = { body: {} };
    middleware.writeStyle(writeReq, {}, function() {
        var req = { query: { id: writeReq.style.data.id } };
        middleware.loadStyle(req, {}, function() {
            t.ok(req.style, 'appends style to req');
            t.equal(req.style.data.id, writeReq.style.data.id, 'has the correct id');
            var history = tm.history();
            if (history.style) {
                t.ok(history.style.indexOf(req.style.data.id) === -1, 'does not write to history');
            }
            t.end();
        });
    });
});

test('loadStyle: loads a tmp style with source', function(t) {
    var sourceId = 'tmsource://' + path.resolve(path.join(__dirname, 'fixtures-localsource'));
    var req = { body: {}, query: { source:sourceId } };
    middleware.writeStyle(req, {}, function(err) {
        t.ifError(err);
        t.deepEqual({
            'style.mss': 'Map {\n  background-color: #fff;\n}\n\n#solid {\n  line-width: 1;\n  line-color: rgba(153,204,68,0.5);\n}\n\n#box {\n  line-width: 1;\n  line-color: rgba(238,68,187,0.5);\n}\n\n'
        }, req.style.data.styles, 'creates default styles');
        t.equal(sourceId, req.style.data.source, 'sets source from input param');
        t.ok(style.tmpid(req.style.data.id));
        t.end();
    });
});

test('loadStyle: loads a tmp style with a raster source', function(t) {
    var sourceId = 'tmsource://' + path.resolve(path.join(__dirname, 'fixtures-localraster'));
    var req = { body: {}, query: { source:sourceId } };
    middleware.writeStyle(req, {}, function(err) {
        t.ifError(err);
        t.deepEqual({
            'style.mss': 'Map {\n  background-color: #fff;\n}\n\n#raster_local {\n  raster-opacity: 1;\n}\n\n'
        }, req.style.data.styles, 'creates default styles');
        t.equal(sourceId, req.style.data.source, 'sets source from input param');
        t.ok(style.tmpid(req.style.data.id));
        t.end();
    });
});

test('loadStyle: errors a tmp style with bad source', function(t) {
    var sourceId = 'tmsource:///bad/path/to/nonexistent/source';
    var req = { body: {}, query: { source:sourceId } };
    middleware.writeStyle(req, {}, function(err) {
        t.ok(err);
        t.equal('ENOENT', err.code);
        t.end();
    });
});

test('loadStyle: loads a persistent style', function(t) {
    var styleId = 'tmstyle://' + path.resolve(path.join(__dirname, 'fixtures-localsource'));
    var styleDoc = require('./fixtures-localsource/project.yml');
    var req = { query: { id: styleId } };
    middleware.loadStyle(req, {}, function() {
        t.ok(req.style, 'appends style to req');
        t.equal(req.style.data.id, styleId, 'has the correct id');
        t.ok(tm.history().indexOf(req.style.data.id) !== -1, 'writes to history');
        t.equal(req.style.data.mtime, styleDoc.mtime, 'style info was loaded');
        t.end();
    });
});

test('writeSource: makes tmp sources', function(t) {
    var req = { body: {} };
    middleware.writeSource(req, {}, function() {
        t.ok(req.source, 'appends source to req');
        t.ok(source.tmpid(req.source.data.id), 'creates a valid tmp id');
        var history = tm.history();
        if (history.source) {
            t.ok(history.source.indexOf(req.source.data.id) === -1, 'does not write to history');
        }
        t.end();
    });
});

test('writeSource: makes persistent sources', function(t) {
    var data = {
        id: 'tmsource://' + tmpId,
        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'
            }
        } ]
    };
    var req = { body: data };
    middleware.writeSource(req, {}, function() {
        var s = req.source;
        t.ok(s, 'appends source to req');
        t.ok(!source.tmpid(s.data.id), 'does not creates a tmp id');
        var history = tm.history();
        if (history.source) {
            t.ok(history.source.indexOf(s.data.id) !== -1, 'writes to history');
        }
        t.deepEqual(s.data, data, 'has the right data');
        t.end();
    });
});

test('writeSource: cleanup', function(t) {
    setTimeout(function() {
        ['data.xml', 'data.yml'].forEach(function(file) {
            try { fs.unlinkSync(path.join(tmpId,file)) } catch(err) {};
        });
        try { fs.rmdirSync(tmpId) } catch(err) {};
        t.end();
    }, 250);
});

test('loadSource: loads a tmp source', function(t) {
    var writeReq = { body: {} };
    middleware.writeSource(writeReq, {}, function() {
        var req = { query: { id: writeReq.source.data.id } };
        middleware.loadSource(req, {}, function() {
            t.ok(req.source, 'appends source to req');
            t.equal(req.source.data.id, writeReq.source.data.id, 'has the correct id');
            var history = tm.history();
            if (history.source) {
                t.ok(history.source.indexOf(req.source.data.id) === -1, 'does not write to history');
            }
            t.end();
        });
    });
});

test('loadSource: loads a persistent source', function(t) {
    var sourceId = 'tmsource://' + path.resolve(path.join(__dirname, 'fixtures-localsource'));
    var sourceDoc = require('./fixtures-localsource/data.yml');
    var req = { query: { id: sourceId } };
    middleware.loadSource(req, {}, function() {
        t.ok(req.source, 'appends source to req');
        t.equal(req.source.data.id, sourceId, 'has the correct id');
        t.ok(tm.history().indexOf(req.source.data.id) !== -1, 'writes to history');
        t.equal(req.source.data.name, sourceDoc.name, 'has the correct name');
        t.equal(req.source.data.attribution, sourceDoc.attribution, 'has the correct attribution');
        t.equal(req.source.data.minzoom, sourceDoc.minzoom, 'has the correct minzoom');
        t.equal(req.source.data.maxzoom, sourceDoc.maxzoom, 'has the correct maxzoom');
        t.deepEqual(req.source.data.Layer[0].Datasource, sourceDoc.Layer[0].Datasource, 'has the correct Layer');
        t.end();
    });
});

test('auth: errors on unauthenticated requests', function(t) {
    tm.db.rm('oauth');
    middleware.auth({}, {}, function(err) {
        t.equal('EOAUTH', err.code);
        t.end();
    });
});

test('auth: passes through authenticated requests', function(t) {
    tm.db.set('oauth', {
        account: 'test',
        accesstoken: '12345678'
    });
    middleware.auth({}, {}, function(err) {
        t.ok(!err);
        t.end();
    });
});

test('exporting: passes through', function(t) {
    middleware.exporting({}, {}, function(err) {
        t.ifError(err);
        t.end();
    });
});
// @TODO test cases where copytask has been started.
// Requires fixes for copytask pause/cancel.

test('userTilesets: fails without oauth', function(t) {
    tm.db.rm('oauth');
    middleware.userTilesets({}, {}, function(err) {
        t.equal('Error: No active OAuth account', err.toString());
        t.equal(err.code, 'EOAUTH');
        t.end();
    });
});

test('userTilesets: requires 200 from Mapbox API', function(t) {
    tm.db.set('oauth', {
        account: 'baduser',
        accesstoken: 'badtoken'
    });
    middleware.userTilesets({}, {}, function(err) {
        t.equal('Error: 403 GET http://localhost:3001/api/Map?account=baduser&_type=tileset&private=true&access_token=badtoken', err.toString());
        t.end();
    });
});

test('userTilesets: adds history entries for tilesets', function(t) {
    tm.db.set('oauth', {
        account: 'test',
        accesstoken: '12345678'
    });
    middleware.userTilesets({}, {}, function(err) {
        t.ifError(err);
        t.ok(tm.history().indexOf('mapbox:///test.vector-source') !== -1);
        t.ok(tm.history().indexOf('mapbox:///test.raster-source') === -1);
        t.end();
    });
});

test('latest: finds latest local project entry', function(t) {
    var req = {};
    middleware.latest(req, {}, function(err) {
        t.ifError(err);
        t.equal(req.latest, sourceId, 'finds latest source');
        t.end();
    });
});

test('cleanup', function(t) {
    tm.db.rm('oauth');
    tm.history(sourceId, true);
    tm.history(styleId, true);
    try { fs.unlinkSync(path.join(tmppath, 'app.db')); } catch(err) {}
    try { fs.rmdirSync(path.join(tmppath, 'cache')); } catch(err) {}
    try { fs.rmdirSync(tmppath); } catch(err) {}
    server.close(function() {
        t.end();
    });
});
<commit_msg>Windows fixes.<commit_after>var test = require('tape');
var _ = require('underscore');
var os = require('os');
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var tilelive = require('tilelive');
var yaml = require('js-yaml');

var tm = require('../lib/tm');
var middleware = require('../lib/middleware');
var style = require('../lib/style');
var source = require('../lib/source');
var mockOauth = require('../lib/mapbox-mock')(require('express')());
var tmp = os.tmpdir();
var tmppath = tm.join(tmp, 'tm2-middleware-' + (+new Date));

var tmpId = tm.join(tmp, 'tm2-middlewareProject-' + (+new Date));
var sourceId = 'tmsource://' + path.resolve(tm.join(__dirname, 'fixtures-localsource'));
var styleId = 'tmstyle://' + path.resolve(tm.join(__dirname, 'fixtures-localsource'));
var server;

test('setup: config', function(t) {
    tm.config({
        db: path.join(tmppath, 'app.db'),
        cache: path.join(tmppath, 'cache'),
        fonts: path.join(tmppath, 'fonts'),
        mapboxauth: 'http://localhost:3001'
    }, t.end);
});

test('setup: mockserver', function(t) {
    tm.db.set('oauth', {
        account: 'test',
        accesstoken: 'testaccesstoken'
    });
    tm._config.mapboxtile = 'http://localhost:3001/v4';
    server = mockOauth.listen(3001, t.end);
});

test('history: loads', function(t) {
    var req = {};
    middleware.history(req, {}, function() {
        t.ok(req.history, 'has history');
        t.ok(req.history.source, 'history object includes a source');
        t.ok(req.history.source['mapbox:///mapbox.mapbox-streets-v5'], 'default source is listed');
        t.end();
    });
});

test('history: gets style/source info', function(t) {
    tm.history(sourceId);
    tm.history(styleId);

    var req = {};
    middleware.history(req, {}, function() {
        var sourceInfo = req.history.source[sourceId];
        var styleInfo = req.history.style[styleId];
        t.equal('Test source', sourceInfo.name, 'source info was loaded');
        t.equal('Test style', styleInfo.name, 'style info was loaded');
        t.end();
    });
});

test('history: removes dead source/styles', function(t) {
    tm.history('tmstyle:///foo');
    tm.history('tmsource:///bar');
    var req = {};
    middleware.history(req, {}, function() {
        t.ok(!req.history.source.foo, 'source `foo` was removed');
        if (req.history.style) t.ok(!req.history.style.bar, 'style `bar` was removed');
        t.end();
    });
});

test('writeStyle: makes tmp styles', function(t) {
    var req = { body: {} };
    middleware.writeStyle(req, {}, function() {
        t.ok(req.style, 'appends style to req');
        t.ok(style.tmpid(req.style.data.id), 'creates a valid tmp id');
        var history = tm.history();
        if (history.style) {
            t.ok(history.style.indexOf(req.style.data.id) === -1, 'does not write to history');
        }

        style.info('tmstyle://' + path.dirname(require.resolve('mapbox-studio-default-style')), function(err, defaultInfo) {
            delete req.style.data.id;
            delete req.style.data.mtime;
            delete req.style.data._tmp;
            delete req.style.data.background;
            delete defaultInfo.id;
            delete defaultInfo.mtime;

            t.deepEqual(req.style.data, defaultInfo, 'mimics default style');
            t.end();
        });
    });
});

test('writeStyle: makes persistent styles', function(t) {
    var data = {
        id:'tmstyle://' + tmpId,
        name:'tmp-1234',
        source:'mapbox:///mapbox.mapbox-streets-v2',
        styles:{ 'a.mss': '#water { polygon-fill:#fff }' }
    };
    var req = { body: data };
    middleware.writeStyle(req, {}, function() {
        t.ok(req.style, 'appends style to req');
        t.ok(!style.tmpid(req.style.data.id), 'does not create a tmp id');
        t.ok(tm.history().indexOf(req.style.data.id) !== -1, 'writes to history');
        t.equal(req.style.data.name, data.name, 'has correct info');
        t.ok(/maxzoom: 22/.test(fs.readFileSync(tmpId + '/project.yml', 'utf8')), 'saves project.yml');
        t.equal(data.styles['a.mss'], fs.readFileSync(tmpId + '/a.mss', 'utf8'), 'saves a.mss');
        t.end();
    });
});

test('writeStyle: cleanup', function(t) {
    setTimeout(function() {
        ['project.xml','project.yml','a.mss','.thumb.png'].forEach(function(file) {
            try { fs.unlinkSync(path.join(tmpId,file)) } catch(err) {};
        });
        try { fs.rmdirSync(tmpId) } catch(err) {};
        t.end();
    }, 250);
});

test('loadStyle: loads a tmp style', function(t) {
    var writeReq = { body: {} };
    middleware.writeStyle(writeReq, {}, function() {
        var req = { query: { id: writeReq.style.data.id } };
        middleware.loadStyle(req, {}, function() {
            t.ok(req.style, 'appends style to req');
            t.equal(req.style.data.id, writeReq.style.data.id, 'has the correct id');
            var history = tm.history();
            if (history.style) {
                t.ok(history.style.indexOf(req.style.data.id) === -1, 'does not write to history');
            }
            t.end();
        });
    });
});

test('loadStyle: loads a tmp style with source', function(t) {
    var sourceId = 'tmsource://' + path.resolve(path.join(__dirname, 'fixtures-localsource'));
    var req = { body: {}, query: { source:sourceId } };
    middleware.writeStyle(req, {}, function(err) {
        t.ifError(err);
        t.deepEqual({
            'style.mss': 'Map {\n  background-color: #fff;\n}\n\n#solid {\n  line-width: 1;\n  line-color: rgba(153,204,68,0.5);\n}\n\n#box {\n  line-width: 1;\n  line-color: rgba(238,68,187,0.5);\n}\n\n'
        }, req.style.data.styles, 'creates default styles');
        t.equal(sourceId, req.style.data.source, 'sets source from input param');
        t.ok(style.tmpid(req.style.data.id));
        t.end();
    });
});

test('loadStyle: loads a tmp style with a raster source', function(t) {
    var sourceId = 'tmsource://' + path.resolve(path.join(__dirname, 'fixtures-localraster'));
    var req = { body: {}, query: { source:sourceId } };
    middleware.writeStyle(req, {}, function(err) {
        t.ifError(err);
        t.deepEqual({
            'style.mss': 'Map {\n  background-color: #fff;\n}\n\n#raster_local {\n  raster-opacity: 1;\n}\n\n'
        }, req.style.data.styles, 'creates default styles');
        t.equal(sourceId, req.style.data.source, 'sets source from input param');
        t.ok(style.tmpid(req.style.data.id));
        t.end();
    });
});

test('loadStyle: errors a tmp style with bad source', function(t) {
    var sourceId = 'tmsource:///bad/path/to/nonexistent/source';
    var req = { body: {}, query: { source:sourceId } };
    middleware.writeStyle(req, {}, function(err) {
        t.ok(err);
        t.equal('ENOENT', err.code);
        t.end();
    });
});

test('loadStyle: loads a persistent style', function(t) {
    var styleId = 'tmstyle://' + path.resolve(path.join(__dirname, 'fixtures-localsource'));
    var styleDoc = require('./fixtures-localsource/project.yml');
    var req = { query: { id: styleId } };
    middleware.loadStyle(req, {}, function() {
        t.ok(req.style, 'appends style to req');
        t.equal(req.style.data.id, styleId, 'has the correct id');
        t.ok(tm.history().indexOf(req.style.data.id) !== -1, 'writes to history');
        t.equal(req.style.data.mtime, styleDoc.mtime, 'style info was loaded');
        t.end();
    });
});

test('writeSource: makes tmp sources', function(t) {
    var req = { body: {} };
    middleware.writeSource(req, {}, function() {
        t.ok(req.source, 'appends source to req');
        t.ok(source.tmpid(req.source.data.id), 'creates a valid tmp id');
        var history = tm.history();
        if (history.source) {
            t.ok(history.source.indexOf(req.source.data.id) === -1, 'does not write to history');
        }
        t.end();
    });
});

test('writeSource: makes persistent sources', function(t) {
    var data = {
        id: 'tmsource://' + tmpId,
        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'
            }
        } ]
    };
    var req = { body: data };
    middleware.writeSource(req, {}, function() {
        var s = req.source;
        t.ok(s, 'appends source to req');
        t.ok(!source.tmpid(s.data.id), 'does not creates a tmp id');
        var history = tm.history();
        if (history.source) {
            t.ok(history.source.indexOf(s.data.id) !== -1, 'writes to history');
        }
        t.deepEqual(s.data, data, 'has the right data');
        t.end();
    });
});

test('writeSource: cleanup', function(t) {
    setTimeout(function() {
        ['data.xml', 'data.yml'].forEach(function(file) {
            try { fs.unlinkSync(path.join(tmpId,file)) } catch(err) {};
        });
        try { fs.rmdirSync(tmpId) } catch(err) {};
        t.end();
    }, 250);
});

test('loadSource: loads a tmp source', function(t) {
    var writeReq = { body: {} };
    middleware.writeSource(writeReq, {}, function() {
        var req = { query: { id: writeReq.source.data.id } };
        middleware.loadSource(req, {}, function() {
            t.ok(req.source, 'appends source to req');
            t.equal(req.source.data.id, writeReq.source.data.id, 'has the correct id');
            var history = tm.history();
            if (history.source) {
                t.ok(history.source.indexOf(req.source.data.id) === -1, 'does not write to history');
            }
            t.end();
        });
    });
});

test('loadSource: loads a persistent source', function(t) {
    var sourceId = 'tmsource://' + path.resolve(path.join(__dirname, 'fixtures-localsource'));
    var sourceDoc = require('./fixtures-localsource/data.yml');
    var req = { query: { id: sourceId } };
    middleware.loadSource(req, {}, function() {
        t.ok(req.source, 'appends source to req');
        t.equal(req.source.data.id, sourceId, 'has the correct id');
        t.ok(tm.history().indexOf(req.source.data.id) !== -1, 'writes to history');
        t.equal(req.source.data.name, sourceDoc.name, 'has the correct name');
        t.equal(req.source.data.attribution, sourceDoc.attribution, 'has the correct attribution');
        t.equal(req.source.data.minzoom, sourceDoc.minzoom, 'has the correct minzoom');
        t.equal(req.source.data.maxzoom, sourceDoc.maxzoom, 'has the correct maxzoom');
        t.deepEqual(req.source.data.Layer[0].Datasource, sourceDoc.Layer[0].Datasource, 'has the correct Layer');
        t.end();
    });
});

test('auth: errors on unauthenticated requests', function(t) {
    tm.db.rm('oauth');
    middleware.auth({}, {}, function(err) {
        t.equal('EOAUTH', err.code);
        t.end();
    });
});

test('auth: passes through authenticated requests', function(t) {
    tm.db.set('oauth', {
        account: 'test',
        accesstoken: '12345678'
    });
    middleware.auth({}, {}, function(err) {
        t.ok(!err);
        t.end();
    });
});

test('exporting: passes through', function(t) {
    middleware.exporting({}, {}, function(err) {
        t.ifError(err);
        t.end();
    });
});
// @TODO test cases where copytask has been started.
// Requires fixes for copytask pause/cancel.

test('userTilesets: fails without oauth', function(t) {
    tm.db.rm('oauth');
    middleware.userTilesets({}, {}, function(err) {
        t.equal('Error: No active OAuth account', err.toString());
        t.equal(err.code, 'EOAUTH');
        t.end();
    });
});

test('userTilesets: requires 200 from Mapbox API', function(t) {
    tm.db.set('oauth', {
        account: 'baduser',
        accesstoken: 'badtoken'
    });
    middleware.userTilesets({}, {}, function(err) {
        t.equal('Error: 403 GET http://localhost:3001/api/Map?account=baduser&_type=tileset&private=true&access_token=badtoken', err.toString());
        t.end();
    });
});

test('userTilesets: adds history entries for tilesets', function(t) {
    tm.db.set('oauth', {
        account: 'test',
        accesstoken: '12345678'
    });
    middleware.userTilesets({}, {}, function(err) {
        t.ifError(err);
        t.ok(tm.history().indexOf('mapbox:///test.vector-source') !== -1);
        t.ok(tm.history().indexOf('mapbox:///test.raster-source') === -1);
        t.end();
    });
});

test('latest: finds latest local project entry', function(t) {
    var req = {};
    middleware.latest(req, {}, function(err) {
        t.ifError(err);
        t.equal(req.latest, sourceId, 'finds latest source');
        t.end();
    });
});

test('cleanup', function(t) {
    tm.db.rm('oauth');
    tm.history(sourceId, true);
    tm.history(styleId, true);
    try { fs.unlinkSync(path.join(tmppath, 'app.db')); } catch(err) {}
    try { fs.rmdirSync(path.join(tmppath, 'cache')); } catch(err) {}
    try { fs.rmdirSync(tmppath); } catch(err) {}
    server.close(function() {
        t.end();
    });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

var chai = require('chai');
var stripAnsi = require('strip-ansi');
var expect = chai.expect;
var mockPackageJson = JSON.parse(fs.readFileSync(path.join(__dirname, './mocks/mockPackageConfig.json'), 'utf8'));
var moduleUtils = require('../index.js');
var moduleUtilsInstance = moduleUtils(mockPackageJson);

var mockConsoleLog = require('./mocks/mockConsoleLog');
var mockProcessExit = require('./mocks/mockProcessExit');

chai.use(require('chai-fs'));
chai.should();

describe('As user of the module utils module', function() {

	it('should export a function', function() {
		expect(moduleUtils).to.be.an('function');
	})

	describe('When creating an instance', function() {

		it('should return an object', function() {
			expect(moduleUtilsInstance).to.be.an('object');
		})
	})

	describe('When using the logMessage function', function() {

		before(function() {
			mockConsoleLog.enable();
		})

		after(function() {
			mockConsoleLog.clearLogData();
		})

		it('should correctly log the input', function() {
			var logInput = "Who are the patriots?"
			var expected = fs.readFileSync(path.join(__dirname, 'structs', 'logMessage.txt'), 'utf8');
			var actual;

			moduleUtilsInstance.logMessage(logInput);
			mockConsoleLog.restore();

			actual = mockConsoleLog.getLogData();

			expect(expected).to.equal(actual);
		});

	})

	describe('When using the finishInstall function', function() {

		describe('And testing the on-screen output', function() {

			before(function() {
				mockConsoleLog.enable();
				mockProcessExit.enable();
			})

			after(function() {
				mockConsoleLog.clearLogData();
			})

			it('should correctly log the input', function() {
				var expected = fs.readFileSync(path.join(__dirname, 'structs', 'finishInstall.txt'), 'utf8');
				var actual;

				moduleUtilsInstance.finishInstall();
				mockConsoleLog.restore();
				mockProcessExit.restore();
				actual = mockConsoleLog.getLogData();

				expect(expected).to.equal(actual);
			})
		})

		describe('And testing if the process it exited', function() {

			before(function() {
				mockProcessExit.enable();
				mockConsoleLog.enable();
			})

			after(function() {
				mockProcessExit.restore();
				mockConsoleLog.clearLogData();
			})

			it('should exit the process with error code 0 (no error)', function() {
				var exitCallInfo;

				moduleUtilsInstance.finishInstall();
				mockConsoleLog.restore();

				exitCallInfo = mockProcessExit.callInfo();

				expect(exitCallInfo.called).to.be.true;
				expect(exitCallInfo.errorCode).to.equal(0);
			})

		})

	})

	describe('When using the exitIfDevEnvironment', function() {

		describe('And NODE_ENV equals `development`', function() {

			beforeEach(function() {
				mockProcessExit.enable();
				mockConsoleLog.enable();

				process.env.NODE_ENV = 'development';
			})

			afterEach(function() {
				mockProcessExit.restore();
				mockConsoleLog.clearLogData();
			})

			it('should output on-screen message saying this step is going to be skipped', function() {
				var expected = fs.readFileSync(path.join(__dirname, 'structs', 'exitIfDev.txt'), 'utf8');
				var actual;

				moduleUtilsInstance.exitIfDevEnvironment();
				mockConsoleLog.restore();

				actual = stripAnsi(mockConsoleLog.getLogData());

				expect(expected).to.equal(actual);
			})

			it('should exit the process with error code 0 (no error)', function() {
				var exitCallInfo;

				moduleUtilsInstance.exitIfDevEnvironment();
				mockConsoleLog.restore();

				exitCallInfo = mockProcessExit.callInfo();

				expect(exitCallInfo.called).to.be.true;
				expect(exitCallInfo.errorCode).to.equal(0);
			})

		})

		describe('And NODE_ENV does not equal `development`', function() {
			beforeEach(function() {
				mockProcessExit.enable();

				process.env.NODE_ENV = 'played-me-like-a-damn-fiddle';
			})

			afterEach(function() {
				mockProcessExit.restore();
			})

			it.skip('should not output an on-screen message', function() {
				//@TODO
			});

			it('should not exit the process', function() {
				var exitCallInfo;

				moduleUtilsInstance.exitIfDevEnvironment();
				exitCallInfo = mockProcessExit.callInfo();

				expect(exitCallInfo.called).to.be.false;
			})
		})

	})
})<commit_msg>test: Check nothing is output for exitIfDevEnvironment if not in dev NODE_ENV<commit_after>var fs = require('fs');
var path = require('path');

var chai = require('chai');
var stripAnsi = require('strip-ansi');
var expect = chai.expect;
var mockPackageJson = JSON.parse(fs.readFileSync(path.join(__dirname, './mocks/mockPackageConfig.json'), 'utf8'));
var moduleUtils = require('../index.js');
var moduleUtilsInstance = moduleUtils(mockPackageJson);

var mockConsoleLog = require('./mocks/mockConsoleLog');
var mockProcessExit = require('./mocks/mockProcessExit');

chai.use(require('chai-fs'));
chai.should();

describe('As user of the module utils module', function() {

	it('should export a function', function() {
		expect(moduleUtils).to.be.an('function');
	})

	describe('When creating an instance', function() {

		it('should return an object', function() {
			expect(moduleUtilsInstance).to.be.an('object');
		})
	})

	describe('When using the logMessage function', function() {

		before(function() {
			mockConsoleLog.enable();
		})

		after(function() {
			mockConsoleLog.clearLogData();
		})

		it('should correctly log the input', function() {
			var logInput = "Who are the patriots?"
			var expected = fs.readFileSync(path.join(__dirname, 'structs', 'logMessage.txt'), 'utf8');
			var actual;

			moduleUtilsInstance.logMessage(logInput);
			mockConsoleLog.restore();

			actual = mockConsoleLog.getLogData();

			expect(expected).to.equal(actual);
		});

	})

	describe('When using the finishInstall function', function() {

		describe('And testing the on-screen output', function() {

			before(function() {
				mockConsoleLog.enable();
				mockProcessExit.enable();
			})

			after(function() {
				mockConsoleLog.clearLogData();
			})

			it('should correctly log the input', function() {
				var expected = fs.readFileSync(path.join(__dirname, 'structs', 'finishInstall.txt'), 'utf8');
				var actual;

				moduleUtilsInstance.finishInstall();
				mockConsoleLog.restore();
				mockProcessExit.restore();
				actual = mockConsoleLog.getLogData();

				expect(expected).to.equal(actual);
			})
		})

		describe('And testing if the process it exited', function() {

			before(function() {
				mockProcessExit.enable();
				mockConsoleLog.enable();
			})

			after(function() {
				mockProcessExit.restore();
				mockConsoleLog.clearLogData();
			})

			it('should exit the process with error code 0 (no error)', function() {
				var exitCallInfo;

				moduleUtilsInstance.finishInstall();
				mockConsoleLog.restore();

				exitCallInfo = mockProcessExit.callInfo();

				expect(exitCallInfo.called).to.be.true;
				expect(exitCallInfo.errorCode).to.equal(0);
			})

		})

	})

	describe('When using the exitIfDevEnvironment', function() {

		describe('And NODE_ENV equals `development`', function() {

			beforeEach(function() {
				mockProcessExit.enable();
				mockConsoleLog.enable();

				process.env.NODE_ENV = 'development';
			})

			afterEach(function() {
				mockProcessExit.restore();
				mockConsoleLog.clearLogData();
			})

			it('should output on-screen message saying this step is going to be skipped', function() {
				var expected = fs.readFileSync(path.join(__dirname, 'structs', 'exitIfDev.txt'), 'utf8');
				var actual;

				moduleUtilsInstance.exitIfDevEnvironment();
				mockConsoleLog.restore();

				actual = stripAnsi(mockConsoleLog.getLogData());

				expect(expected).to.equal(actual);
			})

			it('should exit the process with error code 0 (no error)', function() {
				var exitCallInfo;

				moduleUtilsInstance.exitIfDevEnvironment();
				mockConsoleLog.restore();

				exitCallInfo = mockProcessExit.callInfo();

				expect(exitCallInfo.called).to.be.true;
				expect(exitCallInfo.errorCode).to.equal(0);
			})

		})

		describe('And NODE_ENV does not equal `development`', function() {
			beforeEach(function() {
				mockProcessExit.enable();

				process.env.NODE_ENV = 'played-me-like-a-damn-fiddle';
			})

			afterEach(function() {
				mockProcessExit.restore();
			})

			it('should not output an on-screen message', function() {
				var expected = "";
				var actual;

				moduleUtilsInstance.exitIfDevEnvironment();
				mockConsoleLog.restore();

				actual = mockConsoleLog.getLogData();

				expect(expected).to.equal(actual);
			});

			it('should not exit the process', function() {
				var exitCallInfo;

				moduleUtilsInstance.exitIfDevEnvironment();
				exitCallInfo = mockProcessExit.callInfo();

				expect(exitCallInfo.called).to.be.false;
			})
		})

	})
})<|endoftext|>


<commit_before>'use strict';

// MODULES //

var debug = require( 'debug' )( 'licenses:infer:license' );
var getKeys = require( 'object-keys' ).shim();
var prefix = require( './stdlib.js' );
var replace = require( prefix+'@stdlib/string/replace' );
var removePunctuation = require( prefix+'@stdlib/string/remove-punctuation' );
var RE_WHITESPACE = require( './re_whitespace.js' );
var RE_LIST_MARKS = require( './re_list_marks.js' );
var LICENSES = require( './db.js' );

// VARIABLES //

var KEYS = getKeys( LICENSES );

// INFER //

/**
* Attempts to infer one or more licenses from file content.
*
* @private
* @param {string} file - file content
* @returns {(StringArray|EmptyArray)} inferred license(s)
*/
function infer( file ) {
	var license;
	var out;
	var i;

	debug( 'Normalizing file content...' );
	file = removePunctuation( file );
	file = replace( file, RE_LIST_MARKS, '' );
	file = replace( file, RE_WHITESPACE, '|' );

	debug( 'Inferring licenses...' );
	out = [];
	for ( i = 0; i < KEYS.length; i++ ) {
		license = LICENSES[ KEYS[i] ];
		if ( file.indexOf( license.text ) > -1 ) {
			debug( 'Found matching license text. Inferred license: %s.', license.spdx );
			out.push( license.spdx );
		} else if ( file.indexOf( '|'+license.spdx+'|' ) > -1 ) {
			debug( 'Found matching license SPDX identifier. Inferred license: %s.', license.spdx );
			out.push( license.spdx );
		}
	}
	debug( 'Inferred %d licenses.', out.length );
	return out;
} // end FUNCTION infer()

// EXPORTS //

module.exports = infer;
<commit_msg>Add TODO item<commit_after>'use strict';

// MODULES //

var debug = require( 'debug' )( 'licenses:infer:license' );
var getKeys = require( 'object-keys' ).shim();
var prefix = require( './stdlib.js' );
var replace = require( prefix+'@stdlib/string/replace' );
var removePunctuation = require( prefix+'@stdlib/string/remove-punctuation' );
var RE_WHITESPACE = require( './re_whitespace.js' );
var RE_LIST_MARKS = require( './re_list_marks.js' );
var LICENSES = require( './db.js' );

// VARIABLES //

var KEYS = getKeys( LICENSES );

// INFER //

/**
* Attempts to infer one or more licenses from file content.
*
* @private
* @param {string} file - file content
* @returns {(StringArray|EmptyArray)} inferred license(s)
*/
function infer( file ) {
	var license;
	var out;
	var i;

	debug( 'Normalizing file content...' );
	file = removePunctuation( file );
	file = replace( file, RE_LIST_MARKS, '' );
	file = replace( file, RE_WHITESPACE, '|' );

	// TODO: maybe use distance measure, like lev dist, and threshold (?); could be tricky as some licenses are quite similar and may have to weight based on license length.
	debug( 'Inferring licenses...' );
	out = [];
	for ( i = 0; i < KEYS.length; i++ ) {
		license = LICENSES[ KEYS[i] ];
		if ( file.indexOf( license.text ) > -1 ) {
			debug( 'Found matching license text. Inferred license: %s.', license.spdx );
			out.push( license.spdx );
		} else if ( file.indexOf( '|'+license.spdx+'|' ) > -1 ) {
			debug( 'Found matching license SPDX identifier. Inferred license: %s.', license.spdx );
			out.push( license.spdx );
		}
	}
	debug( 'Inferred %d licenses.', out.length );
	return out;
} // end FUNCTION infer()

// EXPORTS //

module.exports = infer;
<|endoftext|>


<commit_before>define([
    'jquery',
    'underscore',
    'knockout',
    'summernote'
], function ($, _, ko) {
    /**
    * A knockout.js binding for the "summernote" rich text editor widget
    * - pass options to summernote using the following syntax in the knockout
    * data-bind attribute
    * @example
    * summernote: {height: 250}
    * @constructor
    * @name summernote
    */
    ko.bindingHandlers.summernote = {
        init: function(element, valueAccessor, allBindings, viewModel, bindingContext){
            var $element = $(element);
            var options = ko.unwrap(valueAccessor());
            $('.note-codable').on( "keyup", function(text){
                text.currentTarget.value = text.currentTarget.value.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
                console.log(text.currentTarget.value)
            })
            $('.note-codable').on( "paste", function(text){
                text.currentTarget.value = text.currentTarget.value.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
                console.log(text.currentTarget.value)
            })
            options = (typeof options === 'object') ? options : {};
            options = _.defaults(options, {
                height: 150,
                value: ko.observable('')
            });

            options.callbacks = options.callbacks ? options.callbacks : {};
            var userChange = options.callbacks.onChange ? options.callbacks.onChange : null;
            options.callbacks.onChange = function(value) {
                if (ko.isObservable(options.value)) {
                    options.value(value);
                } else {
                    options.value = value;
                }
                if (userChange && typeof userChange === 'function') {
                    userChange.apply($element, arguments);
                }
            };

            $element.summernote(options);

            if (ko.isObservable(options.value)) {
                options.value.subscribe(function(value) {
                    var currentContent = $element.summernote('code');
                    if (value !== currentContent) {
                        $element.summernote('code', value);
                    }
                });
                $element.summernote('code', options.value());
            } else {
                $element.summernote('code', options.value);
            }
        }
    };

    return ko.bindingHandlers.summernote;
});
<commit_msg>Added regex in summernote binding handler to clear script tags from the code editor, re #1837<commit_after>define([
    'jquery',
    'underscore',
    'knockout',
    'summernote'
], function ($, _, ko) {
    /**
    * A knockout.js binding for the "summernote" rich text editor widget
    * - pass options to summernote using the following syntax in the knockout
    * data-bind attribute
    * @example
    * summernote: {height: 250}
    * @constructor
    * @name summernote
    */
    ko.bindingHandlers.summernote = {
        init: function(element, valueAccessor, allBindings, viewModel, bindingContext){
            console.log('initing')
            var $element = $(element);
            var options = ko.unwrap(valueAccessor());
            options = (typeof options === 'object') ? options : {};
            options = _.defaults(options, {
                height: 150,
                value: ko.observable('')
            });

            options.callbacks = options.callbacks ? options.callbacks : {};
            var userChange = options.callbacks.onChange ? options.callbacks.onChange : null;
            options.callbacks.onChange = function(value) {
                if (ko.isObservable(options.value)) {
                    options.value(value);
                } else {
                    options.value = value;
                }
                if (userChange && typeof userChange === 'function') {
                    userChange.apply($element, arguments);
                }
            };

            $element.summernote(options);

            function clearScriptTags(){
                var noteCodable = $('textarea.note-codable')
                noteCodable.val(noteCodable.val().replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ''))
                console.log('Script tags are not permitted in the code editor')
            }

            $('.btn-codeview').on( "mousedown", clearScriptTags)
            $('textarea.note-codable').on( "keypress", clearScriptTags)

            if (ko.isObservable(options.value)) {
                options.value.subscribe(function(value) {
                    var currentContent = $element.summernote('code');
                    if (value !== currentContent) {
                        $element.summernote('code', value);
                    }
                });
                $element.summernote('code', options.value());
            } else {
                $element.summernote('code', options.value);
            }
        }
    };

    return ko.bindingHandlers.summernote;
});
<|endoftext|>


<commit_before>var mouse = require('mouse').create(casper);
var u = require('utils');
var c = require('colorizer').create('Colorizer');

var NB_TESTS = 10;
var nippleIndex = 0;
var collectionIndex = 0;
var showClientLog = false;

/*
    CONFIGURE CASPER
*/

casper.options.viewportSize = {width: 1100, height: 900};
casper.options.clientScripts.unshift('./test/shimBind.js');
casper.options.logLevel = 'debug';

/*
    LISTEN TO CASPER
*/

casper.on('remote.message', function(message) {
    if (!showClientLog) {
        return;
    }
    if (typeof message === 'string') {
        casper.echo('>> [CLIENT] ' + message, 'WARN_BAR');
    } else {
        casper.echo('>> [CLIENT] DUMP', 'WARN_BAR');
        u.dump(message);
    }
});

casper.on('resource.error', function(message) {
    if (!showClientLog) {
        return;
    }
    if (typeof message === 'string') {
        casper.echo('>> [CLIENT] ' + message, 'RED_BAR');
    } else {
        casper.echo('>> [CLIENT] DUMP', 'RED_BAR');
        u.dump(message);
    }
});

casper.on('page.error', function(message, trace) {
    if (!showClientLog) {
        return;
    }
    if (typeof message === 'string') {
        casper.echo('>> [CLIENT] ' + message, 'RED_BAR');
    } else {
        casper.echo('>> [CLIENT] DUMP', 'RED_BAR');
        u.dump(message);
    }
    u.dump(trace);
});

/*
    ACTIONS
*/

function clickZone () {
    mouse.down('.zone.active');
}

function assertNipple (test) {
    return function () {
        test.assertExists('#nipple_' + collectionIndex +
            '_' + nippleIndex,
            'Nipple ' + nippleIndex + ' from collection ' +
            collectionIndex + ' is found');
        nippleIndex += 1;
    };
}

function assertNotNipple (test) {
    return function () {
        test.assertDoesntExist('#nipple_' + collectionIndex +
            '_' + nippleIndex,
            'Nipple ' + nippleIndex + ' from collection ' +
            collectionIndex + ' is NOT found');
        nippleIndex += 1;
    };
}

casper.test.begin('NippleJS test page loads correctly', NB_TESTS,
    function suite(test) {
        var box;
        casper
            .start('http://127.0.0.1:8080')
            .then(function () {
                // Assert that active zone is here.
                test.assertExists('#zone_joystick', 'Active zone is found');
                test.assertExists('.zone.dynamic', 'Dynamic zone is default');
            })
            .then(function () {
                // Get position of active zone.
                box = casper.evaluate(function () {
                    return document.getElementById('zone_joystick')
                        .getBoundingClientRect();
                });
            })
            /**********************************\
            *
            *				DYNAMIC
            *
            \**********************************/
            // Assert we can create more than one nipple on dynamic
            .then(clickZone)
            .then(assertNipple(test))
            .then(clickZone)
            .then(assertNipple(test))
            /**********************************\
            *
            *				SEMI
            *
            \**********************************/
            .then(function () {
                mouse.click('.button.semi');
                collectionIndex += 1;
            })
            .then(function () {
                test.assertVisible('.zone.semi', 'Semi zone should be visible');
            })
            // Assert we can't create more than one nipple on semi
            .then(clickZone)
            .then(assertNipple(test))
            .then(clickZone)
            .then(assertNotNipple(test))
            .then(function () {
                // Revert increment because last nipple doesn't exist
                nippleIndex -= 1;
            })
            /**********************************\
            *
            *				STATIC
            *
            \**********************************/
            .then(function () {
                mouse.click('.button.static');
                collectionIndex += 1;
            })
            .then(function () {
                test.assertVisible('.zone.static',
                    'Static zone should be visible');
            })
            // Assert we can't create more than one nipple on semi
            .then(clickZone)
            .then(assertNipple(test))
            .then(clickZone)
            .then(assertNotNipple(test))
            .then(function () {
                // Revert increment because last nipple doesn't exist
                nippleIndex -= 1;
            })
            .run(function () {
                // End tests
                test.done();
            });
    }
);
<commit_msg>tests: remove useless shim injection<commit_after>var mouse = require('mouse').create(casper);
var u = require('utils');
var c = require('colorizer').create('Colorizer');

var NB_TESTS = 10;
var nippleIndex = 0;
var collectionIndex = 0;
var showClientLog = false;

/*
    CONFIGURE CASPER
*/

casper.options.viewportSize = {width: 1100, height: 900};
casper.options.logLevel = 'debug';

/*
    LISTEN TO CASPER
*/

casper.on('remote.message', function(message) {
    if (!showClientLog) {
        return;
    }
    if (typeof message === 'string') {
        casper.echo('>> [CLIENT] ' + message, 'WARN_BAR');
    } else {
        casper.echo('>> [CLIENT] DUMP', 'WARN_BAR');
        u.dump(message);
    }
});

casper.on('resource.error', function(message) {
    if (!showClientLog) {
        return;
    }
    if (typeof message === 'string') {
        casper.echo('>> [CLIENT] ' + message, 'RED_BAR');
    } else {
        casper.echo('>> [CLIENT] DUMP', 'RED_BAR');
        u.dump(message);
    }
});

casper.on('page.error', function(message, trace) {
    if (!showClientLog) {
        return;
    }
    if (typeof message === 'string') {
        casper.echo('>> [CLIENT] ' + message, 'RED_BAR');
    } else {
        casper.echo('>> [CLIENT] DUMP', 'RED_BAR');
        u.dump(message);
    }
    u.dump(trace);
});

/*
    ACTIONS
*/

function clickZone () {
    mouse.down('.zone.active');
}

function assertNipple (test) {
    return function () {
        test.assertExists('#nipple_' + collectionIndex +
            '_' + nippleIndex,
            'Nipple ' + nippleIndex + ' from collection ' +
            collectionIndex + ' is found');
        nippleIndex += 1;
    };
}

function assertNotNipple (test) {
    return function () {
        test.assertDoesntExist('#nipple_' + collectionIndex +
            '_' + nippleIndex,
            'Nipple ' + nippleIndex + ' from collection ' +
            collectionIndex + ' is NOT found');
        nippleIndex += 1;
    };
}

casper.test.begin('NippleJS test page loads correctly', NB_TESTS,
    function suite(test) {
        var box;
        casper
            .start('http://127.0.0.1:8080')
            .then(function () {
                // Assert that active zone is here.
                test.assertExists('#zone_joystick', 'Active zone is found');
                test.assertExists('.zone.dynamic', 'Dynamic zone is default');
            })
            .then(function () {
                // Get position of active zone.
                box = casper.evaluate(function () {
                    return document.getElementById('zone_joystick')
                        .getBoundingClientRect();
                });
            })
            /**********************************\
            *
            *				DYNAMIC
            *
            \**********************************/
            // Assert we can create more than one nipple on dynamic
            .then(clickZone)
            .then(assertNipple(test))
            .then(clickZone)
            .then(assertNipple(test))
            /**********************************\
            *
            *				SEMI
            *
            \**********************************/
            .then(function () {
                mouse.click('.button.semi');
                collectionIndex += 1;
            })
            .then(function () {
                test.assertVisible('.zone.semi', 'Semi zone should be visible');
            })
            // Assert we can't create more than one nipple on semi
            .then(clickZone)
            .then(assertNipple(test))
            .then(clickZone)
            .then(assertNotNipple(test))
            .then(function () {
                // Revert increment because last nipple doesn't exist
                nippleIndex -= 1;
            })
            /**********************************\
            *
            *				STATIC
            *
            \**********************************/
            .then(function () {
                mouse.click('.button.static');
                collectionIndex += 1;
            })
            .then(function () {
                test.assertVisible('.zone.static',
                    'Static zone should be visible');
            })
            // Assert we can't create more than one nipple on semi
            .then(clickZone)
            .then(assertNipple(test))
            .then(clickZone)
            .then(assertNotNipple(test))
            .then(function () {
                // Revert increment because last nipple doesn't exist
                nippleIndex -= 1;
            })
            .run(function () {
                // End tests
                test.done();
            });
    }
);
<|endoftext|>