<commit_before>/**
 * Copyright (c) 2012 Andreas Madsen
 * MIT License
 */

var common = require('../common'),
	thintalk = require(common.modulePath),
    assert = require('assert'),
    child_process = require('child_process');

module.exports = function (layer) {
	var listenerProcess = child_process.fork(common.fixture('lisenter'), [layer]),
		requester = thintalk();

	listenerProcess.once('message', function (msg) {
		if (layer === 'IPC') {
			requester.connect(layer, listenerProcess);
		} else if (layer === 'TCP') {
			requester.connect(layer, common.PORT);
		}
	});

	return [{
		// first batch of tests
		'when connect is emitted': {
			topic: function () {
				var self = this;
				requester.on('connect', function (remote) {
					self.callback(null, requester);
				});
			},

			'the online state is true': function (error, result) {
				assert.isTrue(result.online);
			},

			'when listning on connect again': {
				topic: function () {
					var self = this;
					requester.on('connect', function (remote) {
						self.callback(null, remote);
					});
				},

				'it too will emit properly': function (error, remote) {
					assert.isDefined(remote, 'add');
					assert.isDefined(remote, 'fail');
				}
			}
		},

		'when we request a method there exist': {
			topic: function () {
				var self = this;
				requester.on('connect', function (remote) {
					remote.add(2, 4, function () {
						self.callback(this.error, arguments);
					});
				});
			},

			'callback is called with correct argument': function (error, result) {
				assert.ifError(error);
				assert.equal(result[0], 6);
			},

			'callback is called with error equal null': function (error, result) {
				assert.isNull(error);
			}
		},

		'when we requiest a method there throw': {
			topic: function () {
				var self = this;

				//temporally ignore error
				var none = function () {};
				requester.once('error', none);

				requester.on('connect', function (remote) {
					remote.fail(2, 4, function () {
						requester.removeListener('error', none);
						self.callback(this.error, arguments);
					});
				});
			},

			'callback is called without arguments': function (error, result) {
				assert.isEmpty(result);
			},

			'callback is called with this.error': function (error, result) {
				assert.instanceOf(error, Error);
				assert.equal(error.message, "error");
			}
		}
	}, {
		// second batch of test
		// we will close in this batch so no more should follow

		'when closeing the connection': {
			topic: function () {
				var self = this;

				function close() {
					requester.removeListener('error', error);
					self.callback(null, requester);
				}

				function error(err) {
					requester.removeListener('close', close);
					self.callback(err, null);
				}

				requester.once('error', error);
				requester.once('close', close);
				requester.close();
			},

			'the close event will emit': function (error, result) {
				assert.ifError(error);
			},

			'the online state will become false': function (error, result) {
				assert.ifError(error);
				assert.isFalse(result.online);
			},

			'and atempting to make a request': {
				topic: function () {
					var self = this;

					function error(err) {
						self.callback(err, null);
					}
					requester.on('error', error);

					requester.remote.add(2, 2, function (result) {
						requester.removeListener('error', error);
						self.callback(this.error, result);
					});
				},

				'it will fail': function (err, result) {
					assert.instanceOf(err, Error);
					assert.equal(err.message, 'Could not make a request, channel is offline');
				}
			}
		},

		teardown: function () {
			// this will execute when all contents has been tested
			listenerProcess.kill();
		}
	}];
};<commit_msg>[testcase] test that result is null when requesting on a closed channel<commit_after>/**
 * Copyright (c) 2012 Andreas Madsen
 * MIT License
 */

var common = require('../common'),
	thintalk = require(common.modulePath),
    assert = require('assert'),
    child_process = require('child_process');

module.exports = function (layer) {
	var listenerProcess = child_process.fork(common.fixture('lisenter'), [layer]),
		requester = thintalk();

	listenerProcess.once('message', function (msg) {
		if (layer === 'IPC') {
			requester.connect(layer, listenerProcess);
		} else if (layer === 'TCP') {
			requester.connect(layer, common.PORT);
		}
	});

	return [{
		// first batch of tests
		'when connect is emitted': {
			topic: function () {
				var self = this;
				requester.on('connect', function (remote) {
					self.callback(null, requester);
				});
			},

			'the online state is true': function (error, result) {
				assert.isTrue(result.online);
			},

			'when listning on connect again': {
				topic: function () {
					var self = this;
					requester.on('connect', function (remote) {
						self.callback(null, remote);
					});
				},

				'it too will emit properly': function (error, remote) {
					assert.isDefined(remote, 'add');
					assert.isDefined(remote, 'fail');
				}
			}
		},

		'when we request a method there exist': {
			topic: function () {
				var self = this;
				requester.on('connect', function (remote) {
					remote.add(2, 4, function () {
						self.callback(this.error, arguments);
					});
				});
			},

			'callback is called with correct argument': function (error, result) {
				assert.ifError(error);
				assert.equal(result[0], 6);
			},

			'callback is called with error equal null': function (error, result) {
				assert.isNull(error);
			}
		},

		'when we requiest a method there throw': {
			topic: function () {
				var self = this;

				//temporally ignore error
				var none = function () {};
				requester.once('error', none);

				requester.on('connect', function (remote) {
					remote.fail(2, 4, function () {
						requester.removeListener('error', none);
						self.callback(this.error, arguments);
					});
				});
			},

			'callback is called without arguments': function (error, result) {
				assert.isEmpty(result);
			},

			'callback is called with this.error': function (error, result) {
				assert.instanceOf(error, Error);
				assert.equal(error.message, "error");
			}
		}
	}, {
		// second batch of test
		// we will close in this batch so no more should follow

		'when closeing the connection': {
			topic: function () {
				var self = this;

				function close() {
					requester.removeListener('error', error);
					self.callback(null, requester);
				}

				function error(err) {
					requester.removeListener('close', close);
					self.callback(err, null);
				}

				requester.once('error', error);
				requester.once('close', close);
				requester.close();
			},

			'the close event will emit': function (error, result) {
				assert.ifError(error);
			},

			'the online state will become false': function (error, result) {
				assert.ifError(error);
				assert.isFalse(result.online);
			},

			'and atempting to make a request': {
				topic: function () {
					var self = this;

					function error(err) {
						self.callback(err, null);
					}
					requester.on('error', error);

					requester.remote.add(2, 2, function (result) {
						requester.removeListener('error', error);
						self.callback(this.error, result);
					});
				},

				'it will fail': function (err, result) {
					assert.isNull(result);
					assert.instanceOf(err, Error);
					assert.equal(err.message, 'Could not make a request, channel is offline');
				}
			}
		},

		teardown: function () {
			// this will execute when all contents has been tested
			listenerProcess.kill();
		}
	}];
};<|endoftext|>


<commit_before>/*
This file in the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

var gulp = require('gulp');

/**
 * PostCSS - Tool for transforming styles with JS plugins
 */
var postcss = require("gulp-postcss");

/**
 * PostCSS Reporter - Log PostCSS messages in the console
 */
var reporter = require('postcss-reporter');

/**
 * Stylelint - Modern CSS linter
 */
var stylelint = require('stylelint');

gulp.task('default', function () {

    console.log('You are running Node Version: ' + process.version);

});

gulp.task('stylelint', function () {
    // Stylelint config rules
    var stylelintConfig = {
        "rules": {
            //Color Rules via http://stylelint.io/user-guide/rules/
            //"color-hex-case": "lower", //TBD
            "color-hex-length": "short",
            "color-named": "never",
            "color-no-invalid-hex": true,

            //Font Family
            "font-family-name-quotes": "always-where-recommended",
            "font-family-no-duplicate-names": true,

            //Font weight
            "font-weight-notation": "named-where-possible", //TODO: Look into this more

            //Function
            "function-calc-no-unspaced-operator": true,
            "function-linear-gradient-no-nonstandard-direction": true,
            "function-max-empty-lines": 0,
            "function-name-case": "lower",
            "function-parentheses-newline-inside": "always-multi-line",
            "function-parentheses-space-inside": "never",
            "function-url-data-uris": "never",
            "function-url-no-scheme-relative": true,
            "function-url-quotes": ["always", {
                "except": ["empty"]
            }],
            "function-whitespace-after": "always",

            //Number
            //"number-leading-zero":"always", //Currently the impact to get rid of this is pretty large, but I can see where it's useful
            "number-no-trailing-zeros": true,

            //String
            "string-no-newline": true,
            "string-quotes": "double",

            //Length
            "length-zero-no-unit": true,

            //TODO: Time

            //Unit
            "unit-no-unknown": true,
            "unit-case": "lower",

            //Value
            "value-no-vendor-prefix": true,
            "value-keyword-case": "lower",

            //Value list
            "value-list-comma-newline-after": "always-multi-line",
            "value-list-comma-newline-before": "always-multi-line",
            "value-list-comma-space-after": "always",
            "value-list-comma-space-before": "never",
            "value-list-max-empty-lines": 0,

            //Custom Properties
            //"custom-property-no-outside-root": true, //TODO: Deprecated as of 7.8.0 - a stylelint plugin may exist in it's place

            //Shorthand property
            "shorthand-property-no-redundant-values": true,

            //Property
            "property-case": "lower",
            "property-no-unknown":true,
            //"property-no-vendor-prefix": true, //Currently the impact isn't huge but should be a todo in the future

            //Keyframe declaration
            "keyframe-declaration-no-important": true,

            //Declaration
            "declaration-bang-space-after": "never",
            "declaration-bang-space-before": "always",
            //"declaration-colon-space-after": "always-single-line", //Currently the impact isn't huge but should be a todo in the future
            "declaration-colon-space-before": "never",
            "declaration-empty-line-before": "never",
            //"declaration-no-important": true, //Only use when checking if !important is being used - note that !important is acceptable in utilities

            //TODO: Declaration Block
            "declaration-block-no-duplicate-properties": [true, {
                "ignore": ["consecutive-duplicates-with-different-values"]
            }],
            "declaration-block-no-redundant-longhand-properties": true,
            "declaration-block-no-shorthand-property-overrides": true,
            "declaration-block-semicolon-newline-after": "always-multi-line",
            "declaration-block-semicolon-newline-before": "never-multi-line",
            "declaration-block-semicolon-space-after": "always-single-line",
            "declaration-block-semicolon-space-before": "never",
            "declaration-block-trailing-semicolon": "always",
            //TODO: Block
            //TODO: Selector
            "selector-attribute-brackets-space-inside": "never",
            "selector-attribute-operator-space-after": "never",
            "selector-attribute-operator-space-before": "never",
            "selector-combinator-space-after": "always",
            "selector-combinator-space-before": "always",
            "selector-descendant-combinator-no-non-space": true,
            "selector-no-id": true,
            "selector-pseudo-class-case": "lower",
            "selector-pseudo-class-no-unknown": true,
            "selector-pseudo-class-parentheses-space-inside": "never",
            "selector-pseudo-element-case": "lower",
            "selector-pseudo-element-no-unknown": true,
            "selector-type-case": "lower",
            "selector-type-no-unknown": true,
            "selector-max-empty-lines":0,
            //TODO: Selector List

            //"root-no-standard-properties": true, //Deprecated as of 7.8.0 - a stylelint plugin may exist in it's place

            "rule-empty-line-before": ["always-multi-line", {
                "ignore": ["after-comment","inside-block"]
            }],

            //TODO: Root rule
            //TODO: Rule
            //TODO: Media Feature
            "media-feature-name-case": "lower",
            "media-feature-name-no-unknown": true,
            //TODO: Custom Media
            //Media query list
            "media-query-list-comma-newline-after": "always-multi-line",
            "media-query-list-comma-newline-before": "never-multi-line",
            "media-query-list-comma-space-after": "always-single-line",
            "media-query-list-comma-space-before": "never-single-line",

            //At-rule
            //"at-rule-empty-line-before": "always",
            "at-rule-name-case": "lower",
            //"at-rule-name-newline-after": "always", // Undefined Rule as of as of stylelint: "6.3.3"
            "at-rule-name-space-after": "always",
            "at-rule-no-unknown": true,
            "at-rule-no-vendor-prefix": true,
            "at-rule-semicolon-newline-after": "always",

            //stylelint-disable comment
            //"stylelint-disable-reason": "always-before", //Deprecated as of 7.8.0 - a stylelint plugin may exist in it's place

            //Comments
            "comment-no-empty": true,

            //TODO: General / Sheet
            "max-empty-lines": 2,
            //"max-line-length": [110, {
            //    "ignore": ["comments"]
            // }], //This may or may not be an issue...
            //"no-browser-hacks": true, //Deprecated as of 7.8.0 - a stylelint plugin may exist in it's place - See: stylelint-no-browser-hacks: https://stylelint.io/user-guide/plugins/
            //"no-descending-specificity": true, //Need to look into
            "no-duplicate-selectors": true,
            "no-eol-whitespace": true,
            "no-extra-semicolons": true,
            //"no-indistinguishable-colors": true, // Either Settings needs to be excluded or need to look into when this issue is taken care of: https://github.com/SlexAxton/css-colorguard/issues/49 - or attempt to disable around rules due to this issue - Deprecated
            "no-invalid-double-slash-comments": true,
            "no-missing-end-of-source-newline": true,
            "no-unknown-animations": true,
            //TODO: Setup supported browser list for not only this rule but theme building - https://stylelint.io/user-guide/rules/no-unsupported-browser-features/
            //"no-unsupported-browser-features": true
        }
    }

    var processors = [
      stylelint(stylelintConfig),
      // Pretty reporting config
      reporter({
          clearAllMessages: true,
          throwError: false
      })
    ];

    return gulp.src(
    // Stylesheet source:
    ['./Content/css/src/**/*.css',
    // Ignore linting vendor assets:
    '!./Content/css/src/vendor/**/*.css', '!./Content/css/src/utilities/debug.css', '!./Content/css/src/utilities/deprecated.css', '!./Content/css/src/base/00-Normalize.css']//, '!./Content/css/src/_settings/**/*.css']
  )
  .pipe(postcss(processors));
});
<commit_msg>Add some selector rules<commit_after>/*
This file in the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

var gulp = require('gulp');

/**
 * PostCSS - Tool for transforming styles with JS plugins
 */
var postcss = require("gulp-postcss");

/**
 * PostCSS Reporter - Log PostCSS messages in the console
 */
var reporter = require('postcss-reporter');

/**
 * Stylelint - Modern CSS linter
 */
var stylelint = require('stylelint');

gulp.task('default', function () {

    console.log('You are running Node Version: ' + process.version);

});

gulp.task('stylelint', function () {
    // Stylelint config rules
    var stylelintConfig = {
        "rules": {
            //Color Rules via http://stylelint.io/user-guide/rules/
            //"color-hex-case": "lower", //TBD
            "color-hex-length": "short",
            "color-named": "never",
            "color-no-invalid-hex": true,

            //Font Family
            "font-family-name-quotes": "always-where-recommended",
            "font-family-no-duplicate-names": true,

            //Font weight
            "font-weight-notation": "named-where-possible", //TODO: Look into this more

            //Function
            "function-calc-no-unspaced-operator": true,
            "function-linear-gradient-no-nonstandard-direction": true,
            "function-max-empty-lines": 0,
            "function-name-case": "lower",
            "function-parentheses-newline-inside": "always-multi-line",
            "function-parentheses-space-inside": "never",
            "function-url-data-uris": "never",
            "function-url-no-scheme-relative": true,
            "function-url-quotes": ["always", {
                "except": ["empty"]
            }],
            "function-whitespace-after": "always",

            //Number
            //"number-leading-zero":"always", //Currently the impact to get rid of this is pretty large, but I can see where it's useful
            "number-no-trailing-zeros": true,

            //String
            "string-no-newline": true,
            "string-quotes": "double",

            //Length
            "length-zero-no-unit": true,

            //TODO: Time

            //Unit
            "unit-no-unknown": true,
            "unit-case": "lower",

            //Value
            "value-no-vendor-prefix": true,
            "value-keyword-case": "lower",

            //Value list
            "value-list-comma-newline-after": "always-multi-line",
            "value-list-comma-newline-before": "always-multi-line",
            "value-list-comma-space-after": "always",
            "value-list-comma-space-before": "never",
            "value-list-max-empty-lines": 0,

            //Custom Properties
            //"custom-property-no-outside-root": true, //TODO: Deprecated as of 7.8.0 - a stylelint plugin may exist in it's place

            //Shorthand property
            "shorthand-property-no-redundant-values": true,

            //Property
            "property-case": "lower",
            "property-no-unknown":true,
            //"property-no-vendor-prefix": true, //Currently the impact isn't huge but should be a todo in the future

            //Keyframe declaration
            "keyframe-declaration-no-important": true,

            //Declaration
            "declaration-bang-space-after": "never",
            "declaration-bang-space-before": "always",
            //"declaration-colon-space-after": "always-single-line", //Currently the impact isn't huge but should be a todo in the future
            "declaration-colon-space-before": "never",
            "declaration-empty-line-before": "never",
            //"declaration-no-important": true, //Only use when checking if !important is being used - note that !important is acceptable in utilities

            //TODO: Declaration Block
            "declaration-block-no-duplicate-properties": [true, {
                "ignore": ["consecutive-duplicates-with-different-values"]
            }],
            "declaration-block-no-redundant-longhand-properties": true,
            "declaration-block-no-shorthand-property-overrides": true,
            "declaration-block-semicolon-newline-after": "always-multi-line",
            "declaration-block-semicolon-newline-before": "never-multi-line",
            "declaration-block-semicolon-space-after": "always-single-line",
            "declaration-block-semicolon-space-before": "never",
            "declaration-block-trailing-semicolon": "always",
            //TODO: Block
            //TODO: Selector
            "selector-attribute-brackets-space-inside": "never",
            "selector-attribute-operator-space-after": "never",
            "selector-attribute-operator-space-before": "never",
            "selector-combinator-space-after": "always",
            "selector-combinator-space-before": "always",
            "selector-descendant-combinator-no-non-space": true,
            "selector-max-compound-selectors": 3,
            //"selector-max-specificity": "0,2,1", // Set to what works for you - https://stylelint.io/user-guide/rules/selector-max-specificity/
            "selector-no-id": true,
            "selector-no-universal": true,
            "selector-no-vendor-prefix": true,
            "selector-pseudo-class-case": "lower",
            "selector-pseudo-class-no-unknown": true,
            "selector-pseudo-class-parentheses-space-inside": "never",
            "selector-pseudo-element-case": "lower",
            "selector-pseudo-element-no-unknown": true,
            "selector-type-case": "lower",
            "selector-type-no-unknown": true,
            "selector-max-empty-lines":0,
            //TODO: Selector List
            "selector-list-comma-newline-after": "always-multi-line",
            "selector-list-comma-newline-before": "never-multi-line",

            //"root-no-standard-properties": true, //Deprecated as of 7.8.0 - a stylelint plugin may exist in it's place

            "rule-empty-line-before": ["always-multi-line", {
                "ignore": ["after-comment","inside-block"]
            }],

            //TODO: Root rule
            //TODO: Rule
            //TODO: Media Feature
            "media-feature-name-case": "lower",
            "media-feature-name-no-unknown": true,
            //TODO: Custom Media
            //Media query list
            "media-query-list-comma-newline-after": "always-multi-line",
            "media-query-list-comma-newline-before": "never-multi-line",
            "media-query-list-comma-space-after": "always-single-line",
            "media-query-list-comma-space-before": "never-single-line",

            //At-rule
            //"at-rule-empty-line-before": "always",
            "at-rule-name-case": "lower",
            //"at-rule-name-newline-after": "always", // Undefined Rule as of as of stylelint: "6.3.3"
            "at-rule-name-space-after": "always",
            "at-rule-no-unknown": true,
            "at-rule-no-vendor-prefix": true,
            "at-rule-semicolon-newline-after": "always",

            //stylelint-disable comment
            //"stylelint-disable-reason": "always-before", //Deprecated as of 7.8.0 - a stylelint plugin may exist in it's place

            //Comments
            "comment-no-empty": true,

            //TODO: General / Sheet
            "max-empty-lines": 2,
            //"max-line-length": [110, {
            //    "ignore": ["comments"]
            // }], //This may or may not be an issue...
            //"no-browser-hacks": true, //Deprecated as of 7.8.0 - a stylelint plugin may exist in it's place - See: stylelint-no-browser-hacks: https://stylelint.io/user-guide/plugins/
            //"no-descending-specificity": true, //Need to look into
            "no-duplicate-selectors": true,
            "no-eol-whitespace": true,
            "no-extra-semicolons": true,
            //"no-indistinguishable-colors": true, // Either Settings needs to be excluded or need to look into when this issue is taken care of: https://github.com/SlexAxton/css-colorguard/issues/49 - or attempt to disable around rules due to this issue - Deprecated
            "no-invalid-double-slash-comments": true,
            "no-missing-end-of-source-newline": true,
            "no-unknown-animations": true,
            //TODO: Setup supported browser list for not only this rule but theme building - https://stylelint.io/user-guide/rules/no-unsupported-browser-features/
            //"no-unsupported-browser-features": true
        }
    }

    var processors = [
      stylelint(stylelintConfig),
      // Pretty reporting config
      reporter({
          clearAllMessages: true,
          throwError: false
      })
    ];

    return gulp.src(
    // Stylesheet source:
    ['./Content/css/src/**/*.css',
    // Ignore linting vendor assets:
    '!./Content/css/src/vendor/**/*.css', '!./Content/css/src/utilities/debug.css', '!./Content/css/src/utilities/deprecated.css', '!./Content/css/src/base/00-Normalize.css']//, '!./Content/css/src/_settings/**/*.css']
  )
  .pipe(postcss(processors));
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var gdal = require('../lib/gdal.js');
var path = require('path');
var assert = require('chai').assert;
var fileUtils = require('./utils/file.js');

describe('gdal', function() {
	afterEach(gc);

	describe('contourGenerate()', function() {
		var src, srcband, dst, lyr;

		before(function(){
			//create a simple ramp in memory
			var w = 64;
			var h = 64;
			src = gdal.open('temp', 'w', 'MEM', w, h, 1);
			srcband = src.bands.get(1);
			for(var y = 0; y < h; y++){
				var buf = new Buffer(w);
				buf.fill(y*4);
				srcband.pixels.write(0, y, w, 1, new Uint8Array(buf))
			}
		});
		after(function(){
			src.close();
		});
		beforeEach(function(){
			dst = gdal.open('temp', 'w', 'Memory');

			lyr = dst.layers.create('temp', null, gdal.Linestring);
			lyr.fields.add(new gdal.FieldDefn('id', gdal.OFTInteger))
			lyr.fields.add(new gdal.FieldDefn('elev', gdal.OFTReal))
		});
		afterEach(function(){
			dst.close();
		})
		it('should generate contours when passed an interval / base', function(){

			var offset = 7;
			var interval = 32;

			gdal.contourGenerate({
				src: srcband,
				dst: lyr,
				offset: offset,
				interval: interval,
				idField: 0,
				elevField: 1
			});

			assert(lyr.features.count() > 0, 'features were created');

			lyr.features.forEach(function(feature){
				assert((feature.fields.get('elev') - offset) % interval === 0, 'contour used correct interval / base');
				assert.isFalse(feature.getGeometry().isEmpty());
			});
		});
		it('should accept an array of fixed levels', function(){

			var levels = [53, 43, 193].sort();

			gdal.contourGenerate({
				src: srcband,
				dst: lyr,
				fixedLevels: levels,
				idField: 0,
				elevField: 1
			});

			assert(lyr.features.count() > 0, 'features were created');

			var actual_levels = [];

			lyr.features.forEach(function(feature){
				var elev = feature.fields.get('elev');
				assert.include(levels, elev, 'contour elevation in array of fixed levels');
				assert.isFalse(feature.getGeometry().isEmpty());
				if(actual_levels.indexOf(elev) == -1) actual_levels.push(elev);
			});

			assert.deepEqual(levels, actual_levels.sort(), 'all fixed levels used');
		});
	});
	describe('fillNodata()', function() {
		var src, srcband;
		var holes_x = [53, 61, 61, 1, 43, 44, 5];
		var holes_y = [11, 5, 6, 33, 22, 11, 0];
		var nodata = 33;

		beforeEach(function(){
			var w = 64;
			var h = 64;

			src = gdal.open('temp', 'w', 'MEM', w, h, 1);
			srcband = src.bands.get(1);
			srcband.noDataValue = nodata;

			//sprinkle a solid fill with nodata
			var buf = new Buffer(w*h);
			buf.fill(128);
			srcband.pixels.write(0, 0, w, h, new Uint8Array(buf));
			for(var i = 0; i < holes_x.length; i++){
				srcband.pixels.set(holes_x[i], holes_y[i], nodata);
				assert.equal(srcband.pixels.get(holes_x[i], holes_y[i]), nodata);
			}
		});
		afterEach(function(){
			src.close();
		});
		it('should fill nodata values', function(){

			gdal.fillNodata({
				src: srcband,
				searchDist: 3,
				smoothingIterations: 2
			});

			for(var i = 0; i < holes_x.length; i++){
				assert.notEqual(srcband.pixels.get(holes_x[i], holes_y[i]), nodata);
			}
		});
	});
	describe('checksumImage()', function() {
		var src, band;
		var w = 16;
		var h = 16;
		beforeEach(function(){
			src = gdal.open('temp', 'w', 'MEM', w, h, 1);
			band = src.bands.get(1);
		});
		afterEach(function(){
			src.close();
		});
		it('should generate unique checksum for the given region', function(){

			for (var x = 0; x < w; x++) {
				for (var y = 0; y < h; y++) {
					band.pixels.set(x,y,(x*h+y)%255);
				}
			}
			band.pixels.set(4, 4, 25);
			var a = gdal.checksumImage(band);
			band.pixels.set(4, 4, 93);
			var b = gdal.checksumImage(band);
			var c = gdal.checksumImage(band, 8, 0, w/2, h);

			assert.notEqual(a, b);
			assert.notEqual(b, c);
		});
	});
	describe('sieveFilter()', function() {
		var src, band;
		var w = 64;
		var h = 64;
		beforeEach(function(){
			src = gdal.open('temp', 'w', 'MEM', w, h, 1);
			band = src.bands.get(1);

			//create two rectangles next to eachother of differing sizes
			var small_buffer = new Buffer(4*4);
			small_buffer.fill(10);
			var big_buffer = new Buffer(32*32);
			big_buffer.fill(20);

			band.pixels.write(5,5,32,32,new Uint8Array(big_buffer));
			band.pixels.write(7,7,4,4,new Uint8Array(small_buffer));
		});
		afterEach(function(){
			src.close();
		});
		it('should fill smaller polygons with value from neighboring bigger polygon', function(){

			assert.equal(band.pixels.get(8, 8), 10);

			gdal.sieveFilter({
				src: band,
				dst: band, //in place
				threshold: 4*4+1,
				connectedness: 8
			});

			assert.equal(band.pixels.get(8, 8), 20);
		});
	});

});<commit_msg>Added simple polygonize() test.<commit_after>'use strict';

var fs = require('fs');
var gdal = require('../lib/gdal.js');
var path = require('path');
var assert = require('chai').assert;
var fileUtils = require('./utils/file.js');

describe('gdal', function() {
	afterEach(gc);

	describe('contourGenerate()', function() {
		var src, srcband, dst, lyr;

		before(function(){
			//create a simple ramp in memory
			var w = 64;
			var h = 64;
			src = gdal.open('temp', 'w', 'MEM', w, h, 1);
			srcband = src.bands.get(1);
			for(var y = 0; y < h; y++){
				var buf = new Buffer(w);
				buf.fill(y*4);
				srcband.pixels.write(0, y, w, 1, new Uint8Array(buf))
			}
		});
		after(function(){
			src.close();
		});
		beforeEach(function(){
			dst = gdal.open('temp', 'w', 'Memory');

			lyr = dst.layers.create('temp', null, gdal.Linestring);
			lyr.fields.add(new gdal.FieldDefn('id', gdal.OFTInteger))
			lyr.fields.add(new gdal.FieldDefn('elev', gdal.OFTReal))
		});
		afterEach(function(){
			dst.close();
		})
		it('should generate contours when passed an interval / base', function(){

			var offset = 7;
			var interval = 32;

			gdal.contourGenerate({
				src: srcband,
				dst: lyr,
				offset: offset,
				interval: interval,
				idField: 0,
				elevField: 1
			});

			assert(lyr.features.count() > 0, 'features were created');

			lyr.features.forEach(function(feature){
				assert((feature.fields.get('elev') - offset) % interval === 0, 'contour used correct interval / base');
				assert.isFalse(feature.getGeometry().isEmpty());
			});
		});
		it('should accept an array of fixed levels', function(){

			var levels = [53, 43, 193].sort();

			gdal.contourGenerate({
				src: srcband,
				dst: lyr,
				fixedLevels: levels,
				idField: 0,
				elevField: 1
			});

			assert(lyr.features.count() > 0, 'features were created');

			var actual_levels = [];

			lyr.features.forEach(function(feature){
				var elev = feature.fields.get('elev');
				assert.include(levels, elev, 'contour elevation in array of fixed levels');
				assert.isFalse(feature.getGeometry().isEmpty());
				if(actual_levels.indexOf(elev) == -1) actual_levels.push(elev);
			});

			assert.deepEqual(levels, actual_levels.sort(), 'all fixed levels used');
		});
	});
	describe('fillNodata()', function() {
		var src, srcband;
		var holes_x = [53, 61, 61, 1, 43, 44, 5];
		var holes_y = [11, 5, 6, 33, 22, 11, 0];
		var nodata = 33;

		beforeEach(function(){
			var w = 64;
			var h = 64;

			src = gdal.open('temp', 'w', 'MEM', w, h, 1);
			srcband = src.bands.get(1);
			srcband.noDataValue = nodata;

			//sprinkle a solid fill with nodata
			var buf = new Buffer(w*h);
			buf.fill(128);
			srcband.pixels.write(0, 0, w, h, new Uint8Array(buf));
			for(var i = 0; i < holes_x.length; i++){
				srcband.pixels.set(holes_x[i], holes_y[i], nodata);
				assert.equal(srcband.pixels.get(holes_x[i], holes_y[i]), nodata);
			}
		});
		afterEach(function(){
			src.close();
		});
		it('should fill nodata values', function(){

			gdal.fillNodata({
				src: srcband,
				searchDist: 3,
				smoothingIterations: 2
			});

			for(var i = 0; i < holes_x.length; i++){
				assert.notEqual(srcband.pixels.get(holes_x[i], holes_y[i]), nodata);
			}
		});
	});
	describe('checksumImage()', function() {
		var src, band;
		var w = 16;
		var h = 16;
		beforeEach(function(){
			src = gdal.open('temp', 'w', 'MEM', w, h, 1);
			band = src.bands.get(1);
		});
		afterEach(function(){
			src.close();
		});
		it('should generate unique checksum for the given region', function(){

			for (var x = 0; x < w; x++) {
				for (var y = 0; y < h; y++) {
					band.pixels.set(x,y,(x*h+y)%255);
				}
			}
			band.pixels.set(4, 4, 25);
			var a = gdal.checksumImage(band);
			band.pixels.set(4, 4, 93);
			var b = gdal.checksumImage(band);
			var c = gdal.checksumImage(band, 8, 0, w/2, h);

			assert.notEqual(a, b);
			assert.notEqual(b, c);
		});
	});
	describe('sieveFilter()', function() {
		var src, band;
		var w = 64;
		var h = 64;
		beforeEach(function(){
			src = gdal.open('temp', 'w', 'MEM', w, h, 1);
			band = src.bands.get(1);

			//create two rectangles next to eachother of differing sizes
			var small_buffer = new Buffer(4*4);
			small_buffer.fill(10);
			var big_buffer = new Buffer(32*32);
			big_buffer.fill(20);

			band.pixels.write(5,5,32,32,new Uint8Array(big_buffer));
			band.pixels.write(7,7,4,4,new Uint8Array(small_buffer));
		});
		afterEach(function(){
			src.close();
		});
		it('should fill smaller polygons with value from neighboring bigger polygon', function(){

			assert.equal(band.pixels.get(8, 8), 10);

			gdal.sieveFilter({
				src: band,
				dst: band, //in place
				threshold: 4*4+1,
				connectedness: 8
			});

			assert.equal(band.pixels.get(8, 8), 20);
		});
	});
	describe('polygonize()', function() {
		var src, srcband, dst, lyr;

		before(function(){
			//create two identical rectangles
			var w = 64;
			var h = 64;
			src = gdal.open('temp', 'w', 'MEM', w, h, 1);
			srcband = src.bands.get(1);
			for(var y = 0; y < h; y++){
				var buf = new Buffer(w);
				buf.fill(y & 32);
				srcband.pixels.write(0, y, w, 1, new Uint8Array(buf))
			}
		});
		after(function(){
			src.close();
		});
		beforeEach(function(){
			dst = gdal.open('temp', 'w', 'Memory');

			lyr = dst.layers.create('temp', null, gdal.Polygon);
			lyr.fields.add(new gdal.FieldDefn('val', gdal.OFTInteger));
		});
		afterEach(function(){
			dst.close();
		})
		it('should generate polygons from a RasterBand', function(){

			var offset = 7;
			var interval = 32;

			gdal.polygonize({
				src: srcband,
				dst: lyr,
				pixValField: 0,
				connectedness: 8
			});

			assert.equal(lyr.features.count(), 2);
			lyr.features.forEach(function(f){
				var geom = f.getGeometry();
				assert.isFalse(geom.isEmpty());
				assert.instanceOf(geom, gdal.Polygon);
			});
		});
	});
});<|endoftext|>


<commit_before>"use strict";

var jsdom = require("../..").jsdom;

// These tests are mostly random regression tests, not systematic parsing tests. They are compiled from the bug tracker.

exports["unclosed  (GH-605)"] = function (t) {
  var doc = jsdom("

first tdsecond td

");

  var tds = doc.getElementsByTagName("td");

  t.equal(tds.length, 2);
  t.equal(tds[0].innerHTML, 'first td');
  t.equal(tds[1].innerHTML, 'second td');

  t.done();
};

exports["innerHTML of ");

  var scripts = doc.getElementsByTagName("script");

  t.equal(scripts.length, 1);
  t.equal(scripts[0].innerHTML, "script innerHTML");

  t.done();
};
<commit_msg>Add test for attributes containing < and >. Fixes #494.<commit_after>"use strict";

var jsdom = require("../..").jsdom;

// These tests are mostly random regression tests, not systematic parsing tests. They are compiled from the bug tracker.

exports["unclosed  (GH-605)"] = function (t) {
  var doc = jsdom("

first tdsecond td

");

  var tds = doc.getElementsByTagName("td");

  t.equal(tds.length, 2);
  t.equal(tds[0].innerHTML, 'first td');
  t.equal(tds[1].innerHTML, 'second td');

  t.done();
};

exports["innerHTML of ");

  var scripts = doc.getElementsByTagName("script");

  t.equal(scripts.length, 1);
  t.equal(scripts[0].innerHTML, "script innerHTML");

  t.done();
};

exports["attributes containing '<' and '>' (GH-494)"] = function (t) {
  var doc = jsdom("<p title='<'>stuff

'>more

just testing
");

  var ps = doc.getElementsByTagName("p");

  t.equal(ps.length, 3);
  t.equal(ps[0].getAttribute("title"), "<");
  t.equal(ps[1].getAttribute("title"), ">");

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


<commit_before>var expect = require('chai').expect;
var lob = require('lob-enc');
var Pipe = require('../../lib/pipe.class.js');

describe('pipe', function(){

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

  it('should create new', function(){
    var pipe = new Pipe('test');
    expect(pipe).to.be.an('object');
  });

  it('should call send', function(done){
    var pipe = new Pipe('test');
    pipe.onSend = function(p, cb)
    {
      expect(p).to.be.an('object');
      cb();
    }
    pipe.send({}, done);
  });

  it('should auto-cloak', function(done){
    var pipe = new Pipe('test');
    pipe.cloaked = true;
    pipe.onSend = function(p, cb)
    {
      expect(p).to.be.an('object');
      expect(p.length).to.be.equal(10);
      //console.log("cloaking is awesome",p.toString("hex"));
      cb();
    }
    var packet = lob.decode(new Buffer("\0\0"));
    pipe.send(packet, done);
  });

  it('should emit an event', function(done){
    var pipe = new Pipe('test');
    pipe.on('test',function(on,a){
      expect(on).to.be.true;
      expect(this).to.be.equal(pipe);
      done();
    });
    pipe.emit('test',true);
  });
  /*
  it('should keep/remove/dedup handlers', function(){
    var pipe = new Pipe('test');
    pipe.on('test',function(){ return false; });
    var truer = function(){ return true; };
    pipe.on('test',truer);
    pipe.on('test',truer);
    expect(pipe.ons['test'].length).to.be.equal(2);
    pipe.emit('test');
    expect(pipe.ons['test'].length).to.be.equal(1);
  });
  */
  it('should fire a keepalive', function(done){
    var pipe = new Pipe('test',10);
    pipe.on('keepalive',function(on){
      expect(this).to.be.equal(pipe);
      clearInterval(pipe.timer)
      done();
      return false;
    });
  });

});
<commit_msg>use a Buffer.isBuffer check for better type checking<commit_after>var expect = require('chai').expect;
var lob = require('lob-enc');
var Pipe = require('../../lib/pipe.class.js');

describe('pipe', function(){

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

  it('should create new', function(){
    var pipe = new Pipe('test');
    expect(pipe).to.be.an('object');
  });

  it('should call send', function(done){
    var pipe = new Pipe('test');
    pipe.onSend = function(p, cb)
    {
      expect(p).to.be.an('object');
      cb();
    }
    pipe.send({}, done);
  });

  it('should auto-cloak', function(done){
    var pipe = new Pipe('test');
    pipe.cloaked = true;
    pipe.onSend = function(p, cb)
    {
      expect(Buffer.isBuffer(p)).to.be.true;
      expect(p.length).to.be.equal(10);
      //console.log("cloaking is awesome",p.toString("hex"));
      cb();
    }
    var packet = lob.decode(new Buffer("\0\0"));
    pipe.send(packet, done);
  });

  it('should emit an event', function(done){
    var pipe = new Pipe('test');
    pipe.on('test',function(on,a){
      expect(on).to.be.true;
      expect(this).to.be.equal(pipe);
      done();
    });
    pipe.emit('test',true);
  });
  /*
  it('should keep/remove/dedup handlers', function(){
    var pipe = new Pipe('test');
    pipe.on('test',function(){ return false; });
    var truer = function(){ return true; };
    pipe.on('test',truer);
    pipe.on('test',truer);
    expect(pipe.ons['test'].length).to.be.equal(2);
    pipe.emit('test');
    expect(pipe.ons['test'].length).to.be.equal(1);
  });
  */
  it('should fire a keepalive', function(done){
    var pipe = new Pipe('test',10);
    pipe.on('keepalive',function(on){
      expect(this).to.be.equal(pipe);
      clearInterval(pipe.timer)
      done();
      return false;
    });
  });

});
<|endoftext|>


<commit_before>var rewire = require('rewire');
var manifest = rewire('../manifest');
var moment = require('moment');

module.exports = {
	'Dependency version change to empty string is not a removal': function (test) {

		var user = 'test-user';
		var repo = 'test-repo';

		// The dependency whose version will change from depVer to ""
		var depName = 'test-dep';
		var depVer = '1.3.8';

		var mockManifests = {};

		mockManifests[user + '/' + repo] = {
			data: {
				name: repo,
				version: '1.0.0',
				dependencies: {}
			},
			expires: moment().subtract({days: 1})
		};

		mockManifests[user + '/' + repo].data.dependencies[depName] = depVer;

		// Add the expired manifest to the manifest module's internal cache
		manifest.__set__('manifests', mockManifests);

		// Mock github to return a new package.json file with updated dependencies
		var mockGithub = {
			repos: {
				getContent: function (opts, cb) {

					var data = {
						name: repo,
						version: '1.0.0',
						dependencies: {}
					};

					// Simulate version change from depVer to ""
					data.dependencies[depName] = '';

					cb(null, {content: JSON.stringify(data), encoding: 'utf-8'});
				}
			}
		};

		manifest.__set__('github', mockGithub);

		manifest.on('dependenciesChange', function(diffs) {

			diffs.forEach(function(diff) {
				test.notStrictEqual(null, diff.version);
				test.equal(depVer, diff.previous);
			});

			test.done();
		});

		manifest.getManifest(user, repo, function () {});

		test.expect(2);
	}
};
<commit_msg>Fix the tests<commit_after>var rewire = require('rewire');
var manifest = rewire('../manifest');
var moment = require('moment');

module.exports = {
	'Dependency version change to empty string is not a removal': function (test) {

		var user = 'test-user';
		var repo = 'test-repo';

		// The dependency whose version will change from depVer to ""
		var depName = 'test-dep';
		var depVer = '1.3.8';

		var mockManifests = {};

		mockManifests[user] = {};
		mockManifests[user][repo] = {
			data: {
				name: repo,
				version: '1.0.0',
				dependencies: {}
			},
			expires: moment().subtract({days: 1})
		};

		mockManifests[user][repo].data.dependencies[depName] = depVer;

		// Add the expired manifest to the manifest module's internal cache
		manifest.__set__('manifests', mockManifests);

		// Mock github to return a new package.json file with updated dependencies
		var mockGithub = {
			repos: {
				getContent: function (opts, cb) {

					var data = {
						name: repo,
						version: '1.0.0',
						dependencies: {}
					};

					// Simulate version change from depVer to ""
					data.dependencies[depName] = '';

					cb(null, {content: JSON.stringify(data), encoding: 'utf-8'});
				}
			}
		};

		manifest.__set__('github', mockGithub);

		manifest.on('dependenciesChange', function(diffs) {

			diffs.forEach(function(diff) {
				test.notStrictEqual(null, diff.version);
				test.equal(depVer, diff.previous);
			});

			test.done();
		});

		manifest.getManifest(user, repo, function () {});

		test.expect(2);
	}
};
<|endoftext|>


<commit_before>var assert = require('assert')
var path = require('path')

var minidump = require('..')
var electronDownload = require('electron-download')
var extractZip = require('extract-zip')
var temp = require('temp').track()

describe('minidump', function () {
  this.timeout(60000)

  describe('walkStack()', function () {
    describe('macOS dump', function () {
      it('calls back with a report', function (done) {
        downloadElectronSymbols('darwin', function (error, symbolsPath) {
          if (error) return done(error)

          var dumpPath = path.join(__dirname, 'fixtures', 'mac.dmp')
          minidump.walkStack(dumpPath, symbolsPath, function (error, report) {
            if (error) return done(error)

            report = report.toString()
            assert.notEqual(report.length, 0)
            assert.notEqual(report.indexOf('Electron Framework!atom::(anonymous namespace)::Crash() [atom_bindings.cc : 27 + 0x0]'), -1)
            done()
          })
        })

      })
    })

    describe('Windows dump', function () {
      it('calls back with a report', function (done) {
        downloadElectronSymbols('win32', function (error, symbolsPath) {
          if (error) return done(error)

          var dumpPath = path.join(__dirname, 'fixtures', 'windows.dmp')
          minidump.walkStack(dumpPath, symbolsPath, function (error, report) {
            if (error) return done(error)

            report = report.toString()
            assert.notEqual(report.length, 0)
            assert.notEqual(report.indexOf('electron.exe!atom::`anonymous namespace\'::Crash [atom_bindings.cc : 27 + 0x0]'), -1)
            done()
          })
        })
      })
    })
  })
})

var downloadElectronSymbols = function (platform, callback) {
 var symbolsPath = temp.mkdirSync('node-minidump-')

 electronDownload({
   version: '1.4.3',
   platform: platform,
   symbols: true,
   quiet: true
 }, function (error, zipPath) {
   if (error) return callback(error)
   extractZip(zipPath, {dir: symbolsPath}, function (error) {
     if (error) return callback(error)
     callback(null, path.join(symbolsPath, 'electron.breakpad.syms'))
   })
 })
}
<commit_msg>:art:<commit_after>var assert = require('assert')
var path = require('path')

var minidump = require('..')
var electronDownload = require('electron-download')
var extractZip = require('extract-zip')
var temp = require('temp').track()

describe('minidump', function () {
  this.timeout(60000)

  describe('walkStack()', function () {
    describe('macOS dump', function () {
      it('calls back with a report', function (done) {
        downloadElectronSymbols('darwin', function (error, symbolsPath) {
          if (error) return done(error)

          var dumpPath = path.join(__dirname, 'fixtures', 'mac.dmp')
          minidump.walkStack(dumpPath, symbolsPath, function (error, report) {
            if (error) return done(error)

            report = report.toString()
            assert.notEqual(report.length, 0)
            assert.notEqual(report.indexOf('Electron Framework!atom::(anonymous namespace)::Crash() [atom_bindings.cc : 27 + 0x0]'), -1)
            done()
          })
        })
      })
    })

    describe('Windows dump', function () {
      it('calls back with a report', function (done) {
        downloadElectronSymbols('win32', function (error, symbolsPath) {
          if (error) return done(error)

          var dumpPath = path.join(__dirname, 'fixtures', 'windows.dmp')
          minidump.walkStack(dumpPath, symbolsPath, function (error, report) {
            if (error) return done(error)

            report = report.toString()
            assert.notEqual(report.length, 0)
            assert.notEqual(report.indexOf('electron.exe!atom::`anonymous namespace\'::Crash [atom_bindings.cc : 27 + 0x0]'), -1)
            done()
          })
        })
      })
    })
  })
})

var downloadElectronSymbols = function (platform, callback) {
  electronDownload({
    version: '1.4.3',
    platform: platform,
    symbols: true,
    quiet: true
  }, function (error, zipPath) {
    if (error) return callback(error)

    var symbolsPath = temp.mkdirSync('node-minidump-')
    extractZip(zipPath, {dir: symbolsPath}, function (error) {
      if (error) return callback(error)
      callback(null, path.join(symbolsPath, 'electron.breakpad.syms'))
   })
  })
}
<|endoftext|>


<commit_before>'use strict';

var expect = require('chai').expect;

var PLATFORM_OSX = 'darwin';
var PLATFORM_WINDOWS = 'win32';
var PLATFORM_LINUX = 'linux';

var PLATFORMS = [
  PLATFORM_OSX,
  PLATFORM_LINUX,
  PLATFORM_WINDOWS
];

var platform = process.platform;

var assertExpectedPlatform = function() {
  expect(PLATFORMS).to.contain(platform);
};

describe('#process.platform', function() {
  it('should be an expected value.', function() {
    expect(PLATFORMS).to.contain(platform);
  });
});

module.exports.PLATFORMS = PLATFORMS;

module.exports.PLATFORM_OSX = PLATFORM_OSX;

module.exports.PLATFORM_LINUX = PLATFORM_LINUX;

module.exports.PLATFORM_WINDOWS = PLATFORM_WINDOWS;

module.exports.assertExpectedPlatform = assertExpectedPlatform;

module.exports.ifOsx = function(callback) {
  callback();
};
<commit_msg>gggggraejrkhaeslfkjasdfl<commit_after>'use strict';

var expect = require('chai').expect;

var PLATFORM_OSX = 'darwin';
var PLATFORM_WINDOWS = 'win32';
var PLATFORM_LINUX = 'linux';

var PLATFORMS = [
  PLATFORM_OSX,
  PLATFORM_LINUX,
  PLATFORM_WINDOWS
];

var platform = process.platform;

var assertExpectedPlatform = function() {
  expect(PLATFORMS).to.contain(platform);
};

describe('#process.platform', function() {
  it('should be an expected value.', function() {
    expect(PLATFORMS).to.contain(platform);
  });
});

module.exports.PLATFORMS = PLATFORMS;

module.exports.PLATFORM_OSX = PLATFORM_OSX;

module.exports.PLATFORM_LINUX = PLATFORM_LINUX;

module.exports.PLATFORM_WINDOWS = PLATFORM_WINDOWS;

module.exports.assertExpectedPlatform = assertExpectedPlatform;

module.exports.ifOsx = function(callback) {
  if (platform === PLATFORM_OSX) {
    callback();
  }
};
<|endoftext|>


<commit_before>var assert = require('chai').assert,
    Reflux = require('../src'),
    Action = Reflux.createAction,
    Store = Reflux.createStore,
    fn = function(){};

describe('Stopping',function(){
    describe('a single listen', function(){
        describe('by calling stop directly',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(Action(),fn);
                store.listenTo(action3,fn);
                it('should remove that listener from the list but keep the others',function(){
                    store.subscriptions[1].stop();
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
            });
            describe('when the listener has already been removed from the list somehow',function(){
                var store = Store();
                store.listenTo(Action(),fn);
                store.listenTo(Action(),fn);
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.subscriptions.pop().stop();
                    });
                });
            });
        });
        describe('by using stopListenTo',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action2 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(action2,fn);
                store.listenTo(action3,fn);
                var result = store.stopListeningTo(action2);
                it('should remove that listener from the list but keep the others',function(){
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
                it('should return true',function(){
                    assert.equal(true,result);
                });
            });
            describe('when the stop method won\'t remove it from the array',function(){
                var store = Store(),
                    action = Action();
                store.listenTo(action,fn);
                store.subscriptions[0].stop = fn;
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.stopListeningTo(action);
                    });
                });
            });
        });
    });
    describe('all listens',function(){
        describe('when all is well',function(){
            var store = Store();
            store.listenTo(Action(),fn);
            store.listenTo(Action(),fn);
            it('should clear the subscriptions list',function(){
                store.stopListeningToAll();
                assert.deepEqual([],store.subscriptions);
            });
        });
        describe('when a stop fails to remove the subscription object from the list',function(){
            var store = Store();
            store.listenTo(Action());
            store.subscriptions[0].stop = fn;
            it('should throw an error',function(){
                assert.throws(function(){
                    store.stopListeningToAll();
                });
            });
        });
    });
});
<commit_msg>added tests for stopping non-listenings<commit_after>var assert = require('chai').assert,
    Reflux = require('../src'),
    Action = Reflux.createAction,
    Store = Reflux.createStore,
    fn = function(){};

describe('Stopping',function(){
    describe('a single listen', function(){
        describe('by calling stop directly',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(Action(),fn);
                store.listenTo(action3,fn);
                it('should remove that listener from the list but keep the others',function(){
                    store.subscriptions[1].stop();
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
            });
            describe('when the listener has already been removed from the list somehow',function(){
                var store = Store();
                store.listenTo(Action(),fn);
                store.listenTo(Action(),fn);
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.subscriptions.pop().stop();
                    });
                });
            });
        });
        describe('by using stopListenTo',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action2 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(action2,fn);
                store.listenTo(action3,fn);
                var result = store.stopListeningTo(action2);
                it('should remove that listener from the list but keep the others',function(){
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
                it('should return true',function(){
                    assert.equal(true,result);
                });
            });
            describe('when the stop method won\'t remove it from the array',function(){
                var store = Store(),
                    action = Action();
                store.listenTo(action,fn);
                store.subscriptions[0].stop = fn;
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.stopListeningTo(action);
                    });
                });
            });
            describe('when we weren\'t actually listening to the given listenable',function(){
                var action1 = Action(),
                    action2 = Action(),
                    store = Store(),
                    result;
                store.listenTo(action1);
                store.listenTo(action2);
                result = Store().stopListeningTo(Action());
                it('should return false',function(){
                    assert.equal(false,result);
                });
                it('should leave the other listens intact',function(){
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action2,store.subscriptions[1].listenable);
                });
            });
            describe('when we don\'t have a subscriptions list',function(){
                var store = Store(), result;
                delete store.subscriptions;
                result = store.stopListeningTo(Action());
                it('should return false',function(){
                    assert.equal(result,false);
                });
            });
        });
    });
    describe('all listens',function(){
        describe('when all is well',function(){
            var store = Store();
            store.listenTo(Action(),fn);
            store.listenTo(Action(),fn);
            it('should clear the subscriptions list',function(){
                store.stopListeningToAll();
                assert.deepEqual([],store.subscriptions);
            });
        });
        describe('when a stop fails to remove the subscription object from the list',function(){
            var store = Store();
            store.listenTo(Action());
            store.subscriptions[0].stop = fn;
            it('should throw an error',function(){
                assert.throws(function(){
                    store.stopListeningToAll();
                });
            });
        });
        describe('when we don\'t have a subscriptions list',function(){
            var store = Store();
            delete store.subscriptions;
            it('should be a noop',function(){
                store.stopListeningToAll();
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

// Reinitialize the URL hash:
window.location.hash = '';

var Baobab = require('baobab'),
    assert = require('assert'),
    BaobabRouter = require('../baobab-router.js');

// Instanciate a Baobab tree and its related router:
var unloggedState = {
      logged: false,
      view: null,
      data: {
        pid: null
      }
    },
    loggedState = {
      logged: true,
      view: 'home',
      data: {
        pid: null
      }
    },
    routes = {
      defaultRoute: '/login',
      readOnly: [['logged']],
      routes: [
        {
          path: '/login',
          state: { view: 'login',
                   logged: false,
                   data: { pid: null } }
        },
        {
          state: { logged: true,
                   data: { pid: null } },
          defaultRoute: '/home',
          routes: [
            {
              path: '/home',
              state: { view: 'home' }
            },
            {
              path: '/settings',
              state: { view: 'settings', }
            },
            {
              path: '/project/:pid',
              state: { view: 'project',
                       data: { pid: ':pid' } },
              routes: [
                {
                  path: '/settings',
                  state: { view: 'project.settings' }
                },
                {
                  path: '/dashboard',
                  state: { view: 'project.dashboard' }
                }
              ]
            }
          ]
        }
      ]
    };

function _newTree(state) {
  return new Baobab(state || loggedState);
}

function _newRouter(tree) {
  return new BaobabRouter(tree || _newTree(), routes);
}

describe('Instanciation and destruction:', function() {
  var tree,
      router;

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('it should update the URL when the router is instanciated', function(done) {
    assert.equal(window.location.hash, '');
    tree = _newTree();
    router = _newRouter(tree);

    setTimeout(function() {
      assert.equal(window.location.hash, '#/home');
      assert.equal(tree.get('view'), 'home');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });
});

describe('Ascending communication', function() {
  var tree,
      router;

  beforeEach(function(done) {
    window.location.hash = '';
    tree = _newTree();
    router = _newRouter(tree);

    setTimeout(done, 0);
  });

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('should stop on the first matching case', function(done) {
    tree.set('logged', true)
        .set('view', 'settings')
        .set(['data', 'pid'], null)
        .commit();

    assert.equal(window.location.hash, '#/settings');
    assert.equal(tree.get('view'), 'settings');
    assert.equal(tree.get('data', 'pid'), null);

    setTimeout(function() {
      done();
    }, 0);
  });

  it('should check all cases until one matches', function(done) {
    tree.set('logged', true)
        .set('view', 'home')
        .set(['data', 'pid'], null)
        .commit();

    assert.equal(window.location.hash, '#/home');
    assert.equal(tree.get('view'), 'home');
    assert.equal(tree.get('data', 'pid'), null);

    setTimeout(function() {
      done();
    }, 0);
  });

  it('should work with dynamics attributes', function(done) {
    tree.set('logged', true)
        .set('view', 'project')
        .set(['data', 'pid'], '123456')
        .commit();

    assert.equal(window.location.hash, '#/project/123456');
    assert.equal(tree.get('view'), 'project');
    assert.equal(tree.get('data', 'pid'), '123456');

    setTimeout(function() {
      done();
    }, 0);
  });

  it('should work with children overriding values', function(done) {
    tree.set('logged', true)
        .set('view', 'project.settings')
        .set(['data', 'pid'], '123456')
        .commit();

    assert.equal(window.location.hash, '#/project/123456/settings');
    assert.equal(tree.get('view'), 'project.settings');
    assert.equal(tree.get('data', 'pid'), '123456');

    setTimeout(function() {
      done();
    }, 0);
  });

  it('should not match cases where some dynamic attributes are missing', function(done) {
    tree.set('logged', true)
        .set('view', 'project')
        .set(['data', 'pid'], null)
        .commit();

    assert.equal(window.location.hash, '#/home');
    assert.equal(tree.get('view'), 'home');
    assert.equal(tree.get('data', 'pid'), null);

    setTimeout(function() {
      done();
    }, 0);
  });
});

describe('Descending communication', function() {
  var tree,
      router;

  beforeEach(function(done) {
    window.location.hash = '';
    tree = _newTree();
    router = _newRouter(tree);

    setTimeout(done, 0);
  });

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('should fallback to the default route when no route matches', function(done) {
    window.location.hash = '#/invalid/route';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/home');
      assert.equal(tree.get('view'), 'home');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should fallback to the default route when no route matches - bis', function(done) {
    window.location.hash = '#/project';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/home');
      assert.equal(tree.get('view'), 'home');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should work fine when a route does match', function(done) {
    window.location.hash = '#/home';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/home');
      assert.equal(tree.get('view'), 'home');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should work fine when a route does match - bis', function(done) {
    window.location.hash = '#/settings';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/settings');
      assert.equal(tree.get('view'), 'settings');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should work fine when a route does match with dynamic attribute', function(done) {
    window.location.hash = '#/project/123456';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/project/123456');
      assert.equal(tree.get('view'), 'project');
      assert.equal(tree.get('data', 'pid'), '123456');
      done();
    }, 0);
  });

  it('should work fine when a route does match with dynamic attribute - bis', function(done) {
    window.location.hash = '#/project/123456/settings';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/project/123456/settings');
      assert.equal(tree.get('view'), 'project.settings');
      assert.equal(tree.get('data', 'pid'), '123456');
      done();
    }, 0);
  });
});

describe('Read-only state constraints', function() {
  var tree,
      router;

  beforeEach(function(done) {
    window.location.hash = '';
    tree = _newTree(unloggedState);
    router = _newRouter(tree);

    setTimeout(done, 0);
  });

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('should fallback on a route with the good values for read-only constraints (ascending)', function(done) {
    tree.set('logged', false)
        .set('view', 'home')
        .set(['data', 'pid'], null)
        .commit();

    setTimeout(function() {
      assert.equal(window.location.hash, '#/login');
      assert.equal(tree.get('logged'), false);
      assert.equal(tree.get('view'), 'login');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should fallback on a route with the good values for read-only constraints (descending)', function(done) {
    window.location.hash = '#/home';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/login');
      assert.equal(tree.get('logged'), false);
      assert.equal(tree.get('view'), 'login');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });
});

describe('API and errors', function() {
  it('should throw an error when a router is initialized without default route', function() {
    assert.throws(
      function() {
        var router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { path: '/toto', state: { toto: true } } ] }
        );
      },
      /The root must have a default route/
    );
  });

  it('should throw an error when a route does not have any state restriction', function() {
    assert.throws(
      function() {
        var router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { path: 'app' } ], defaultRoute: 'app' }
        );
      },
      /Each route should have some state restrictions/
    );
  });

  it('should throw an error when the default route does not match any existing route', function() {
    assert.throws(
      function() {
        var router = new BaobabRouter(
          new Baobab({ toto: null }),
          { defaultRoute: 'somethingElse' }
        );
      },
      /The default route "somethingElse" does not match any registered route/
    );

    assert.throws(
      function() {
        var router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { path: 'app', state: { key: 'value' } } ], defaultRoute: 'somethingElse' }
        );
      },
      /The default route "somethingElse" does not match any registered route/
    );
  });

  it('should throw an error when a route does not have any path nor defaultRoute', function() {
    assert.throws(
      function() {
        var router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { state: { key: 'value' } } ] }
        );
      },
      /A route must have either a path or a default route/
    );

    assert.throws(
      function() {
        var router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { state: { key: 'value' }, routes: [ { path: '/somePath', state: { key2: 'value2' } } ] } ] }
        );
      },
      /A route must have either a path or a default route/
    );
  });

  it('should throw an error when a router is bound to a tree that already has a router', function() {
    var tree = _newTree(),
        router1 = _newRouter(tree);

    assert.throws(
      function() { _newRouter(tree); },
      /A router has already been bound to this tree/
    );
  });
});

describe('Facets support', function() {
  var tree,
      router;

  beforeEach(function(done) {
    window.location.hash = '';
    tree = new Baobab(

      // Data
      {
        user: null,
        view: null
      },

      // Options
      {
        facets: {
          logged: {
            cursors: {
              user: ['user']
            },
            get: function(data) {
              return !!data.user;
            }
          }
        }
      }
    );

    router = new BaobabRouter(tree, {
      readOnly: [['user']],
      defaultRoute: '/',
      routes: [

        // Login
        {
          path: '/login',
          facets: {
            logged: false
          },
          state: {
            view: 'login'
          }
        },

        // Home
        {
          path: '/',
          facets: {
            logged: true
          },
          state: {
            view: 'home'
          }
        }
      ]
    });

    setTimeout(done, 0);
  });

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('should work with both facets and state.', function(done) {

    assert.strictEqual(window.location.hash, '#/login');
    assert(!tree.facets.logged.get());
    assert.strictEqual(tree.get('view'), 'login');

    window.location.hash = '';

    // Trying to override hash
    setTimeout(function() {
      assert.strictEqual(window.location.hash, '#/login');
      assert(!tree.facets.logged.get());
      assert.strictEqual(tree.get('view'), 'login');

      // Setting our user
      tree.set('user', {name: 'John'});

      setTimeout(function() {
        assert.strictEqual(window.location.hash, '');
        assert(tree.facets.logged.get());
        assert.strictEqual(tree.get('view'), 'home');

        done();
      }, 30);
    }, 30);
  });
});
<commit_msg>Fixed API unit tests<commit_after>'use strict';

// Reinitialize the URL hash:
window.location.hash = '';

var Baobab = require('baobab'),
    assert = require('assert'),
    BaobabRouter = require('../baobab-router.js');

// Instanciate a Baobab tree and its related router:
var unloggedState = {
      logged: false,
      view: null,
      data: {
        pid: null
      }
    },
    loggedState = {
      logged: true,
      view: 'home',
      data: {
        pid: null
      }
    },
    routes = {
      defaultRoute: '/login',
      readOnly: [['logged']],
      routes: [
        {
          path: '/login',
          state: { view: 'login',
                   logged: false,
                   data: { pid: null } }
        },
        {
          state: { logged: true,
                   data: { pid: null } },
          defaultRoute: '/home',
          routes: [
            {
              path: '/home',
              state: { view: 'home' }
            },
            {
              path: '/settings',
              state: { view: 'settings', }
            },
            {
              path: '/project/:pid',
              state: { view: 'project',
                       data: { pid: ':pid' } },
              routes: [
                {
                  path: '/settings',
                  state: { view: 'project.settings' }
                },
                {
                  path: '/dashboard',
                  state: { view: 'project.dashboard' }
                }
              ]
            }
          ]
        }
      ]
    };

function _newTree(state) {
  return new Baobab(state || loggedState);
}

function _newRouter(tree) {
  return new BaobabRouter(tree || _newTree(), routes);
}

describe('Instanciation and destruction:', function() {
  var tree,
      router;

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('it should update the URL when the router is instanciated', function(done) {
    assert.equal(window.location.hash, '');
    tree = _newTree();
    router = _newRouter(tree);

    setTimeout(function() {
      assert.equal(window.location.hash, '#/home');
      assert.equal(tree.get('view'), 'home');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });
});

describe('Ascending communication', function() {
  var tree,
      router;

  beforeEach(function(done) {
    window.location.hash = '';
    tree = _newTree();
    router = _newRouter(tree);

    setTimeout(done, 0);
  });

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('should stop on the first matching case', function(done) {
    tree.set('logged', true)
        .set('view', 'settings')
        .set(['data', 'pid'], null)
        .commit();

    assert.equal(window.location.hash, '#/settings');
    assert.equal(tree.get('view'), 'settings');
    assert.equal(tree.get('data', 'pid'), null);

    setTimeout(function() {
      done();
    }, 0);
  });

  it('should check all cases until one matches', function(done) {
    tree.set('logged', true)
        .set('view', 'home')
        .set(['data', 'pid'], null)
        .commit();

    assert.equal(window.location.hash, '#/home');
    assert.equal(tree.get('view'), 'home');
    assert.equal(tree.get('data', 'pid'), null);

    setTimeout(function() {
      done();
    }, 0);
  });

  it('should work with dynamics attributes', function(done) {
    tree.set('logged', true)
        .set('view', 'project')
        .set(['data', 'pid'], '123456')
        .commit();

    assert.equal(window.location.hash, '#/project/123456');
    assert.equal(tree.get('view'), 'project');
    assert.equal(tree.get('data', 'pid'), '123456');

    setTimeout(function() {
      done();
    }, 0);
  });

  it('should work with children overriding values', function(done) {
    tree.set('logged', true)
        .set('view', 'project.settings')
        .set(['data', 'pid'], '123456')
        .commit();

    assert.equal(window.location.hash, '#/project/123456/settings');
    assert.equal(tree.get('view'), 'project.settings');
    assert.equal(tree.get('data', 'pid'), '123456');

    setTimeout(function() {
      done();
    }, 0);
  });

  it('should not match cases where some dynamic attributes are missing', function(done) {
    tree.set('logged', true)
        .set('view', 'project')
        .set(['data', 'pid'], null)
        .commit();

    assert.equal(window.location.hash, '#/home');
    assert.equal(tree.get('view'), 'home');
    assert.equal(tree.get('data', 'pid'), null);

    setTimeout(function() {
      done();
    }, 0);
  });
});

describe('Descending communication', function() {
  var tree,
      router;

  beforeEach(function(done) {
    window.location.hash = '';
    tree = _newTree();
    router = _newRouter(tree);

    setTimeout(done, 0);
  });

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('should fallback to the default route when no route matches', function(done) {
    window.location.hash = '#/invalid/route';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/home');
      assert.equal(tree.get('view'), 'home');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should fallback to the default route when no route matches - bis', function(done) {
    window.location.hash = '#/project';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/home');
      assert.equal(tree.get('view'), 'home');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should work fine when a route does match', function(done) {
    window.location.hash = '#/home';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/home');
      assert.equal(tree.get('view'), 'home');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should work fine when a route does match - bis', function(done) {
    window.location.hash = '#/settings';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/settings');
      assert.equal(tree.get('view'), 'settings');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should work fine when a route does match with dynamic attribute', function(done) {
    window.location.hash = '#/project/123456';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/project/123456');
      assert.equal(tree.get('view'), 'project');
      assert.equal(tree.get('data', 'pid'), '123456');
      done();
    }, 0);
  });

  it('should work fine when a route does match with dynamic attribute - bis', function(done) {
    window.location.hash = '#/project/123456/settings';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/project/123456/settings');
      assert.equal(tree.get('view'), 'project.settings');
      assert.equal(tree.get('data', 'pid'), '123456');
      done();
    }, 0);
  });
});

describe('Read-only state constraints', function() {
  var tree,
      router;

  beforeEach(function(done) {
    window.location.hash = '';
    tree = _newTree(unloggedState);
    router = _newRouter(tree);

    setTimeout(done, 0);
  });

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('should fallback on a route with the good values for read-only constraints (ascending)', function(done) {
    tree.set('logged', false)
        .set('view', 'home')
        .set(['data', 'pid'], null)
        .commit();

    setTimeout(function() {
      assert.equal(window.location.hash, '#/login');
      assert.equal(tree.get('logged'), false);
      assert.equal(tree.get('view'), 'login');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });

  it('should fallback on a route with the good values for read-only constraints (descending)', function(done) {
    window.location.hash = '#/home';

    setTimeout(function() {
      assert.equal(window.location.hash, '#/login');
      assert.equal(tree.get('logged'), false);
      assert.equal(tree.get('view'), 'login');
      assert.equal(tree.get('data', 'pid'), null);
      done();
    }, 0);
  });
});

describe('API and errors', function() {
  var router;

  afterEach(function(done) {
    if (router && router.kill) {
      router.kill();
      window.location.hash = '';
      router = null;
    }

    setTimeout(done, 0);
  });

  it('should throw an error when a router is initialized without default route', function() {
    assert.throws(
      function() {
        router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { path: '/toto', state: { toto: true } } ] }
        );
      },
      /The root must have a default route/
    );
  });

  it('should throw an error when a route does not have any state restriction', function() {
    assert.throws(
      function() {
        router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { path: 'app' } ], defaultRoute: 'app' }
        );
      },
      /Each route should have some state restrictions/
    );
  });

  it('should throw an error when the default route does not match any existing route', function() {
    assert.throws(
      function() {
        router = new BaobabRouter(
          new Baobab({ toto: null }),
          { defaultRoute: 'somethingElse' }
        );
      },
      /The default route "somethingElse" does not match any registered route/
    );

    assert.throws(
      function() {
        router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { path: 'app', state: { key: 'value' } } ], defaultRoute: 'somethingElse' }
        );
      },
      /The default route "somethingElse" does not match any registered route/
    );
  });

  it('should throw an error when a route does not have any path nor defaultRoute', function() {
    assert.throws(
      function() {
        router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { state: { key: 'value' } } ] }
        );
      },
      /A route must have either a path or a default route/
    );

    assert.throws(
      function() {
        router = new BaobabRouter(
          new Baobab({ toto: null }),
          { routes: [ { state: { key: 'value' }, routes: [ { path: '/somePath', state: { key2: 'value2' } } ] } ] }
        );
      },
      /A route must have either a path or a default route/
    );
  });

  it('should throw an error when a router is bound to a tree that already has a router', function() {
    var router2,
        tree = _newTree();

    router = _newRouter(tree);

    assert.throws(
      function() { router2 = _newRouter(tree); },
      /A router has already been bound to this tree/
    );

    if (router2 && router2.kill)
      router2.kill();
  });
});

describe('Facets support', function() {
  var tree,
      router;

  beforeEach(function(done) {
    window.location.hash = '';
    tree = new Baobab(

      // Data
      {
        user: null,
        view: null
      },

      // Options
      {
        facets: {
          logged: {
            cursors: {
              user: ['user']
            },
            get: function(data) {
              return !!data.user;
            }
          }
        }
      }
    );

    router = new BaobabRouter(tree, {
      readOnly: [['user']],
      defaultRoute: '/',
      routes: [

        // Login
        {
          path: '/login',
          facets: {
            logged: false
          },
          state: {
            view: 'login'
          }
        },

        // Home
        {
          path: '/',
          facets: {
            logged: true
          },
          state: {
            view: 'home'
          }
        }
      ]
    });

    setTimeout(done, 0);
  });

  afterEach(function(done) {
    router.kill();
    window.location.hash = '';
    router = null;

    setTimeout(done, 0);
  });

  it('should work with both facets and state.', function(done) {

    assert.strictEqual(window.location.hash, '#/login');
    assert(!tree.facets.logged.get());
    assert.strictEqual(tree.get('view'), 'login');

    window.location.hash = '';

    // Trying to override hash
    setTimeout(function() {
      assert.strictEqual(window.location.hash, '#/login');
      assert(!tree.facets.logged.get());
      assert.strictEqual(tree.get('view'), 'login');

      // Setting our user
      tree.set('user', {name: 'John'});

      setTimeout(function() {
        assert.strictEqual(window.location.hash, '');
        assert(tree.facets.logged.get());
        assert.strictEqual(tree.get('view'), 'home');

        done();
      }, 30);
    }, 30);
  });
});
<|endoftext|>


<commit_before>var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var RK = require('../react-kinetic');

describe('Stage', function () {
  it('can render empty Stage', function () {
    var stage = TestUtils.renderIntoDocument(RK.Stage(null));
    expect(stage.getDOMNode().textContent).toEqual('');
  });
});

function renderSingle(type, component) {
  var stage = TestUtils.renderIntoDocument(
    RK.Stage(null,
      RK.Layer(null, component)));
  return TestUtils.findRenderedComponentWithType(stage, type);
}

describe('Circle', function () {
  it('can render Circle', function () {
    var rendered = renderSingle(RK.Circle, RK.Circle({x: 10, y: 20, radius: 5, stroke: 'red'}));
    expect(rendered.props.x).toBe(10);
    expect(rendered.props.y).toBe(20);
    expect(rendered.props.radius).toBe(5);
  });
});

describe('Text', function () {
  it('can render Text with no size', function () {
    var rendered = renderSingle(RK.Text, RK.Text(null, "Hello, world"));
    expect(rendered.getDOMNode().textContent).toEqual('Hello, world');
  });
  it('can render Text with size', function () {
    var rendered = renderSingle(RK.Text, RK.Text({
      x: 10,
      y: 15,
      text: 'Simple Text',
      fontSize: 30,
      fontFamily: 'Calibri',
      fill: 'green'
    }, "Hello, world"));
    expect(rendered.getDOMNode().textContent).toEqual('Hello, world');
  });
});

describe('TextPath', function () {
  it('can render TextPath', function () {
    var txt = 'All the world\'s a stage, and all the men and women merely players.';
    var rendered = renderSingle(RK.TextPath, RK.TextPath({
      x: 100,
      y: 50,
      fill: '#333',
      fontSize: '24',
      fontFamily: 'Arial',
      text: txt,
      data: 'M10,10 C0,0 10,150 100,100 S300,150 400,50'
    }));
    expect(rendered.props.text).toBe(txt);
  });
});
<commit_msg>Unit test Circle rendering, checking the Kinetic node not rendering to DOM.<commit_after>var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var RK = require('../react-kinetic');

describe('Stage', function () {
  it('can render empty Stage', function () {
    var stage = TestUtils.renderIntoDocument(RK.Stage(null));
    expect(stage.getDOMNode().textContent).toEqual('');
  });
});

function renderSingle(type, component) {
  var stageInstance = TestUtils.renderIntoDocument(
    RK.Stage(null,
      RK.Layer(null, component)));
  return TestUtils.findRenderedComponentWithType(stageInstance, type);
}

describe('Circle', function () {
  it('can render Circle', function () {
    var stageInstance = TestUtils.renderIntoDocument(
      RK.Stage(null,
        RK.Layer(null, RK.Circle({id: 1, x: 10, y: 20, radius: 5, stroke: 'red'}))));
    var circleInstance = TestUtils.findRenderedComponentWithType(stageInstance, RK.Circle);
    var kineticCircle = circleInstance.getKineticNode();
    expect(kineticCircle.x()).toBe(10);
    expect(kineticCircle.y()).toBe(20);
    expect(kineticCircle.radius()).toBe(5);
    expect(kineticCircle.stroke()).toBe('red');
    expect(kineticCircle.id()).toBe(1);
  });
});

describe('Text', function () {
  it('can render Text with no size', function () {
    var rendered = renderSingle(RK.Text, RK.Text(null, "Hello, world"));
    expect(rendered.getDOMNode().textContent).toEqual('Hello, world');
  });
  it('can render Text with size', function () {
    var rendered = renderSingle(RK.Text, RK.Text({
      id: "text1",
      x: 10,
      y: 15,
      text: 'Simple Text',
      fontSize: 30,
      fontFamily: 'Calibri',
      fill: 'green'
    }, "Hello, world"));
    expect(rendered.getDOMNode().textContent).toEqual('Hello, world');
  });
});

describe('TextPath', function () {
  it('can render TextPath', function () {
    var txt = 'All the world\'s a stage, and all the men and women merely players.';
    var rendered = renderSingle(RK.TextPath, RK.TextPath({
      x: 100,
      y: 50,
      fill: '#333',
      fontSize: '24',
      fontFamily: 'Arial',
      text: txt,
      data: 'M10,10 C0,0 10,150 100,100 S300,150 400,50'
    }));
    expect(rendered.props.text).toBe(txt);
  });
});
<|endoftext|>