<commit_before>/* globals describe, it */
"use strict";

require("should");

const webpack = require("../lib/webpack");

describe("Validation", () => {
	const testCases = [{
		name: "undefined configuration",
		config: undefined,
		message: [
			" - configuration should be an object."
		]
	}, {
		name: "null configuration",
		config: null,
		message: [
			" - configuration should be an object."
		]
	}, {
		name: "empty configuration",
		config: {},
		message: [
			" - configuration misses the property 'entry'.",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation."
		]
	}, {
		name: "empty entry string",
		config: {
			entry: ""
		},
		message: [
			" - configuration.entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration.entry should be an object.",
			"      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
			"    * configuration.entry should not be empty.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry should be an array:",
			"      [non-empty string]",
			"    * configuration.entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things."
		]
	}, {
		name: "empty entry bundle array",
		config: {
			entry: {
				"bundle": []
			}
		},
		message: [
			" - configuration.entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration.entry['bundle'] should be a string.",
			"      -> The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry['bundle'] should not be empty.",
			"    * configuration.entry should be a string.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry should be an array:",
			"      [non-empty string]",
			"    * configuration.entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things."
		]
	}, {
		name: "invalid instanceof",
		config: {
			entry: "a",
			module: {
				wrappedContextRegExp: 1337
			}
		},
		message: [
			" - configuration.module.wrappedContextRegExp should be an instance of RegExp",
			"   -> Set the inner regular expression for partial dynamic dependencies"
		]
	}, {
		name: "invalid minimum",
		config: {
			entry: "a",
			parallelism: 0
		},
		message: [
			" - configuration.parallelism should be >= 1.",
			"   -> The number of parallel processed modules in the compilation."
		]
	}, {
		name: "repeated value",
		config: {
			entry: ["abc", "def", "abc"]
		},
		message: [
			" - configuration.entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration.entry should be an object.",
			"      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
			"    * configuration.entry should be a string.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry should not contain the item 'abc' twice.",
			"    * configuration.entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
		]
	}, {
		name: "multiple errors",
		config: {
			entry: [/a/],
			output: {
				filename: /a/
			}
		},
		message: [
			" - configuration.entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration.entry should be an object.",
			"      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
			"    * configuration.entry should be a string.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry[0] should be a string.",
			"      -> A non-empty string",
			"    * configuration.entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
			" - configuration.output.filename should be a string.",
			"   -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files."
		]
	}, {
		name: "multiple configurations",
		config: [{
			entry: [/a/],
		}, {
			entry: "a",
			output: {
				filename: /a/
			}
		}],
		message: [
			" - configuration[0].entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration[0].entry should be an object.",
			"      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
			"    * configuration[0].entry should be a string.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration[0].entry[0] should be a string.",
			"      -> A non-empty string",
			"    * configuration[0].entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
			" - configuration[1].output.filename should be a string.",
			"   -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files."
		]
	}, {
		name: "deep error",
		config: {
			entry: "a",
			module: {
				rules: [{
					oneOf: [{
						test: "/a",
						paser: {
							amd: false
						}
					}]
				}]
			}
		},
		message: [
			" - configuration.module.rules[0].oneOf[0] has an unknown property 'paser'. These properties are valid:",
			"   object { enforce?, exclude?, include?, issuer?, loader?, loaders?, oneOf?, options?, parser?, query?, resource?, resourceQuery?, compiler?, rules?, test?, use? }",
			"   -> A rule"
		]
	}, {
		name: "additional key on root",
		config: {
			entry: "a",
			postcss: () => {}
		},
		message: [
			" - configuration has an unknown property 'postcss'. These properties are valid:",
			"   object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, " +
			"loader?, module?, name?, node?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, " +
			"recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }",
			"   For typos: please correct them.",
			"   For loader options: webpack 2 no longer allows custom properties in configuration.",
			"     Loaders should be updated to allow passing options via loader options in module.rules.",
			"     Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:",
			"     plugins: [",
			"       new webpack.LoaderOptionsPlugin({",
			"         // test: /\\.xxx$/, // may apply this only for some modules",
			"         options: {",
			"           postcss: ...",
			"         }",
			"       })",
			"     ]"
		]
	}, {
		name: "enum",
		config: {
			entry: "a",
			devtool: true
		},
		message: [
			" - configuration.devtool should be one of these:",
			"   string | false",
			"   -> A developer tool to enhance debugging.",
			"   Details:",
			"    * configuration.devtool should be a string.",
			"    * configuration.devtool should be false"
		]
	}, {
		name: "relative path",
		config: {
			entry: "foo.js",
			output: {
				filename: "/bar"
			}
		},
		message: [
			" - configuration.output.filename: A relative path is expected. However the provided value \"/bar\" is an absolute path!",
			"   -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.",
			"   Please use output.path to specify absolute path and output.filename for the file name."
		]
	}, {
		name: "absolute path",
		config: {
			entry: "foo.js",
			output: {
				filename: "bar"
			},
			context: "baz"
		},
		message: [
			" - configuration.context: The provided value \"baz\" is not an absolute path!",
			"   -> The base directory (absolute path!) for resolving the `entry` option. If `output.pathinfo` is set, the included pathinfo is shortened to this directory."
		]
	}, {
		name: "missing stats option",
		config: {
			entry: "foo.js",
			stats: {
				foobar: true
			}
		},
		test(err) {
			err.message.should.startWith("Invalid configuration object.");
			err.message.split("\n").slice(1)[0].should.be.eql(
				" - configuration.stats should be one of these:"
			);
		}
	}, {
		name: "Invalid plugin provided: bool",
		config: {
			entry: "foo.js",
			plugins: [
				false
			]
		},
		test(err) {
			err.message.should.startWith("Invalid configuration object.");
			err.message.split("\n").slice(1)[0].should.be.eql(
				" - configuration.plugins[0] should be one of these:"
			);
		}
	}, {
		name: "Invalid plugin provided: array",
		config: {
			entry: "foo.js",
			plugins: [
				[]
			]
		},
		test(err) {
			err.message.should.startWith("Invalid configuration object.");
			err.message.split("\n").slice(1)[0].should.be.eql(
				" - configuration.plugins[0] should be one of these:"
			);
		}
	}, {
		name: "Invalid plugin provided: string",
		config: {
			entry: "foo.js",
			plugins: ["abc123"]
		},
		test(err) {
			err.message.should.startWith("Invalid configuration object.");
			err.message.split("\n").slice(1)[0].should.be.eql(
				" - configuration.plugins[0] should be one of these:"
			);
		}
	}, {
		name: "Invalid plugin provided: int",
		config: {
			entry: "foo.js",
			plugins: [
				12
			]
		},
		test(err) {
			err.message.should.startWith("Invalid configuration object.");
			err.message.split("\n").slice(1)[0].should.be.eql(
				" - configuration.plugins[0] should be one of these:"
			);
		}
	}, {
		name: "Invalid plugin provided: object without apply function",
		config: {
			entry: "foo.js",
			plugins: [
				new function() {}
			]
		},
		test(err) {
			err.message.should.startWith("Invalid configuration object.");
			err.message.split("\n").slice(1)[0].should.be.eql(
				" - configuration.plugins[0] should be one of these:"
			);
		}
	}];

	testCases.forEach((testCase) => {
		it("should fail validation for " + testCase.name, () => {
			try {
				webpack(testCase.config);
			} catch(err) {
				if(err.name !== 'WebpackOptionsValidationError') throw err;

				if(testCase.test) {
					testCase.test(err);

					return;
				}

				err.message.should.startWith("Invalid configuration object.");
				err.message.split("\n").slice(1).should.be.eql(testCase.message);

				return;
			}

			throw new Error("Validation didn't fail");
		});
	});
});
<commit_msg>Add options.plugins schema validatio: Move away from error parsing to comparing the whole message<commit_after>/* globals describe, it */
"use strict";

require("should");

const webpack = require("../lib/webpack");

describe("Validation", () => {
	const testCases = [{
		name: "undefined configuration",
		config: undefined,
		message: [
			" - configuration should be an object."
		]
	}, {
		name: "null configuration",
		config: null,
		message: [
			" - configuration should be an object."
		]
	}, {
		name: "empty configuration",
		config: {},
		message: [
			" - configuration misses the property 'entry'.",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation."
		]
	}, {
		name: "empty entry string",
		config: {
			entry: ""
		},
		message: [
			" - configuration.entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration.entry should be an object.",
			"      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
			"    * configuration.entry should not be empty.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry should be an array:",
			"      [non-empty string]",
			"    * configuration.entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things."
		]
	}, {
		name: "empty entry bundle array",
		config: {
			entry: {
				"bundle": []
			}
		},
		message: [
			" - configuration.entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration.entry['bundle'] should be a string.",
			"      -> The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry['bundle'] should not be empty.",
			"    * configuration.entry should be a string.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry should be an array:",
			"      [non-empty string]",
			"    * configuration.entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things."
		]
	}, {
		name: "invalid instanceof",
		config: {
			entry: "a",
			module: {
				wrappedContextRegExp: 1337
			}
		},
		message: [
			" - configuration.module.wrappedContextRegExp should be an instance of RegExp",
			"   -> Set the inner regular expression for partial dynamic dependencies"
		]
	}, {
		name: "invalid minimum",
		config: {
			entry: "a",
			parallelism: 0
		},
		message: [
			" - configuration.parallelism should be >= 1.",
			"   -> The number of parallel processed modules in the compilation."
		]
	}, {
		name: "repeated value",
		config: {
			entry: ["abc", "def", "abc"]
		},
		message: [
			" - configuration.entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration.entry should be an object.",
			"      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
			"    * configuration.entry should be a string.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry should not contain the item 'abc' twice.",
			"    * configuration.entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
		]
	}, {
		name: "multiple errors",
		config: {
			entry: [/a/],
			output: {
				filename: /a/
			}
		},
		message: [
			" - configuration.entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration.entry should be an object.",
			"      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
			"    * configuration.entry should be a string.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration.entry[0] should be a string.",
			"      -> A non-empty string",
			"    * configuration.entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
			" - configuration.output.filename should be a string.",
			"   -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files."
		]
	}, {
		name: "multiple configurations",
		config: [{
			entry: [/a/],
		}, {
			entry: "a",
			output: {
				filename: /a/
			}
		}],
		message: [
			" - configuration[0].entry should be one of these:",
			"   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function",
			"   -> The entry point(s) of the compilation.",
			"   Details:",
			"    * configuration[0].entry should be an object.",
			"      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
			"    * configuration[0].entry should be a string.",
			"      -> An entry point without name. The string is resolved to a module which is loaded upon startup.",
			"    * configuration[0].entry[0] should be a string.",
			"      -> A non-empty string",
			"    * configuration[0].entry should be an instance of function",
			"      -> A Function returning an entry object, an entry string, an entry array or a promise to these things.",
			" - configuration[1].output.filename should be a string.",
			"   -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files."
		]
	}, {
		name: "deep error",
		config: {
			entry: "a",
			module: {
				rules: [{
					oneOf: [{
						test: "/a",
						paser: {
							amd: false
						}
					}]
				}]
			}
		},
		message: [
			" - configuration.module.rules[0].oneOf[0] has an unknown property 'paser'. These properties are valid:",
			"   object { enforce?, exclude?, include?, issuer?, loader?, loaders?, oneOf?, options?, parser?, query?, resource?, resourceQuery?, compiler?, rules?, test?, use? }",
			"   -> A rule"
		]
	}, {
		name: "additional key on root",
		config: {
			entry: "a",
			postcss: () => {}
		},
		message: [
			" - configuration has an unknown property 'postcss'. These properties are valid:",
			"   object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, " +
			"loader?, module?, name?, node?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, " +
			"recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }",
			"   For typos: please correct them.",
			"   For loader options: webpack 2 no longer allows custom properties in configuration.",
			"     Loaders should be updated to allow passing options via loader options in module.rules.",
			"     Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:",
			"     plugins: [",
			"       new webpack.LoaderOptionsPlugin({",
			"         // test: /\\.xxx$/, // may apply this only for some modules",
			"         options: {",
			"           postcss: ...",
			"         }",
			"       })",
			"     ]"
		]
	}, {
		name: "enum",
		config: {
			entry: "a",
			devtool: true
		},
		message: [
			" - configuration.devtool should be one of these:",
			"   string | false",
			"   -> A developer tool to enhance debugging.",
			"   Details:",
			"    * configuration.devtool should be a string.",
			"    * configuration.devtool should be false"
		]
	}, {
		name: "relative path",
		config: {
			entry: "foo.js",
			output: {
				filename: "/bar"
			}
		},
		message: [
			" - configuration.output.filename: A relative path is expected. However the provided value \"/bar\" is an absolute path!",
			"   -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.",
			"   Please use output.path to specify absolute path and output.filename for the file name."
		]
	}, {
		name: "absolute path",
		config: {
			entry: "foo.js",
			output: {
				filename: "bar"
			},
			context: "baz"
		},
		message: [
			" - configuration.context: The provided value \"baz\" is not an absolute path!",
			"   -> The base directory (absolute path!) for resolving the `entry` option. If `output.pathinfo` is set, the included pathinfo is shortened to this directory."
		]
	}, {
		name: "missing stats option",
		config: {
			entry: "foo.js",
			stats: {
				foobar: true
			}
		},
		test(err) {
			err.message.should.startWith("Invalid configuration object.");
			err.message.split("\n").slice(1)[0].should.be.eql(
				" - configuration.stats should be one of these:"
			);
		}
	}, {
		name: "Invalid plugin provided: bool",
		config: {
			entry: "foo.js",
			plugins: [
				false
			]
		},
		message: [
			" - configuration.plugins[0] should be one of these:",
			"   object { apply, ... } | function",
			"   -> Plugin of type object or instanceof Function",
			"   Details:",
			"    * configuration.plugins[0] should be an object.",
			"      -> Compiler or Resolver Plugin instance of Function",
			"    * configuration.plugins[0] should be an instance of function",
			"      -> Compiler or Resolver Plugin instance of Function"
		]
	}, {
		name: "Invalid plugin provided: array",
		config: {
			entry: "foo.js",
			plugins: [
				[]
			]
		},
		message: [
			" - configuration.plugins[0] should be one of these:",
			"   object { apply, ... } | function",
			"   -> Plugin of type object or instanceof Function",
			"   Details:",
			"    * configuration.plugins[0] should be an object.",
			"      -> Compiler or Resolver Plugin instance of Function",
			"    * configuration.plugins[0] should be an instance of function",
			"      -> Compiler or Resolver Plugin instance of Function"
		]
	}, {
		name: "Invalid plugin provided: string",
		config: {
			entry: "foo.js",
			plugins: ["abc123"]
		},
		message: [
			" - configuration.plugins[0] should be one of these:",
			"   object { apply, ... } | function",
			"   -> Plugin of type object or instanceof Function",
			"   Details:",
			"    * configuration.plugins[0] should be an object.",
			"      -> Compiler or Resolver Plugin instance of Function",
			"    * configuration.plugins[0] should be an instance of function",
			"      -> Compiler or Resolver Plugin instance of Function"
		]
	}, {
		name: "Invalid plugin provided: int",
		config: {
			entry: "foo.js",
			plugins: [
				12
			]
		},
		message: [
			" - configuration.plugins[0] should be one of these:",
			"   object { apply, ... } | function",
			"   -> Plugin of type object or instanceof Function",
			"   Details:",
			"    * configuration.plugins[0] should be an object.",
			"      -> Compiler or Resolver Plugin instance of Function",
			"    * configuration.plugins[0] should be an instance of function",
			"      -> Compiler or Resolver Plugin instance of Function"
		]
	}, {
		name: "Invalid plugin provided: object without apply function",
		config: {
			entry: "foo.js",
			plugins: [
				new function() {}
			]
		},
		message: [
			" - configuration.plugins[0] should be one of these:",
			"   object { apply, ... } | function",
			"   -> Plugin of type object or instanceof Function",
			"   Details:",
			"    * configuration.plugins[0] misses the property 'apply'.",
			"      function",
			"      -> The run point of the plugin, required method.",
			"    * configuration.plugins[0] misses the property 'apply'.",
			"      function",
			"      -> The run point of the plugin, required method.",
			"    * configuration.plugins[0] should be an instance of function",
			"      -> Compiler or Resolver Plugin instance of Function"
		]
	}];

	testCases.forEach((testCase) => {
		it("should fail validation for " + testCase.name, () => {
			try {
				webpack(testCase.config);
			} catch(err) {
				if(err.name !== 'WebpackOptionsValidationError') throw err;

				if(testCase.test) {
					testCase.test(err);

					return;
				}

				err.message.should.startWith("Invalid configuration object.");
				err.message.split("\n").slice(1).should.be.eql(testCase.message);

				return;
			}

			throw new Error("Validation didn't fail");
		});
	});
});
<|endoftext|>


<commit_before>(function(){

    angular.module('foodGenerator')
        .factory("authInterceptor", authInterceptor);

    function authInterceptor(BASEURL, auth) {

        function req(config){
            // automatically attach Authorization header
            if(config.url.indexOf(BASEURL) === 0 && auth.isAuthed()) {
                var token = auth.getToken();
                config.headers.Authorization = 'JWT ' + token;
            }

            return config;

        }

        function res(res){

            // If a token was sent back, save it
            if(res && res.config.url.indexOf(BASEURL) === 0 && res.data.token) {
                auth.saveToken(res.data.token);
            }

            return res;

        }

        return {
            request: req,
            response: res
        };
    }

})();<commit_msg>added debugging output<commit_after>(function(){

    angular.module('foodGenerator')
        .factory("authInterceptor", authInterceptor);

    function authInterceptor(BASEURL, auth) {

        function req(config){
            // automatically attach Authorization header
            if(config.url.indexOf(BASEURL) === 0 && auth.isAuthed()) {
                var token = auth.getToken();
                console.log("Adding an auth token: " + token);
                config.headers.Authorization = 'JWT ' + token;
            }

            return config;

        }

        function res(res){

            // If a token was sent back, save it
            if(res && res.config.url.indexOf(BASEURL) === 0 && res.data.token) {
                auth.saveToken(res.data.token);
                console.log("Received an auth token: " + res.data.token);
            }

            return res;

        }

        return {
            request: req,
            response: res
        };
    }

})();<|endoftext|>


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

var Checker = require('jscs/lib/checker');
var assert = require('assert');

describe('rules/require-dictionary-words', function() {
    var checker;

    beforeEach(function() {
        checker = new Checker();
        checker.registerDefaultRules();
        checker.configure({ plugins: [plugin] });
    });

    describe('true', function() {
        beforeEach(function() {
            checker.configure({ requireDictionaryWords: true });
        });

        it('should report non-words', function() {
            assert(checker.checkString('asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('var asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('let asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('const asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('function asdf(jkl) {var asdf = 1;}').getErrorCount() === 3);
            assert(checker.checkString('var asdf = function asdf() {};').getErrorCount() === 2);
            assert(checker.checkString('for(asdf = 0; asdf<1; asdf++){asdf;}').getErrorCount() === 1);
            assert(checker.checkString('object["jkl"] = 1;').getErrorCount() === 1);
            assert(checker.checkString('object.jkl = 1;').getErrorCount() === 1);
            assert(checker.checkString('object = {jkl: 1};').getErrorCount() === 1);
            assert(checker.checkString('object = {"jkl": 1};').getErrorCount() === 1);
            assert(checker.checkString('asdf: void 0;').getErrorCount() === 1);

            assert(checker.checkString('JKL = 1;').getErrorCount() === 1);
        });

        it('should report multiple non-words', function() {
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdfASDF = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdfASDFAsdf = 1;').getErrorCount() === 3);
            assert(checker.checkString('asdf_asdf = 1;').getErrorCount() === 2);
        });

        it('should ignore numbers and symbols', function() {
            assert(checker.checkString('$asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdf$Asdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdfAsdf$ = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdf9Asdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdfAsdf9 = 1;').getErrorCount() === 2);
        });

        it('should not report non-"instantiation" usages', function() {
            assert(checker.checkString('asdf').isEmpty());
            assert(checker.checkString('asdf.jkl').isEmpty());
            assert(checker.checkString('asdf(jkl)').isEmpty());
            assert(checker.checkString('asdf.jkl(jkl)').isEmpty());
            assert(checker.checkString('value = asdf').isEmpty());
            assert(checker.checkString('var value = asdf').isEmpty());
            assert(checker.checkString('object.property = asdf').isEmpty());
            assert(checker.checkString('if(asdf){}').isEmpty());
            assert(checker.checkString('object[jkl] = 1;').isEmpty());
        });

        it('should not report defined words', function() {
            assert(checker.checkString('good = 1;').isEmpty());
        });

        it('should not report multiple defined words', function() {
            assert(checker.checkString('goodGood = 1;').isEmpty());
        });
    });

    describe('esnext', function() {
        beforeEach(function() {
            checker.configure({ requireDictionaryWords: true, esnext: true });
        });

        it('should report non-words in es6', function() {
            assert(checker.checkString('object = {asdf, jkl() {}, [0 + 1]: 2};').getErrorCount() === 2);
            assert(checker.checkString('class Asdf { jkl() {} }').getErrorCount() === 2);
        });

        it('should not report defined words in es6', function() {
            assert(checker.checkString('object = {good, good() {}, [0 + 1]: 2};').isEmpty());
            assert(checker.checkString('class Good { good() {} }').isEmpty());
        });
    });

    describe('allowWords', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowWords: ['asdf', 'jkl']
                }
            });
        });

        it('should not report allowed words', function() {
            assert(checker.checkString('asdf = 1;').isEmpty());
            assert(checker.checkString('object.jkl = 1;').isEmpty());
            assert(checker.checkString('asdfAsdf = 1;').isEmpty());
            assert(checker.checkString('object.jklJkl = 1;').isEmpty());
        });
    });

    describe('allowNames', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowNames: ['asdf', 'jkl']
                }
            });
        });

        it('should report names used as parts of names', function() {
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('object.jklJkl = 1;').getErrorCount() === 2);
        });

        it('should not report allowed names', function() {
            assert(checker.checkString('asdf = 1;').isEmpty());
            assert(checker.checkString('object.jkl = 1;').isEmpty());
        });
    });

    describe('allowWordsInIdentifiers', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowWordsInIdentifiers: ['asdf', 'jkl']
                }
            });
        });

        it('should report non-words in properties', function() {
            assert(checker.checkString('object.jkl = 1;').getErrorCount() === 1);
            assert(checker.checkString('object.jklJkl = 1;').getErrorCount() === 2);
        });

        it('should not report allowed words in identifiers', function() {
            assert(checker.checkString('asdf = 1;').isEmpty());
            assert(checker.checkString('asdfAsdf = 1;').isEmpty());
        });
    });

    describe('allowWordsInProperties', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowWordsInProperties: ['asdf', 'jkl']
                }
            });
        });

        it('should report non-words in identifiers', function() {
            assert(checker.checkString('asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
        });

        it('should not report allowed words in properties', function() {
            assert(checker.checkString('object.jkl = 1;').isEmpty());
            assert(checker.checkString('object.jklJkl = 1;').isEmpty());
        });
    });

    describe('allowNamesAsIdentifiers', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowNamesAsIdentifiers: ['asdf', 'jkl']
                }
            });
        });

        it('should report non-names and properties', function() {
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('object.jkl = 1;').getErrorCount() === 1);
            assert(checker.checkString('object.jklJkl = 1;').getErrorCount() === 2);
        });

        it('should not report allowed names as identifiers', function() {
            assert(checker.checkString('asdf = 1;').isEmpty());
        });
    });

    describe('allowNamesAsProperties', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowNamesAsProperties: ['asdf', 'jkl']
                }
            });
        });

        it('should report non-names and identifiers', function() {
            assert(checker.checkString('asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('object.jklJkl = 1;').getErrorCount() === 2);
        });

        it('should not report allowed names as properties', function() {
            assert(checker.checkString('object.jkl = 1;').isEmpty());
        });
    });

    describe('excludeWords', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    excludeWords: ['good']
                }
            });
        });

        it('should report excluded words', function() {
            assert(checker.checkString('good = 1;').getErrorCount() === 1);
            assert(checker.checkString('object.good = 1;').getErrorCount() === 1);
        });
    });

    describe('dictionaries', function() {
        describe('english', function() {
            beforeEach(function() {
                checker.configure({
                    requireDictionaryWords: {
                        dictionaries: ['english']
                    }
                });
            });

            it('should report non-words', function() {
                assert(checker.checkString('color = 1;').getErrorCount() === 1);
            });
        });

        describe('english, american', function() {
            beforeEach(function() {
                checker.configure({
                    requireDictionaryWords: {
                        dictionaries: ['english', 'english/american']
                    }
                });
            });

            it('should not report defined words', function() {
                assert(checker.checkString('color = 1;').isEmpty());
            });
        });

        describe('missing dictionary', function() {
            it('should throw an informative error', function() {
                var missingLanguage = 'elvish';
                assert.throws(function() {
                    checker.configure({
                        requireDictionaryWords: {
                            dictionaries: [missingLanguage]
                        }
                    });
                }, new RegExp('wordlist-' + missingLanguage));
            });
        });
    });

    describe('inline configuration', function() {
        beforeEach(function() {
            checker.configure({ requireDictionaryWords: true });
        });

        it('should split', function() {
            assert(checker.checkString([
                '// jscs:allowWords',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).getErrorCount() === 2);
            assert(checker.checkString([
                '// jscs:allowWords asdf',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).getErrorCount() === 1);
            assert(checker.checkString([
                '// jscs:allowWords asdf, jkl',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowWords asdf, jkl,',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '/* jscs:allowWords',
                ' asdf, jkl */',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '/* jscs:allowWords',
                ' asdf,',
                ' jkl */',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).isEmpty());
        });

        it('should later allow and later disallow inline', function() {
            assert(checker.checkString([
                'asdf = 1',
                '// jscs:allowWords asdf, jkl',
                'asdf = 1',
                '// jscs:disallowWords asdf, jkl',
                'asdf = 1'
            ].join('\n')).getErrorCount() === 2);

            assert(checker.checkString([
                'asdf = 1',
                'jkl = 1',
                '// jscs:allowWords asdf, jkl',
                'asdf = 1',
                'jkl = 1',
                '// jscs:disallowWords asdf, jkl',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).getErrorCount() === 4);
        });

        it('should allow words inline', function() {
            assert(checker.checkString([
                '// jscs:allowWords asdf, jkl',
                'asdf = 1',
                'asdfAsdf = 1',
                'object.jkl = 1',
                'object.jklJkl = 1'
            ].join('\n')).isEmpty());
        });

        it('should allow words in identifiers inline', function() {
            assert(checker.checkString([
                '// jscs:allowWordsInIdentifiers asdf, jkl',
                'asdf = 1',
                'asdfAsdf = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowWordsInIdentifiers asdf, jkl',
                'object.jkl = 1',
                'object.jklJkl = 1'
            ].join('\n')).getErrorCount() === 3);
        });

        it('should allow words in properties inline', function() {
            assert(checker.checkString([
                '// jscs:allowWordsInProperties asdf, jkl',
                'object.jkl = 1',
                'object.jklJkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowWordsInProperties asdf, jkl',
                'asdf = 1',
                'asdfAsdf = 1'
            ].join('\n')).getErrorCount() === 3);
        });

        it('should allow names inline', function() {
            assert(checker.checkString([
                '// jscs:allowNames asdf, jkl',
                'asdf = 1',
                'object.jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowNames asdf, jkl',
                'asdfAsdf = 1',
                'object.jklJkl = 1'
            ].join('\n')).getErrorCount() === 4);
        });

        it('should allow names as identifiers inline', function() {
            assert(checker.checkString([
                '// jscs:allowNamesAsIdentifiers asdf, jkl',
                'asdf = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowNamesAsIdentifiers asdf, jkl',
                'asdfAsdf = 1',
                'object.jkl = 1',
                'object.jklJkl = 1'
            ].join('\n')).getErrorCount() === 5);
        });

        it('should allow names as properties inline', function() {
            assert(checker.checkString([
                '// jscs:allowNamesAsProperties asdf, jkl',
                'object.jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowNamesAsProperties asdf, jkl',
                'asdf = 1',
                'asdfAsdf = 1',
                'object.jklJkl = 1'
            ].join('\n')).getErrorCount() === 5);
        });
    });
});
<commit_msg>requireDictionaryWords: Add test for newable plugin<commit_after>var plugin = require('../../..');

var Checker = require('jscs/lib/checker');
var assert = require('assert');

describe('plugin', function() {
    var called = false;
    plugin({
        registerRule: function(Rule) {
            var rule = new Rule();
            assert(typeof rule.configure === 'function');
            assert(typeof rule.getOptionName === 'function');
            assert(typeof rule.check === 'function');
            called = true;
        }
    });
    assert(called);
});

describe('rules/require-dictionary-words', function() {
    var checker;

    beforeEach(function() {
        checker = new Checker();
        checker.registerDefaultRules();
        checker.configure({ plugins: [plugin] });
    });

    describe('true', function() {
        beforeEach(function() {
            checker.configure({ requireDictionaryWords: true });
        });

        it('should report non-words', function() {
            assert(checker.checkString('asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('var asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('let asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('const asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('function asdf(jkl) {var asdf = 1;}').getErrorCount() === 3);
            assert(checker.checkString('var asdf = function asdf() {};').getErrorCount() === 2);
            assert(checker.checkString('for(asdf = 0; asdf<1; asdf++){asdf;}').getErrorCount() === 1);
            assert(checker.checkString('object["jkl"] = 1;').getErrorCount() === 1);
            assert(checker.checkString('object.jkl = 1;').getErrorCount() === 1);
            assert(checker.checkString('object = {jkl: 1};').getErrorCount() === 1);
            assert(checker.checkString('object = {"jkl": 1};').getErrorCount() === 1);
            assert(checker.checkString('asdf: void 0;').getErrorCount() === 1);

            assert(checker.checkString('JKL = 1;').getErrorCount() === 1);
        });

        it('should report multiple non-words', function() {
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdfASDF = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdfASDFAsdf = 1;').getErrorCount() === 3);
            assert(checker.checkString('asdf_asdf = 1;').getErrorCount() === 2);
        });

        it('should ignore numbers and symbols', function() {
            assert(checker.checkString('$asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdf$Asdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdfAsdf$ = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdf9Asdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('asdfAsdf9 = 1;').getErrorCount() === 2);
        });

        it('should not report non-"instantiation" usages', function() {
            assert(checker.checkString('asdf').isEmpty());
            assert(checker.checkString('asdf.jkl').isEmpty());
            assert(checker.checkString('asdf(jkl)').isEmpty());
            assert(checker.checkString('asdf.jkl(jkl)').isEmpty());
            assert(checker.checkString('value = asdf').isEmpty());
            assert(checker.checkString('var value = asdf').isEmpty());
            assert(checker.checkString('object.property = asdf').isEmpty());
            assert(checker.checkString('if(asdf){}').isEmpty());
            assert(checker.checkString('object[jkl] = 1;').isEmpty());
        });

        it('should not report defined words', function() {
            assert(checker.checkString('good = 1;').isEmpty());
        });

        it('should not report multiple defined words', function() {
            assert(checker.checkString('goodGood = 1;').isEmpty());
        });
    });

    describe('esnext', function() {
        beforeEach(function() {
            checker.configure({ requireDictionaryWords: true, esnext: true });
        });

        it('should report non-words in es6', function() {
            assert(checker.checkString('object = {asdf, jkl() {}, [0 + 1]: 2};').getErrorCount() === 2);
            assert(checker.checkString('class Asdf { jkl() {} }').getErrorCount() === 2);
        });

        it('should not report defined words in es6', function() {
            assert(checker.checkString('object = {good, good() {}, [0 + 1]: 2};').isEmpty());
            assert(checker.checkString('class Good { good() {} }').isEmpty());
        });
    });

    describe('allowWords', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowWords: ['asdf', 'jkl']
                }
            });
        });

        it('should not report allowed words', function() {
            assert(checker.checkString('asdf = 1;').isEmpty());
            assert(checker.checkString('object.jkl = 1;').isEmpty());
            assert(checker.checkString('asdfAsdf = 1;').isEmpty());
            assert(checker.checkString('object.jklJkl = 1;').isEmpty());
        });
    });

    describe('allowNames', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowNames: ['asdf', 'jkl']
                }
            });
        });

        it('should report names used as parts of names', function() {
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('object.jklJkl = 1;').getErrorCount() === 2);
        });

        it('should not report allowed names', function() {
            assert(checker.checkString('asdf = 1;').isEmpty());
            assert(checker.checkString('object.jkl = 1;').isEmpty());
        });
    });

    describe('allowWordsInIdentifiers', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowWordsInIdentifiers: ['asdf', 'jkl']
                }
            });
        });

        it('should report non-words in properties', function() {
            assert(checker.checkString('object.jkl = 1;').getErrorCount() === 1);
            assert(checker.checkString('object.jklJkl = 1;').getErrorCount() === 2);
        });

        it('should not report allowed words in identifiers', function() {
            assert(checker.checkString('asdf = 1;').isEmpty());
            assert(checker.checkString('asdfAsdf = 1;').isEmpty());
        });
    });

    describe('allowWordsInProperties', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowWordsInProperties: ['asdf', 'jkl']
                }
            });
        });

        it('should report non-words in identifiers', function() {
            assert(checker.checkString('asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
        });

        it('should not report allowed words in properties', function() {
            assert(checker.checkString('object.jkl = 1;').isEmpty());
            assert(checker.checkString('object.jklJkl = 1;').isEmpty());
        });
    });

    describe('allowNamesAsIdentifiers', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowNamesAsIdentifiers: ['asdf', 'jkl']
                }
            });
        });

        it('should report non-names and properties', function() {
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('object.jkl = 1;').getErrorCount() === 1);
            assert(checker.checkString('object.jklJkl = 1;').getErrorCount() === 2);
        });

        it('should not report allowed names as identifiers', function() {
            assert(checker.checkString('asdf = 1;').isEmpty());
        });
    });

    describe('allowNamesAsProperties', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    allowNamesAsProperties: ['asdf', 'jkl']
                }
            });
        });

        it('should report non-names and identifiers', function() {
            assert(checker.checkString('asdf = 1;').getErrorCount() === 1);
            assert(checker.checkString('asdfAsdf = 1;').getErrorCount() === 2);
            assert(checker.checkString('object.jklJkl = 1;').getErrorCount() === 2);
        });

        it('should not report allowed names as properties', function() {
            assert(checker.checkString('object.jkl = 1;').isEmpty());
        });
    });

    describe('excludeWords', function() {
        beforeEach(function() {
            checker.configure({
                requireDictionaryWords: {
                    excludeWords: ['good']
                }
            });
        });

        it('should report excluded words', function() {
            assert(checker.checkString('good = 1;').getErrorCount() === 1);
            assert(checker.checkString('object.good = 1;').getErrorCount() === 1);
        });
    });

    describe('dictionaries', function() {
        describe('english', function() {
            beforeEach(function() {
                checker.configure({
                    requireDictionaryWords: {
                        dictionaries: ['english']
                    }
                });
            });

            it('should report non-words', function() {
                assert(checker.checkString('color = 1;').getErrorCount() === 1);
            });
        });

        describe('english, american', function() {
            beforeEach(function() {
                checker.configure({
                    requireDictionaryWords: {
                        dictionaries: ['english', 'english/american']
                    }
                });
            });

            it('should not report defined words', function() {
                assert(checker.checkString('color = 1;').isEmpty());
            });
        });

        describe('missing dictionary', function() {
            it('should throw an informative error', function() {
                var missingLanguage = 'elvish';
                assert.throws(function() {
                    checker.configure({
                        requireDictionaryWords: {
                            dictionaries: [missingLanguage]
                        }
                    });
                }, new RegExp('wordlist-' + missingLanguage));
            });
        });
    });

    describe('inline configuration', function() {
        beforeEach(function() {
            checker.configure({ requireDictionaryWords: true });
        });

        it('should split', function() {
            assert(checker.checkString([
                '// jscs:allowWords',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).getErrorCount() === 2);
            assert(checker.checkString([
                '// jscs:allowWords asdf',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).getErrorCount() === 1);
            assert(checker.checkString([
                '// jscs:allowWords asdf, jkl',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowWords asdf, jkl,',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '/* jscs:allowWords',
                ' asdf, jkl */',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '/* jscs:allowWords',
                ' asdf,',
                ' jkl */',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).isEmpty());
        });

        it('should later allow and later disallow inline', function() {
            assert(checker.checkString([
                'asdf = 1',
                '// jscs:allowWords asdf, jkl',
                'asdf = 1',
                '// jscs:disallowWords asdf, jkl',
                'asdf = 1'
            ].join('\n')).getErrorCount() === 2);

            assert(checker.checkString([
                'asdf = 1',
                'jkl = 1',
                '// jscs:allowWords asdf, jkl',
                'asdf = 1',
                'jkl = 1',
                '// jscs:disallowWords asdf, jkl',
                'asdf = 1',
                'jkl = 1'
            ].join('\n')).getErrorCount() === 4);
        });

        it('should allow words inline', function() {
            assert(checker.checkString([
                '// jscs:allowWords asdf, jkl',
                'asdf = 1',
                'asdfAsdf = 1',
                'object.jkl = 1',
                'object.jklJkl = 1'
            ].join('\n')).isEmpty());
        });

        it('should allow words in identifiers inline', function() {
            assert(checker.checkString([
                '// jscs:allowWordsInIdentifiers asdf, jkl',
                'asdf = 1',
                'asdfAsdf = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowWordsInIdentifiers asdf, jkl',
                'object.jkl = 1',
                'object.jklJkl = 1'
            ].join('\n')).getErrorCount() === 3);
        });

        it('should allow words in properties inline', function() {
            assert(checker.checkString([
                '// jscs:allowWordsInProperties asdf, jkl',
                'object.jkl = 1',
                'object.jklJkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowWordsInProperties asdf, jkl',
                'asdf = 1',
                'asdfAsdf = 1'
            ].join('\n')).getErrorCount() === 3);
        });

        it('should allow names inline', function() {
            assert(checker.checkString([
                '// jscs:allowNames asdf, jkl',
                'asdf = 1',
                'object.jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowNames asdf, jkl',
                'asdfAsdf = 1',
                'object.jklJkl = 1'
            ].join('\n')).getErrorCount() === 4);
        });

        it('should allow names as identifiers inline', function() {
            assert(checker.checkString([
                '// jscs:allowNamesAsIdentifiers asdf, jkl',
                'asdf = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowNamesAsIdentifiers asdf, jkl',
                'asdfAsdf = 1',
                'object.jkl = 1',
                'object.jklJkl = 1'
            ].join('\n')).getErrorCount() === 5);
        });

        it('should allow names as properties inline', function() {
            assert(checker.checkString([
                '// jscs:allowNamesAsProperties asdf, jkl',
                'object.jkl = 1'
            ].join('\n')).isEmpty());
            assert(checker.checkString([
                '// jscs:allowNamesAsProperties asdf, jkl',
                'asdf = 1',
                'asdfAsdf = 1',
                'object.jklJkl = 1'
            ].join('\n')).getErrorCount() === 5);
        });
    });
});
<|endoftext|>


<commit_before>var Class = require('../../utils/Class');
var BaseSoundManager = require('../BaseSoundManager');
var HTML5AudioSound = require('./HTML5AudioSound');
var HTML5AudioSoundManager = new Class({
    Extends: BaseSoundManager,
    initialize: function HTML5AudioSoundManager(game) {
        /**
         * Flag indicating whether if there are no idle instances of HTML5 Audio tag,
         * for any particular sound, if one of the used tags should be stopped and used
         * for succeeding playback or if succeeding Phaser.Sound.HTML5AudioSound#play
         * call should be ignored.
         *
         * @property {boolean} override
         * @default true
         */
        this.override = true;
        /**
         * Value representing time difference in seconds between calling
         * play method on an audio tag and when it actually starts playing.
         * It is used to achieve more accurate delayed sound playback.
         *
         * You might need to tweak this value to get the desired results
         * since audio play delay varies depending on the browser/platform.
         *
         * @property {number} audioPlayDelay
         * @default 0.1
         */
        this.audioPlayDelay = 0.1;
        /**
         * A value by which we should offset the loop end marker of the looping sound to compensate
         * for lag, caused by changing audio tag position, in order to achieve gapless looping.
         *
         * You might need to tweak this value to get the desired results
         * since loop lag varies depending on the browser/platform.
         *
         * @property {number} loopEndOffset
         * @default 0.05
         */
        this.loopEndOffset = 0.05;
        /**
         * An array for keeping track of all the sounds
         * that were paused when game lost focus.
         *
         * @private
         * @property {Phaser.Sound.HTML5AudioSound[]} onBlurPausedSounds
         * @default []
         */
        this.onBlurPausedSounds = [];
        /**
         * HTML5 Audio streams cannot be loaded unless triggered by explicit user interaction, such as a tap.
         * True if the audio system is currently locked awaiting user interaction.
         *
         * @private
         * @property {boolean} touchLocked
         */
        this.touchLocked = 'ontouchstart' in window;
        /**
         * Flag used for indicating when the audio has been unlocked,
         * if there ever was a need for it.
         *
         * @private
         * @type {boolean}
         * @default false
         */
        this.touchUnlocked = false;
        /**
         * Property that actually holds the value of global mute
         * for HTML5 Audio sound manager implementation.
         *
         * @private
         * @property {boolean} _mute
         * @default false
         */
        this._mute = false;
        /**
         * Property that actually holds the value of global volume
         * for HTML5 Audio sound manager implementation.
         *
         * @private
         * @property {boolean} _volume
         * @default 1
         */
        this._volume = 1;
        BaseSoundManager.call(this, game);
    },
    add: function (key, config) {
        var sound = new HTML5AudioSound(this, key, config);
        this.sounds.push(sound);
        return sound;
    },
    unlock: function () {
        var _this = this;
        if ('ontouchstart' in window) {
            var unlock_1 = function () {
                document.body.removeEventListener('touchend', unlock_1);
                _this.game.cache.audio.entries.each(function (key, tags) {
                    for (var i = 0; i < tags.length; i++) {
                        tags[i].load();
                    }
                    return true;
                });
                _this.forEachActiveSound(function (sound) {
                    sound.pause();
                    sound.resume();
                });
            };
            document.body.addEventListener('touchend', unlock_1, false);
        }
    },
    onBlur: function () {
        this.forEachActiveSound(function (sound) {
            if (sound.isPlaying) {
                this.onBlurPausedSounds.push(sound);
                sound.onBlur();
            }
        });
    },
    onFocus: function () {
        this.onBlurPausedSounds.forEach(function (sound) {
            sound.onFocus();
        });
        this.onBlurPausedSounds.length = 0;
    },
    destroy: function () {
        BaseSoundManager.prototype.destroy.call(this);
        this.onBlurPausedSounds.length = 0;
        this.onBlurPausedSounds = null;
    }
});
/**
 * Global mute setting.
 *
 * @name Phaser.Sound.HTML5AudioSoundManager#mute
 * @property {boolean} mute
 */
Object.defineProperty(HTML5AudioSoundManager.prototype, 'mute', {
    get: function () {
        return this._mute;
    },
    set: function (value) {
        this._mute = value;
        this.forEachActiveSound(function (sound) {
            sound.setMute();
        });
        this.emit('mute', this, value);
    }
});
/**
 * Global volume setting.
 *
 * @name Phaser.Sound.HTML5AudioSoundManager#volume
 * @property {number} volume
 */
Object.defineProperty(HTML5AudioSoundManager.prototype, 'volume', {
    get: function () {
        return this._volume;
    },
    set: function (value) {
        this._volume = value;
        this.forEachActiveSound(function (sound) {
            sound.setVolume();
        });
        this.emit('volume', this, value);
    }
});
module.exports = HTML5AudioSoundManager;
<commit_msg>Using touchLocked value as condition<commit_after>var Class = require('../../utils/Class');
var BaseSoundManager = require('../BaseSoundManager');
var HTML5AudioSound = require('./HTML5AudioSound');
var HTML5AudioSoundManager = new Class({
    Extends: BaseSoundManager,
    initialize: function HTML5AudioSoundManager(game) {
        /**
         * Flag indicating whether if there are no idle instances of HTML5 Audio tag,
         * for any particular sound, if one of the used tags should be stopped and used
         * for succeeding playback or if succeeding Phaser.Sound.HTML5AudioSound#play
         * call should be ignored.
         *
         * @property {boolean} override
         * @default true
         */
        this.override = true;
        /**
         * Value representing time difference in seconds between calling
         * play method on an audio tag and when it actually starts playing.
         * It is used to achieve more accurate delayed sound playback.
         *
         * You might need to tweak this value to get the desired results
         * since audio play delay varies depending on the browser/platform.
         *
         * @property {number} audioPlayDelay
         * @default 0.1
         */
        this.audioPlayDelay = 0.1;
        /**
         * A value by which we should offset the loop end marker of the looping sound to compensate
         * for lag, caused by changing audio tag position, in order to achieve gapless looping.
         *
         * You might need to tweak this value to get the desired results
         * since loop lag varies depending on the browser/platform.
         *
         * @property {number} loopEndOffset
         * @default 0.05
         */
        this.loopEndOffset = 0.05;
        /**
         * An array for keeping track of all the sounds
         * that were paused when game lost focus.
         *
         * @private
         * @property {Phaser.Sound.HTML5AudioSound[]} onBlurPausedSounds
         * @default []
         */
        this.onBlurPausedSounds = [];
        /**
         * HTML5 Audio streams cannot be loaded unless triggered by explicit user interaction, such as a tap.
         * True if the audio system is currently locked awaiting user interaction.
         *
         * @private
         * @property {boolean} touchLocked
         */
        this.touchLocked = 'ontouchstart' in window;
        /**
         * Flag used for indicating when the audio has been unlocked,
         * if there ever was a need for it.
         *
         * @private
         * @type {boolean}
         * @default false
         */
        this.touchUnlocked = false;
        /**
         * Property that actually holds the value of global mute
         * for HTML5 Audio sound manager implementation.
         *
         * @private
         * @property {boolean} _mute
         * @default false
         */
        this._mute = false;
        /**
         * Property that actually holds the value of global volume
         * for HTML5 Audio sound manager implementation.
         *
         * @private
         * @property {boolean} _volume
         * @default 1
         */
        this._volume = 1;
        BaseSoundManager.call(this, game);
    },
    add: function (key, config) {
        var sound = new HTML5AudioSound(this, key, config);
        this.sounds.push(sound);
        return sound;
    },
    unlock: function () {
        var _this = this;
        if (this.touchLocked) {
            var unlock_1 = function () {
                document.body.removeEventListener('touchend', unlock_1);
                _this.game.cache.audio.entries.each(function (key, tags) {
                    for (var i = 0; i < tags.length; i++) {
                        tags[i].load();
                    }
                    return true;
                });
                _this.forEachActiveSound(function (sound) {
                    sound.pause();
                    sound.resume();
                });
            };
            document.body.addEventListener('touchend', unlock_1, false);
        }
    },
    onBlur: function () {
        this.forEachActiveSound(function (sound) {
            if (sound.isPlaying) {
                this.onBlurPausedSounds.push(sound);
                sound.onBlur();
            }
        });
    },
    onFocus: function () {
        this.onBlurPausedSounds.forEach(function (sound) {
            sound.onFocus();
        });
        this.onBlurPausedSounds.length = 0;
    },
    destroy: function () {
        BaseSoundManager.prototype.destroy.call(this);
        this.onBlurPausedSounds.length = 0;
        this.onBlurPausedSounds = null;
    }
});
/**
 * Global mute setting.
 *
 * @name Phaser.Sound.HTML5AudioSoundManager#mute
 * @property {boolean} mute
 */
Object.defineProperty(HTML5AudioSoundManager.prototype, 'mute', {
    get: function () {
        return this._mute;
    },
    set: function (value) {
        this._mute = value;
        this.forEachActiveSound(function (sound) {
            sound.setMute();
        });
        this.emit('mute', this, value);
    }
});
/**
 * Global volume setting.
 *
 * @name Phaser.Sound.HTML5AudioSoundManager#volume
 * @property {number} volume
 */
Object.defineProperty(HTML5AudioSoundManager.prototype, 'volume', {
    get: function () {
        return this._volume;
    },
    set: function (value) {
        this._volume = value;
        this.forEachActiveSound(function (sound) {
            sound.setVolume();
        });
        this.emit('volume', this, value);
    }
});
module.exports = HTML5AudioSoundManager;
<|endoftext|>


<commit_before>;(function () {
	/* Lightweight EventEmitter implementation */
	var EventEmitter = function () {}
	EventEmitter.prototype._events = {}

	EventEmitter.prototype.on = function (evt, fn) {
		this._events[evt] = this._events[evt] || []
		this._events[evt].push(fn)
	}
	EventEmitter.prototype.off = function (evt, fn) {
		if (evt in this._events === false) return
		this._events[evt].splice(this._events[evt].indexOf(fn), 1)
	}
	EventEmitter.prototype.emit = function (evt) {
		if (evt in this._events === false) return

		for (var i = 0, l = this._events[evt].length; i < l; i++) {
			this._events[evt][i].apply(this, Array.prototype.slice.call(arguments, 1))
		}
	}

	/* Copy the stuff from Array to FileList */
	FileList.prototype.forEach = Array.prototype.forEach
	FileList.prototype.every = Array.prototype.every
	FileList.prototype.some = Array.prototype.some
	FileList.prototype.filter = Array.prototype.filter
	FileList.prototype.map = Array.prototype.map
	FileList.prototype.reduce = Array.prototype.reduce
	FileList.prototype.reduceRight = Array.prototype.reduceRight

	Object.defineProperty(FileList.prototype, "size", {
		get: function getSize () {
			return this.map(function(item) {
				return item.size
			}).reduce(function (prev, curr) {
				return prev + curr
			})
		}
	})

	/* Utility to convert bytes into human units */
	var humanSize = {
		get: function humanSize (size) {
			var units = ["B", "KiB", "MIB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
			var e = Math.floor(Math.log(this.size) / Math.log(1024))
			return (this.size / Math.pow(1024, e)).toFixed(2) + " " + units[e]
		}
	}
	Object.defineProperty(FileList.prototype, "humanSize", humanSize)
	Object.defineProperty(File.prototype, "humanSize", humanSize)

	Object.defineProperty(FileList.prototype, "uploadedSize", {
		get: function getUploadedSize () {
			return this.map(function(item) {
				return item.uploadedSize || 0
			}).reduce(function (prev, curr) {
				return prev + curr
			})
		}
	})

	/* Object URL stuff */
	Object.defineProperty(File.prototype, "url", {
		get: function getURL () {
			return window.URL.createObjectURL(this);
		}
	})
	File.revokeURL = function revokeURL (url) {
		window.URL.revokeObjectURL(url)
	}

	// b gets merged as defaults for a
	var defaults = function (a, b) {
		var out = {}
		for (var key in b) {
			out[key] = (a[key] === void 0) ? b[key] : a[key]
		}
		return out
	}

	var FileListUploader = function (url, files, opts) {
		this.url = url
		this.files = files

		opts = opts || {}

		this.opts = defaults(opts, {
			'field': 'files[]',
		   'method': 'POST'
		})
	}
	FileListUploader.prototype = Object.create(EventEmitter.prototype)
	FileListUploader.prototype.upload = function (cb) {
		if (cb) this.on('uploadcomplete', cb)

		var opts = this.opts
		var files = this.files
		var events = this

		var data = new FormData()
		files.forEach(function (file) {
			data.append(opts.field, file)
		})

		var xhr = new XMLHttpRequest()

		xhr.open(opts.method, this.url, true)
		xhr.upload.addEventListener('progress', function (e) {
			if (e.lengthComputable) {
				size = e.loaded
				// We know the size of the files, the order they're in, and how
				// much we've uploaded.  Based on this data, we can do some magic
				// to figure out which file we're on, and how much we've uploaded
				// of that file.
				// TODO: This math has trouble on later uploads.  Leak somewhere
				for (var i = 0, l = files.length; i < l; i++) {
					files[i].uploadedSize = Math.min(size, files[i].size)
					size -= files[i].uploadedSize
					if (size <= 0) {
						console.log((i+1) + '/' + l + ': ' + files[i].name + ': ' + humanSize(files[i].uploadedSize) + '/' + humanSize(files[i].size));
						files.current = files[i]
						size = 0
						break
					}
				}
			}
			events.emit('uploadprogress', e, files)
		}, false)
		xhr.upload.addEventListener('loadstart', function (e) { events.emit('uploadstart', e) })
		xhr.upload.addEventListener('load', function (e) { events.emit('uploadcomplete', e) })
		xhr.addEventListener('progress', function (e) { events.emit('progress', e) })
		xhr.addEventListener('load', function (e) { events.emit('load', e, xhr.responseText) })

		xhr.send(data)
		/* TODO: Add more event passthroughs, maybe abstract it into a helper? */
	}

	FileList.prototype.upload = function uploadFileList (url, opts) {
		return new FileListUploader(url, this, opts)
	}
})()
<commit_msg>Add percentUploaded<commit_after>;(function () {
	/* Lightweight EventEmitter implementation */
	var EventEmitter = function () {}
	EventEmitter.prototype._events = {}

	EventEmitter.prototype.on = function (evt, fn) {
		this._events[evt] = this._events[evt] || []
		this._events[evt].push(fn)
	}
	EventEmitter.prototype.off = function (evt, fn) {
		if (evt in this._events === false) return
		this._events[evt].splice(this._events[evt].indexOf(fn), 1)
	}
	EventEmitter.prototype.emit = function (evt) {
		if (evt in this._events === false) return

		for (var i = 0, l = this._events[evt].length; i < l; i++) {
			this._events[evt][i].apply(this, Array.prototype.slice.call(arguments, 1))
		}
	}

	/* Copy the stuff from Array to FileList */
	FileList.prototype.forEach = Array.prototype.forEach
	FileList.prototype.every = Array.prototype.every
	FileList.prototype.some = Array.prototype.some
	FileList.prototype.filter = Array.prototype.filter
	FileList.prototype.map = Array.prototype.map
	FileList.prototype.reduce = Array.prototype.reduce
	FileList.prototype.reduceRight = Array.prototype.reduceRight

	Object.defineProperty(FileList.prototype, "size", {
		get: function getSize () {
			return this.map(function(item) {
				return item.size
			}).reduce(function (prev, curr) {
				return prev + curr
			})
		}
	})

	/* Utility to convert bytes into human units */
	var humanSize = {
		get: function humanSize (size) {
			var units = ["B", "KiB", "MIB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
			var e = Math.floor(Math.log(this.size) / Math.log(1024))
			return (this.size / Math.pow(1024, e)).toFixed(2) + " " + units[e]
		}
	}
	Object.defineProperty(FileList.prototype, "humanSize", humanSize)
	Object.defineProperty(File.prototype, "humanSize", humanSize)

	var percentUploaded = {
		get: function percentUploaded () {
			return this.uploadedSize / this.size
		}
	}
	Object.defineProperty(FileList.prototype, "percentUploaded", percentUploaded)
	Object.defineProperty(File.prototype, "percentUploaded", percentUploaded)

	Object.defineProperty(FileList.prototype, "uploadedSize", {
		get: function getUploadedSize () {
			return this.map(function(item) {
				return item.uploadedSize || 0
			}).reduce(function (prev, curr) {
				return prev + curr
			})
		}
	})

	/* Object URL stuff */
	Object.defineProperty(File.prototype, "url", {
		get: function getURL () {
			return window.URL.createObjectURL(this);
		}
	})
	File.revokeURL = function revokeURL (url) {
		window.URL.revokeObjectURL(url)
	}

	// b gets merged as defaults for a
	var defaults = function (a, b) {
		var out = {}
		for (var key in b) {
			out[key] = (a[key] === void 0) ? b[key] : a[key]
		}
		return out
	}

	var FileListUploader = function (url, files, opts) {
		this.url = url
		this.files = files

		opts = opts || {}

		this.opts = defaults(opts, {
			'field': 'files[]',
		   'method': 'POST'
		})
	}
	FileListUploader.prototype = Object.create(EventEmitter.prototype)
	FileListUploader.prototype.upload = function (cb) {
		if (cb) this.on('uploadcomplete', cb)

		var opts = this.opts
		var files = this.files
		var events = this

		var data = new FormData()
		files.forEach(function (file) {
			data.append(opts.field, file)
		})

		var xhr = new XMLHttpRequest()

		xhr.open(opts.method, this.url, true)
		xhr.upload.addEventListener('progress', function (e) {
			if (e.lengthComputable) {
				size = e.loaded
				// We know the size of the files, the order they're in, and how
				// much we've uploaded.  Based on this data, we can do some magic
				// to figure out which file we're on, and how much we've uploaded
				// of that file.
				// TODO: This math has trouble on later uploads.  Leak somewhere
				for (var i = 0, l = files.length; i < l; i++) {
					files[i].uploadedSize = Math.min(size, files[i].size)
					size -= files[i].uploadedSize
					if (size <= 0) {
						console.log((i+1) + '/' + l + ': ' + files[i].name + ': ' + humanSize(files[i].uploadedSize) + '/' + humanSize(files[i].size));
						files.current = files[i]
						size = 0
						break
					}
				}
			}
			events.emit('uploadprogress', e, files)
		}, false)
		xhr.upload.addEventListener('loadstart', function (e) { events.emit('uploadstart', e) })
		xhr.upload.addEventListener('load', function (e) { events.emit('uploadcomplete', e) })
		xhr.addEventListener('progress', function (e) { events.emit('progress', e) })
		xhr.addEventListener('load', function (e) { events.emit('load', e, xhr.responseText) })

		xhr.send(data)
		/* TODO: Add more event passthroughs, maybe abstract it into a helper? */
	}

	FileList.prototype.upload = function uploadFileList (url, opts) {
		return new FileListUploader(url, this, opts)
	}
})()
<|endoftext|>


<commit_before>/**
 * PUSH Notification server
 * (c) Telefonica Digital, 2012 - All rights reserved
 * License: GNU Affero V3 (see LICENSE file)
 * Fernando Rodríguez Sela <frsela@tid.es>
 * Guillermo Lopez Leal <gll@tid.es>
 */

var hp = require("../../src/common/Helpers.js"),
    assert = require('assert'),
    vows = require('vows'),
    baseURL = require('../../src/config.js').consts.publicBaseURL;

vows.describe('Helper tests').addBatch({
  "getNotificationURL": function() {
    var token = Date.now();
    var url = hp.getNotificationURL(token);
    assert.isString(url);
    assert.equal(url, baseURL + '/notify/' + token);
  },
  "getAppToken": function() {
    var apptoken = hp.getAppToken("DummyToken","DummyKey");
    assert.isString(apptoken);
    assert.equal(apptoken,
      'd0e1c9740c5bafe851749d66a40f4744b7bd4c4ee4798560315dbe75ac6f9365');
  },
  "padNumber": function() {
    assert.isString(hp.padNumber(1,2));
    assert.equal(hp.padNumber(5,3), '005');
    assert.equal(hp.padNumber(10,3), '010');
    assert.equal(hp.padNumber(10,2), '10');
    assert.equal(hp.padNumber(10,1), '10');
    assert.equal(hp.padNumber(10,0), '10');
    assert.equal(hp.padNumber(536,5), '00536');
  },
  "checkCallback": function() {
    assert.isFunction(hp.checkCallback(function() {}));
    assert.isFunction(hp.checkCallback({}));
    assert.isFunction(hp.checkCallback([]));
    assert.isFunction(hp.checkCallback(null));
    assert.isFunction(hp.checkCallback(1234567890));
    assert.isFunction(hp.checkCallback('1234567890'));
  },
  "getMaxFileDescriptors": {
    topic: function() {
      hp.getMaxFileDescriptors(this.callback);
    },
    "getMaxFileDescriptors ok": function(err, filedesc) {
      assert.isString(filedesc);
      assert.isNull(err);
    }
  },
  "isVersion": function() {
    assert.isTrue(hp.isVersion(0));
    assert.isTrue(hp.isVersion(1));
    assert.isFalse(hp.isVersion(-1));
    assert.isTrue(hp.isVersion(9007199254740991));
    assert.isFalse(hp.isVersion(9007199254740992));
    assert.isFalse(hp.isVersion('hello'));
    assert.isTrue(hp.isVersion('0'));
    assert.isTrue(hp.isVersion('1'));
    assert.isFalse(hp.isVersion('-1'));
    assert.isTrue(hp.isVersion('9007199254740991'));
    assert.isFalse(hp.isVersion('9007199254740992'));
    assert.isFalse(hp.isVersion(null));
  },
  "getCaChannel": function() {
    assert.isArray(hp.getCaChannel());
  },
  'isIPInNetwork': {
    '192.168.1.11 in 192.168.1.0/24': function() {
      assert.isTrue(hp.isIPInNetwork('192.168.1.11', ['192.168.1.0/24']));
    },
    '192.168.1.1 is private': function() {
      assert.isTrue(hp.isIPInNetwork('192.168.1.1'));
    },
    '127.0.0.1 in 0.0.0.0/1': function() {
      assert.isTrue(hp.isIPInNetwork('127.0.0.1', ['0.0.0.0/1']));
    },
    '10.4.5.6 in 10.0.0.0/8': function() {
      assert.isTrue(hp.isIPInNetwork('10.4.5.6', ['10.0.0.0/8']));
    },
    'null in 192.168.1.0/8': function() {
      assert.isFalse(hp.isIPInNetwork(null, ['192.168.1.0/8']));
    },
    '"" in 192.168.1.0/8': function() {
      assert.isFalse(hp.isIPInNetwork("", ['192.168.1.0/8']));
    },
    'a in 192.168.1.0/8': function() {
      assert.isFalse(hp.isIPInNetwork('a', ['192.168.1.0/8']));
    },
    '10.1.1.1 in 192.168.1.0/24 or 10.0.0.0/8': function() {
      assert.isTrue(hp.isIPInNetwork('10.1.1.1', ['192.168.1.0/24', '10.0.0.0/8']));
    },
    '10.1.1.1 in []': function() {
      assert.isTrue(hp.isIPInNetwork('10.1.1.1', []));
    },
    '10.1.1.1 in null': function() {
      assert.isTrue(hp.isIPInNetwork('10.1.1.1', null));
    },
    '10.1.1.1 in NOT in 192.168.1.0/24': function() {
      assert.isFalse(hp.isIPInNetwork('10.1.1.1', ['192.168.1.0/24']));
    },
    '10.1.1.1 in NOT in 192.168.1.0/24 or 11.0.0.0/8 but on 10.0.0.0/8': function() {
      assert.isTrue(hp.isIPInNetwork('10.1.1.1', ['192.168.1.0/24', '11.0.0.0/8', '10.0.0.0/8']));
    }
  }
}).export(module);
<commit_msg>Fix helpers tests<commit_after>/**
 * PUSH Notification server
 * (c) Telefonica Digital, 2012 - All rights reserved
 * License: GNU Affero V3 (see LICENSE file)
 * Fernando Rodríguez Sela <frsela@tid.es>
 * Guillermo Lopez Leal <gll@tid.es>
 */

var hp = require("../../src/common/Helpers.js"),
    assert = require('assert'),
    vows = require('vows'),
    baseURL = require('../../src/config.js').consts.publicBaseURL;

vows.describe('Helper tests').addBatch({
  "getNotificationURL": function() {
    var token = Date.now();
    var url = hp.getNotificationURL(token);
    assert.isString(url);
    assert.equal(url, baseURL + '/notify/' + token);
  },
  "getAppToken": function() {
    var apptoken = hp.getAppToken("DummyToken","DummyKey");
    assert.isString(apptoken);
    assert.equal(apptoken,
      'd0e1c9740c5bafe851749d66a40f4744b7bd4c4ee4798560315dbe75ac6f9365');
  },
  "padNumber": function() {
    assert.isString(hp.padNumber(1,2));
    assert.equal(hp.padNumber(5,3), '005');
    assert.equal(hp.padNumber(10,3), '010');
    assert.equal(hp.padNumber(10,2), '10');
    assert.equal(hp.padNumber(10,1), '10');
    assert.equal(hp.padNumber(10,0), '10');
    assert.equal(hp.padNumber(536,5), '00536');
  },
  "checkCallback": function() {
    assert.isFunction(hp.checkCallback(function() {}));
    assert.isFunction(hp.checkCallback({}));
    assert.isFunction(hp.checkCallback([]));
    assert.isFunction(hp.checkCallback(null));
    assert.isFunction(hp.checkCallback(1234567890));
    assert.isFunction(hp.checkCallback('1234567890'));
  },
  "getMaxFileDescriptors": {
    topic: function() {
      hp.getMaxFileDescriptors(this.callback);
    },
    "getMaxFileDescriptors ok": function(err, filedesc) {
      assert.isString(filedesc);
      assert.isNull(err);
    }
  },
  "isVersion": function() {
    assert.isTrue(hp.isVersion(0));
    assert.isTrue(hp.isVersion(1));
    assert.isFalse(hp.isVersion(-1));
    assert.isTrue(hp.isVersion(9007199254740991));
    assert.isFalse(hp.isVersion(9007199254740992));
    assert.isFalse(hp.isVersion('hello'));
    assert.isTrue(hp.isVersion('0'));
    assert.isTrue(hp.isVersion('1'));
    assert.isFalse(hp.isVersion('-1'));
    assert.isTrue(hp.isVersion('9007199254740991'));
    assert.isFalse(hp.isVersion('9007199254740992'));
    assert.isFalse(hp.isVersion(null));
  },
  "getCaChannel": function() {
    assert.isArray(hp.getCaChannel());
  },
  'isIPInNetwork': {
    '192.168.1.11 in 192.168.1.0/24': function() {
      assert.isTrue(hp.isIPInNetwork('192.168.1.11', ['192.168.1.0/24']));
    },
    '127.0.0.1 in 0.0.0.0/1': function() {
      assert.isTrue(hp.isIPInNetwork('127.0.0.1', ['0.0.0.0/1']));
    },
    '10.4.5.6 in 10.0.0.0/8': function() {
      assert.isTrue(hp.isIPInNetwork('10.4.5.6', ['10.0.0.0/8']));
    },
    'null in 192.168.1.0/8': function() {
      assert.isFalse(hp.isIPInNetwork(null, ['192.168.1.0/8']));
    },
    '"" in 192.168.1.0/8': function() {
      assert.isFalse(hp.isIPInNetwork("", ['192.168.1.0/8']));
    },
    'a in 192.168.1.0/8': function() {
      assert.isFalse(hp.isIPInNetwork('a', ['192.168.1.0/8']));
    },
    '10.1.1.1 in 192.168.1.0/24 or 10.0.0.0/8': function() {
      assert.isTrue(hp.isIPInNetwork('10.1.1.1', ['192.168.1.0/24', '10.0.0.0/8']));
    },
    '10.1.1.1 in []': function() {
      assert.isTrue(hp.isIPInNetwork('10.1.1.1', []));
    },
    '10.1.1.1 in NOT in 192.168.1.0/24': function() {
      assert.isFalse(hp.isIPInNetwork('10.1.1.1', ['192.168.1.0/24']));
    },
    '10.1.1.1 in NOT in 192.168.1.0/24 or 11.0.0.0/8 but on 10.0.0.0/8': function() {
      assert.isTrue(hp.isIPInNetwork('10.1.1.1', ['192.168.1.0/24', '11.0.0.0/8', '10.0.0.0/8']));
    }
  }
}).export(module);
<|endoftext|>