<commit_before>'use strict';

var async = require('async');
var fs = require('fs');
var should = require('should');
var File = require('vinyl');
var Neuter = require('../index');
var path = require('path');

function readFileAsync(filepath) {
	var filepath = path.resolve(process.cwd(), filepath);

	return function(callback) {
		fs.readFile(filepath, function(err, data) {
			if (err) {
				return callback(err);
			}

			var file = new File({
				base: path.dirname(filepath),
				path: filepath,
				contents: data,
			});

			return callback(null, file);
		});
	}
}

function loadFiles(original, result, callback) {
	async.parallel([
		function(callback) { new Neuter().parse(original, callback) },
		readFileAsync(result),
	], function(err, results) {
		if (err) {
			throw err;
		}

		callback(results[0], results[1]);
	});
}

describe('Require statements', function() {
	it('should combine in the order of the require statements', function(done) {
		fs.readFile('test/expected/simple_require_statements.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/simple_require_filepath_transforms.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	it('should be ignored if told so', function(done) {
		fs.readFile('test/expected/ignores_files_when_told.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/ignores_files_when_told.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	it('in javascript statements should be ignored', function(done) {
		fs.readFile('test/expected/do_not_replace_requires_in_statements.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/do_not_replace_requires_in_statements.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	it('in comments should be ignored', function(done) {
		fs.readFile('test/expected/comment_out_require.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/comment_out_require.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	describe('not ending with a semicolon', function() {
		it('should be read correctly', function(done) {
			fs.readFile('test/expected/optional_semicolons.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/optional_semicolons.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with filepath transforms', function() {
		it('should combine in the order of the require statements', function(done) {
			fs.readFile('test/expected/simple_require_filepath_transforms.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/simple_require_filepath_transforms.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with basepath options', function() {
		it('should combine in the order of the require statements', function(done) {
			fs.readFile('test/expected/simple_require_filepath_transforms.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/simple_require_filepath_transforms.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('that are repeated', function() {
		it('should be ignored', function(done) {
			fs.readFile('test/expected/duplicate_require_statements.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/duplicate_require_statements.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with circular references', function() {
		it('should be correctly handled', function(done) {
			fs.readFile('test/expected/circular_require_statements.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/circular_require_statements.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});
});

describe('Relative require statements', function() {
	it('should combine in the order of the require statements', function(done) {
		fs.readFile('test/expected/relative_require_statements.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/relative_require_statements.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	describe('with basepath options', function() {
		it('should combine in the order of the require statements', function(done) {
			fs.readFile('test/expected/relative_requires_with_basepath.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/relative_requires_with_basepath.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});
});

describe('Seperator options', function() {
	it('should be customizable', function(done) {
		fs.readFile('test/expected/custom_separator_options.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/simple_require_statements.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});
});

describe('Code order between require statements', function() {
	it('should be left intact', function(done) {
		fs.readFile('test/expected/respects_code_order_between_requires.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/respects_code_order_between_requires.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});
});

describe('Patterns', function() {
	describe('for files and paths', function() {
		it('should be read correctly', function(done) {
			fs.readFile('test/expected/accepts_file_patterns.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/glob/*.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with require("glob/*")', function() {
		it('should require all files in that directory', function(done) {
			fs.readFile('test/expected/glob_require.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/glob_require.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with spaces', function() {
		it('should include correctly', function(done) {
			fs.readFile('test/expected/spaces_allowed_within_require_statement.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/spaces_allowed_within_require_statement.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('without .js extension', function() {
		it('should include correctly', function(done) {
			fs.readFile('test/expected/optional_dotjs.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/optional_dotjs.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});
});

describe('Source maps', function() {
	it('should be generated', function(done) {
		fs.readFile('test/expected/source_maps.map', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().generateMap('test/fixtures/glob_require.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});
});

describe('Files', function() {
	it('should be processed as a template', function(done) {
		fs.readFile('test/expected/process_as_template.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/process_as_template.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	it('should be processed with a function', function(done) {
		fs.readFile('test/expected/process_with_function.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/simple_require.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});
});
<commit_msg>updated test statements to use correct parse options<commit_after>'use strict';

var async = require('async');
var fs = require('fs');
var should = require('should');
var File = require('vinyl');
var Neuter = require('../index');
var path = require('path');

function readFileAsync(filepath) {
	var filepath = path.resolve(process.cwd(), filepath);

	return function(callback) {
		fs.readFile(filepath, function(err, data) {
			if (err) {
				return callback(err);
			}

			var file = new File({
				base: path.dirname(filepath),
				path: filepath,
				contents: data,
			});

			return callback(null, file);
		});
	}
}

function loadFiles(original, result, callback) {
	async.parallel([
		function(callback) { new Neuter().parse(original, callback) },
		readFileAsync(result),
	], function(err, results) {
		if (err) {
			throw err;
		}

		callback(results[0], results[1]);
	});
}

describe('Require statements', function() {
	it('should combine in the order of the require statements', function(done) {
		fs.readFile('test/expected/simple_require_statements.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/simple_require_filepath_transforms.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	it('should be ignored if told so', function(done) {
		fs.readFile('test/expected/ignores_files_when_told.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter({
				skipFiles: [
					'test/fixtures/contains_commonjs_require.js'
				],
			}).parse('test/fixtures/ignores_files_when_told.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	it('in javascript statements should be ignored', function(done) {
		fs.readFile('test/expected/do_not_replace_requires_in_statements.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/do_not_replace_requires_in_statements.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	it('in comments should be ignored', function(done) {
		fs.readFile('test/expected/comment_out_require.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/comment_out_require.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	describe('not ending with a semicolon', function() {
		it('should be read correctly', function(done) {
			fs.readFile('test/expected/optional_semicolons.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/optional_semicolons.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with filepath transforms', function() {
		it('should combine in the order of the require statements', function(done) {
			fs.readFile('test/expected/simple_require_filepath_transforms.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter({
					filepathTransform: function(filepath) {
						return 'test/fixtures/' + filepath;
					},
				}).parse('test/fixtures/simple_require_filepath_transforms.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with basepath options', function() {
		it('should combine in the order of the require statements', function(done) {
			fs.readFile('test/expected/simple_require_filepath_transforms.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter({
					basePath: 'test/fixtures/',
				}).parse('test/fixtures/simple_require_filepath_transforms.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('that are repeated', function() {
		it('should be ignored', function(done) {
			fs.readFile('test/expected/duplicate_require_statements.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/duplicate_require_statements.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with circular references', function() {
		it('should be correctly handled', function(done) {
			fs.readFile('test/expected/circular_require_statements.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/circular_require_statements.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});
});

describe('Relative require statements', function() {
	it('should combine in the order of the require statements', function(done) {
		fs.readFile('test/expected/relative_require_statements.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/relative_require_statements.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	describe('with basepath options', function() {
		it('should combine in the order of the require statements', function(done) {
			fs.readFile('test/expected/relative_requires_with_basepath.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter({
					basePath: 'test/fixtures/'
				}).parse('test/fixtures/relative_requires_with_basepath.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});
});

describe('Seperator options', function() {
	it('should be customizable', function(done) {
		fs.readFile('test/expected/custom_separator_options.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter({
				separator: '!!!!',
			}).parse('test/fixtures/simple_require_statements.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});
});

describe('Code order between require statements', function() {
	it('should be left intact', function(done) {
		fs.readFile('test/expected/respects_code_order_between_requires.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().parse('test/fixtures/respects_code_order_between_requires.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});
});

describe('Patterns', function() {
	describe('for files and paths', function() {
		it('should be read correctly', function(done) {
			fs.readFile('test/expected/accepts_file_patterns.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/glob/*.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with require("glob/*")', function() {
		it('should require all files in that directory', function(done) {
			fs.readFile('test/expected/glob_require.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/glob_require.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('with spaces', function() {
		it('should include correctly', function(done) {
			fs.readFile('test/expected/spaces_allowed_within_require_statement.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/spaces_allowed_within_require_statement.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});

	describe('without .js extension', function() {
		it('should include correctly', function(done) {
			fs.readFile('test/expected/optional_dotjs.js', function(err, expected) {
				if (err) {
					return callback(err);
				}

				new Neuter().parse('test/fixtures/optional_dotjs.js', function(err, result) {
					if (err) {
						throw err;
					}

					result.should.equal(expected.toString());
					done();
				});
			});
		});
	});
});

describe('Source maps', function() {
	it('should be generated', function(done) {
		fs.readFile('test/expected/source_maps.map', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter().generateMap('test/fixtures/glob_require.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});
});

describe('Files', function() {
	it('should be processed as a template', function(done) {
		fs.readFile('test/expected/process_as_template.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter({
				process: {
					data: {
						foo: 5,
						bar: 'baz'
					}
				}
			}).parse('test/fixtures/process_as_template.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});

	it('should be processed with a function', function(done) {
		fs.readFile('test/expected/process_with_function.js', function(err, expected) {
			if (err) {
				return callback(err);
			}

			new Neuter({
				process: function(file) {
					file.contents = Buffer.concat([
						new Buffer('// Source for: ' + file.path + '\n'),
						file.contents,
					]);
					return file;
				}
			}).parse('test/fixtures/simple_require.js', function(err, result) {
				if (err) {
					throw err;
				}

				result.should.equal(expected.toString());
				done();
			});
		});
	});
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var os = require('os');
var mkdirp = require('mkdirp');
var should = require('should');
var expect = require('chai').expect;
var compressor = require('../lib/node-minify');

var oneFile = __dirname + '/../examples/public/js/base.js';
var filesArray = [
  __dirname + '/../examples/public/js/base.js',
  __dirname + '/../examples/public/js/base2.js'
];
var fileCSS = __dirname + '/../examples/public/css/base.css';
var fileCSSArray = [
  __dirname + '/../examples/public/css/base.css',
  __dirname + '/../examples/public/css/base2.css'
];

var tests = {
  concat: [
    {
      it: 'should concat javascript and no compress',
      minify: {
        type: 'no-compress',
        fileIn: filesArray,
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-nocompress.js'
      }
    }
  ],
  commoncss: [
    {
      it: 'should compress css with {type} and a single file',
      minify: {
        type: '{type}',
        fileIn: fileCSS,
        fileOut: __dirname + '/../examples/public/css/base-min-{type}.css'
      }
    },
    {
      it: 'should compress css with {type} and an array of file',
      minify: {
        type: '{type}',
        fileIn: fileCSSArray,
        fileOut: __dirname + '/../examples/public/css/base-onefile-{type}.css'
      }
    }
  ],
  commonjs: [
    {
      it: 'should compress javascript with {type} and a single file',
      minify: {
        type: '{type}',
        fileIn: oneFile,
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js'
      }
    },
    {
      it: 'should compress javascript with {type} and a single file with a custom temp path',
      minify: {
        type: '{type}',
        fileIn: oneFile,
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and a single file with a custom public folder',
      minify: {
        type: '{type}',
        fileIn: 'base.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {type} and a single file with a custom public folder and a custom temp path',
      minify: {
        type: '{type}',
        fileIn: 'base.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and a single file with a custom buffer size',
      minify: {
        type: '{type}',
        fileIn: oneFile,
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file',
      minify: {
        type: '{type}',
        fileIn: filesArray,
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file with a custom temp path',
      minify: {
        type: '{type}',
        fileIn: filesArray,
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file with a custom public folder',
      minify: {
        type: '{type}',
        fileIn: [
          'base.js',
          'base2.js'
        ],
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file with a custom public folder and a custom temp path',
      minify: {
        type: '{type}',
        fileIn: [
          'base.js',
          'base2.js'
        ],
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file with a custom buffer size',
      minify: {
        type: '{type}',
        fileIn: filesArray,
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path',
      minify: {
        type: '{type}',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path with a custom temp path',
      minify: {
        type: '{type}',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path with a custom public folder',
      minify: {
        type: '{type}',
        fileIn: '**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path with a custom public folder and a custom temp path',
      minify: {
        type: '{type}',
        fileIn: '**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path with a custom buffer size',
      minify: {
        type: '{type}',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        buffer: 2000 * 1024
      }
    }
  ]
};

var runOneTest = function(options, type, sync) {
  // extend object
  options = JSON.parse(JSON.stringify(options));

  options.minify.type = options.minify.type.replace('{type}', type);
  options.minify.fileOut = options.minify.fileOut.replace('{type}', type);

  if (sync) {
    options.minify.sync = true;
  }

  it(options.it.replace('{type}', type), function(done) {
    options.minify.callback = function(err, min) {
      should.not.exist(err);
      should.exist(min);

      done();
    };

    compressor.minify(options.minify);
  });
};

describe('node-minify', function() {
  mkdirp('/tmp/');

  describe('Fake binary', function() {
    it('should throw an error if binary does not exist', function(done) {
      var options = {};
      options.minify = {
        type: 'fake',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      };

      expect(function() {
        compressor.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('No type', function() {
    it('should throw an error if no type', function(done) {
      var options = {};
      options.minify = {
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      };

      expect(function() {
        compressor.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('Deprecated', function() {
    it('should show a deprecated message', function(done) {
      var options = {};
      options.minify = {
        type: 'uglifyjs',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      };

      options.minify.callback = function(err, min) {
        should.not.exist(err);
        should.exist(min);

        done();
      };

      new compressor.minify(options.minify);
    });
  });

  describe('Concatenation', function() {
    tests.concat.forEach(function(o) {
      runOneTest(o, 'no-compress');
    });
    tests.concat.forEach(function(o) {
      runOneTest(o, 'no-compress', true);
    });
  });

  describe('GCC', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc', true);
    });
  });

  describe('YUI', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'yui-js');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'yui-js', true);
    });

    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'yui-css');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'yui-css', true);
    });
  });

  describe('UglifyJS', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'uglifyjs');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'uglifyjs', true);
    });
  });

  describe('Clean-css', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'clean-css');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'clean-css', true);
    });
  });

  describe('CSSO', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'csso');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'csso', true);
    });
  });

  describe('Sqwish', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'sqwish');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'sqwish', true);
    });
  });

  describe('Sqwish with no binary', function() {
    before(function() {
      if (os.platform() === 'win32') {
        fs.renameSync(__dirname + '/../node_modules/.bin/sqwish.cmd', __dirname + '/../node_modules/.bin/sqwish.cmd.old');
      }
      fs.renameSync(__dirname + '/../node_modules/.bin/sqwish', __dirname + '/../node_modules/.bin/sqwish.old');
      fs.renameSync(__dirname + '/../node_modules/sqwish/bin/sqwish', __dirname + '/../node_modules/sqwish/bin/sqwish.old');
    });
    after(function() {
      if (os.platform() === 'win32') {
        fs.renameSync(__dirname + '/../node_modules/.bin/sqwish.cmd.old', __dirname + '/../node_modules/.bin/sqwish.cmd');
      }
      fs.renameSync(__dirname + '/../node_modules/.bin/sqwish.old', __dirname + '/../node_modules/.bin/sqwish');
      fs.renameSync(__dirname + '/../node_modules/sqwish/bin/sqwish.old', __dirname + '/../node_modules/sqwish/bin/sqwish');
    });
    it('should throw an error if binary does not exist', function(done) {
      var options = {};
      options.minify = {
        type: 'sqwish',
        fileIn: fileCSS,
        fileOut: __dirname + '/../examples/public/css/base-min-sqwish.css'
      };

      expect(function() {
        compressor.minify(options.minify);
      }).to.throw();
      done();
    });
  });
});
<commit_msg>Add test<commit_after>'use strict';

var fs = require('fs');
var os = require('os');
var mkdirp = require('mkdirp');
var should = require('should');
var expect = require('chai').expect;
var compressor = require('../lib/node-minify');

var oneFile = __dirname + '/../examples/public/js/base.js';
var filesArray = [
  __dirname + '/../examples/public/js/base.js',
  __dirname + '/../examples/public/js/base2.js'
];
var fileCSS = __dirname + '/../examples/public/css/base.css';
var fileCSSArray = [
  __dirname + '/../examples/public/css/base.css',
  __dirname + '/../examples/public/css/base2.css'
];

var tests = {
  concat: [
    {
      it: 'should concat javascript and no compress and an array of file',
      minify: {
        type: 'no-compress',
        fileIn: filesArray,
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-nocompress.js'
      }
    },
    {
      it: 'should concat javascript and no compress and a single file',
      minify: {
        type: 'no-compress',
        fileIn: oneFile,
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-nocompress.js'
      }
    }
  ],
  commoncss: [
    {
      it: 'should compress css with {type} and a single file',
      minify: {
        type: '{type}',
        fileIn: fileCSS,
        fileOut: __dirname + '/../examples/public/css/base-min-{type}.css'
      }
    },
    {
      it: 'should compress css with {type} and an array of file',
      minify: {
        type: '{type}',
        fileIn: fileCSSArray,
        fileOut: __dirname + '/../examples/public/css/base-onefile-{type}.css'
      }
    }
  ],
  commonjs: [
    {
      it: 'should compress javascript with {type} and a single file',
      minify: {
        type: '{type}',
        fileIn: oneFile,
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js'
      }
    },
    {
      it: 'should compress javascript with {type} and a single file with a custom temp path',
      minify: {
        type: '{type}',
        fileIn: oneFile,
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and a single file with a custom public folder',
      minify: {
        type: '{type}',
        fileIn: 'base.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {type} and a single file with a custom public folder and a custom temp path',
      minify: {
        type: '{type}',
        fileIn: 'base.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and a single file with a custom buffer size',
      minify: {
        type: '{type}',
        fileIn: oneFile,
        fileOut: __dirname + '/../examples/public/js-dist/base-min-{type}.js',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file',
      minify: {
        type: '{type}',
        fileIn: filesArray,
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file with a custom temp path',
      minify: {
        type: '{type}',
        fileIn: filesArray,
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file with a custom public folder',
      minify: {
        type: '{type}',
        fileIn: [
          'base.js',
          'base2.js'
        ],
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file with a custom public folder and a custom temp path',
      minify: {
        type: '{type}',
        fileIn: [
          'base.js',
          'base2.js'
        ],
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and an array of file with a custom buffer size',
      minify: {
        type: '{type}',
        fileIn: filesArray,
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path',
      minify: {
        type: '{type}',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path with a custom temp path',
      minify: {
        type: '{type}',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path with a custom public folder',
      minify: {
        type: '{type}',
        fileIn: '**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/'
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path with a custom public folder and a custom temp path',
      minify: {
        type: '{type}',
        fileIn: '**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        publicFolder: __dirname + '/../examples/public/js/',
        tempPath: '/tmp/'
      }
    },
    {
      it: 'should compress javascript with {type} and wildcards path with a custom buffer size',
      minify: {
        type: '{type}',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js',
        buffer: 2000 * 1024
      }
    }
  ]
};

var runOneTest = function(options, type, sync) {
  // extend object
  options = JSON.parse(JSON.stringify(options));

  options.minify.type = options.minify.type.replace('{type}', type);
  options.minify.fileOut = options.minify.fileOut.replace('{type}', type);

  if (sync) {
    options.minify.sync = true;
  }

  it(options.it.replace('{type}', type), function(done) {
    options.minify.callback = function(err, min) {
      should.not.exist(err);
      should.exist(min);

      done();
    };

    compressor.minify(options.minify);
  });
};

describe('node-minify', function() {
  mkdirp('/tmp/');

  describe('Fake binary', function() {
    it('should throw an error if binary does not exist', function(done) {
      var options = {};
      options.minify = {
        type: 'fake',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      };

      expect(function() {
        compressor.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('No type', function() {
    it('should throw an error if no type', function(done) {
      var options = {};
      options.minify = {
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      };

      expect(function() {
        compressor.minify(options.minify);
      }).to.throw();
      done();
    });
  });

  describe('Deprecated', function() {
    it('should show a deprecated message', function(done) {
      var options = {};
      options.minify = {
        type: 'uglifyjs',
        fileIn: __dirname + '/../examples/public/js/**/*.js',
        fileOut: __dirname + '/../examples/public/js-dist/base-onefile-{type}.js'
      };

      options.minify.callback = function(err, min) {
        should.not.exist(err);
        should.exist(min);

        done();
      };

      new compressor.minify(options.minify);
    });
  });

  describe('Concatenation', function() {
    tests.concat.forEach(function(o) {
      runOneTest(o, 'no-compress');
    });
    tests.concat.forEach(function(o) {
      runOneTest(o, 'no-compress', true);
    });
  });

  describe('GCC', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'gcc', true);
    });
  });

  describe('YUI', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'yui-js');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'yui-js', true);
    });

    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'yui-css');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'yui-css', true);
    });
  });

  describe('UglifyJS', function() {
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'uglifyjs');
    });
    tests.commonjs.forEach(function(o) {
      runOneTest(o, 'uglifyjs', true);
    });
  });

  describe('Clean-css', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'clean-css');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'clean-css', true);
    });
  });

  describe('CSSO', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'csso');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'csso', true);
    });
  });

  describe('Sqwish', function() {
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'sqwish');
    });
    tests.commoncss.forEach(function(o) {
      runOneTest(o, 'sqwish', true);
    });
  });

  describe('Sqwish with no binary', function() {
    before(function() {
      if (os.platform() === 'win32') {
        fs.renameSync(__dirname + '/../node_modules/.bin/sqwish.cmd', __dirname + '/../node_modules/.bin/sqwish.cmd.old');
      }
      fs.renameSync(__dirname + '/../node_modules/.bin/sqwish', __dirname + '/../node_modules/.bin/sqwish.old');
      fs.renameSync(__dirname + '/../node_modules/sqwish/bin/sqwish', __dirname + '/../node_modules/sqwish/bin/sqwish.old');
    });
    after(function() {
      if (os.platform() === 'win32') {
        fs.renameSync(__dirname + '/../node_modules/.bin/sqwish.cmd.old', __dirname + '/../node_modules/.bin/sqwish.cmd');
      }
      fs.renameSync(__dirname + '/../node_modules/.bin/sqwish.old', __dirname + '/../node_modules/.bin/sqwish');
      fs.renameSync(__dirname + '/../node_modules/sqwish/bin/sqwish.old', __dirname + '/../node_modules/sqwish/bin/sqwish');
    });
    it('should throw an error if binary does not exist', function(done) {
      var options = {};
      options.minify = {
        type: 'sqwish',
        fileIn: fileCSS,
        fileOut: __dirname + '/../examples/public/css/base-min-sqwish.css'
      };

      expect(function() {
        compressor.minify(options.minify);
      }).to.throw();
      done();
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var parser = require('../lib/parse');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.parser = {
  setUp: function(done) {
    this.defaultOptions = {
      parser: Number
    };

    done();
  },

  integer: function(test) {
    test.deepEqual(
      parser({
        a: '8'
      }, this.defaultOptions),
      {
        a: 8
      },
      'Should convert integers.'
    );

    test.done();
  },

  radix: function(test) {
    test.deepEqual(
      parser({
        a: '08'
      }, this.defaultOptions),
      {
        a: 8
      },
      'Should convert strings starting with 0.'
    );

    test.done();
  },

  float: function(test) {
    test.deepEqual(
      parser({
        a: '0.8'
      }, this.defaultOptions),
      {
        a: 0.8
      },
      'Should convert floating point numbers.'
    );

    test.done();
  },

  deep: function(test) {
    test.deepEqual(
      parser({
        a: {
          b: '8'
        }
      }, this.defaultOptions),
      {
        a: {
          b: 8
        }
      },
      'Should convert recursively.'
    );

    test.done();
  },

  string: function(test) {
    test.deepEqual(
      parser({
        a: 'string'
      }, this.defaultOptions),
      {
        a: 'string'
      },
      'Should not convert regular string.'
    );

    test.deepEqual(
      parser({
        a: '10.0.0.1'
      }, this.defaultOptions),
      {
        a: '10.0.0.1'
      },
      'Should not convert IP string.'
    );

    test.deepEqual(
      parser({
        a: '106e04cf-344b-4c1c-98a0-002a67df7099'
      }, this.defaultOptions),
      {
        a: '106e04cf-344b-4c1c-98a0-002a67df7099'
      },
      'Should not convert UUID string.'
    );

    test.done();
  }
};
<commit_msg>Add tests for arrays<commit_after>'use strict';

var parser = require('../lib/parse');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.parser = {
  setUp: function(done) {
    this.defaultOptions = {
      parser: Number
    };

    done();
  },

  integer: function(test) {
    test.deepEqual(
      parser({
        a: '8'
      }, this.defaultOptions),
      {
        a: 8
      },
      'Should convert integers.'
    );

    test.done();
  },

  radix: function(test) {
    test.deepEqual(
      parser({
        a: '08'
      }, this.defaultOptions),
      {
        a: 8
      },
      'Should convert strings starting with 0.'
    );

    test.done();
  },

  float: function(test) {
    test.deepEqual(
      parser({
        a: '0.8'
      }, this.defaultOptions),
      {
        a: 0.8
      },
      'Should convert floating point numbers.'
    );

    test.done();
  },

  deep: function(test) {
    test.deepEqual(
      parser({
        a: {
          b: '8'
        }
      }, this.defaultOptions),
      {
        a: {
          b: 8
        }
      },
      'Should convert recursively.'
    );

    test.done();
  },

  array: function(test) {
    test.deepEqual(
      parser(['8'], this.defaultOptions),
      [8],
      'Should convert array items.'
    );

    test.done();
  },

  deepArray: function(test) {
    test.deepEqual(
      parser({
        a: ['8', ['9'], { a: '7' }],
      }, this.defaultOptions),
      {
        a: [8, [9], { a: 7 }],
      },
      'Should convert arrays recursively.'
    );

    test.done();
  },

  string: function(test) {
    test.deepEqual(
      parser({
        a: 'string'
      }, this.defaultOptions),
      {
        a: 'string'
      },
      'Should not convert regular string.'
    );

    test.deepEqual(
      parser({
        a: '10.0.0.1'
      }, this.defaultOptions),
      {
        a: '10.0.0.1'
      },
      'Should not convert IP string.'
    );

    test.deepEqual(
      parser({
        a: '106e04cf-344b-4c1c-98a0-002a67df7099'
      }, this.defaultOptions),
      {
        a: '106e04cf-344b-4c1c-98a0-002a67df7099'
      },
      'Should not convert UUID string.'
    );

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


<commit_before>/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/

define(function(require){
	var $ = require('jquery');
	var html = require('text!test/markup/picker-markup.html!strip');

	require('bootstrap');
	require('fuelux/picker');

	module('Fuel UX Picker');

	// TODO: add shown/hidden event test

	test('should be defined on jquery object', function () {
		ok($().find('#picker1').picker(), 'picker method is defined');
	});

	test('should return element', function () {
		var $picker = $(html).find('#picker1');
		ok($picker.picker() === $picker, 'picker should be initialized');
	});

	test('should behave as expected - input', function(){
		var $picker = $(html).find('#picker1');

		$('body').append($picker);
		$picker.picker();
		$picker.on('cancelled.fu.picker', function(e, helpers){
			ok(1===1, 'default action event (cancel) triggered upon external click');
		});

		console.log($picker.find('.picker-trigger'));

		var $textInputTrigger = $($picker.find('.picker-trigger')[0]);
		var $otherTrigger = $($picker.find('.picker-trigger')[1]);
		$textInputTrigger.focus().focus();
		equal($picker.hasClass('showing'), true, 'picker shows when appropriate');

		$('body').click();
		equal($picker.hasClass('showing'), false, 'picker hides when appropriate');

		$textInputTrigger.click();
		equal($picker.hasClass('showing'), true, 'picker shows when appropriate');

		$textInputTrigger.click();
		equal($picker.hasClass('showing'), true, 'picker continues showing when text input clicked and picker is already showing');

		$otherTrigger.click();
		equal($picker.hasClass('showing'), false, 'picker hides when non-text input clicked and picker is already showing');

		$picker.remove();
	});

	test('should behave as expected - button', function(){
		var $picker = $(html).find('#picker2');

		$picker.picker();
		$picker.on('cancelled.fu.picker', function(e, helpers){
			ok(1===1, 'default action event (cancel) triggered upon external click');
		});
		$('body').append($picker);

		$($picker.find('.picker-trigger')[1]).click();
		equal($picker.hasClass('showing'), true, 'picker shows when appropriate');

		$('body').click();
		equal($picker.hasClass('showing'), false, 'picker hides when appropriate');
		$picker.remove();
	});

	test('show/hide functions should behave as expected', function(){
		var $picker = $(html).find('#picker1');
		$picker.picker();

		$picker.picker('show');
		equal($picker.hasClass('showing'), true, 'picker shows when appropriate');

		$picker.picker('hide');
		equal($picker.hasClass('showing'), false, 'picker hides when appropriate');
	});

	test('trigger events should fire as expected', function(){
		var $picker = $(html).find('#picker1');

		$picker.picker();
		$picker.on('accepted.fu.picker', function(e, helpers){
			ok(1===1, 'accept event triggers on accept');
			equal(typeof e, 'object', 'event object passed in accept event');
			equal(typeof helpers, 'object', 'helpers object passed in accept event');
			equal((helpers.contents!==undefined), true, 'helpers object contains correct attributes');
		});
		$picker.on('cancelled.fu.picker', function(e, helpers){
			ok(1===1, 'cancel event triggers on cancel');
			equal(typeof e, 'object', 'event object passed in cancel event');
			equal(typeof helpers, 'object', 'helpers object passed in cancel event');
			equal((helpers.contents!==undefined), true, 'helpers object contains correct attributes');
		});

		$picker.find('input').focus().focus();
		$picker.find('.picker-cancel').click();
		$picker.find('input').focus().focus();
		$picker.find('.picker-accept').click();
	});

	test('onAccept function should be called as expected', function(){
		var $picker = $(html).find('#picker1');

		$picker.picker({
			onAccept: function(helpers){
				ok(1===1, 'onAccept function called on accept');
				equal(typeof helpers, 'object', 'helpers object passed to onAccept function');
				equal((helpers.contents!==undefined), true, 'helpers object contains correct attributes');
				$picker.picker('hide');
			}
		});

		$picker.find('input').focus().focus();
		$picker.find('.picker-accept').click();
	});

	test('onCancel function should be called as expected', function(){
		var $picker = $(html).find('#picker1');

		$picker.picker({
			onCancel: function(helpers){
				ok(1===1, 'onCancel function called on cancel');
				equal(typeof helpers, 'object', 'helpers object passed to onCancel function');
				equal((helpers.contents!==undefined), true, 'helpers object contains correct attributes');
				$picker.picker('hide');
			}
		});

		$picker.find('input').focus().focus();
		$picker.find('.picker-cancel').click();
	});

	test('Enter and exit keys should trigger appropriate response', function(){
		var $picker = $(html).find('#picker1');
		var $input  = $picker.find('input');
		var e = $.Event("keydown");

		$picker.picker({
			onAccept: function(){
				ok(1===1, 'onAccept function called when enter keypress');
			},
			onCancel: function(){
				ok(1===1, 'onCancel function called when exit keypress');
			}
		});

		e.keyCode = 13;
		$input.trigger(e);
		e.keyCode = 27;
		$input.trigger(e);
	});

	test('externalClickExceptions option should work as expected', function(){
		var $picker = $(html).find('#picker1');

		$('body').append('

');
		$('body').append($picker);
		$picker.picker({
			externalClickExceptions: ['.test', '#test']
		});

		$picker.find('input').focus().focus();
		$('#test').click();
		equal($picker.hasClass('showing'), true, 'externalClick ignored for specified id');
		$('.test').click();
		equal($picker.hasClass('showing'), true, 'externalClick ignored for specified class');
		$('.innerTest').click();
		equal($picker.hasClass('showing'), true, 'externalClick ignored for child of specified selector');

		$picker.remove();
		$('.test,#test').remove();
	});

	test('explicit option should work as expected', function(){
		var $picker = $(html).find('#picker1');

		$('body').append($picker);
		$picker.picker({
			explicit: true
		});

		$picker.find('input').focus().focus();
		$('body').click();
		equal($picker.hasClass('showing'), true, 'externalClick ignored due to not being an explicit accept/cancel action');
		$picker.find('.picker-accept').click();
		equal($picker.hasClass('showing'), false, 'picker not showing after explicit action');

		$picker.remove();
	});

	test('should disable/enable as expected', function(){
		var $picker = $(html).find('#picker1');
		var $trigger = $picker.find('.picker-trigger');

		$picker.picker('disable');
		equal($picker.hasClass('disabled'), true, 'disabled class properly added to element');
		equal($trigger.attr('disabled'), 'disabled', 'disabled attribute properly added to trigger');

		$picker.picker('enable');
		equal($picker.hasClass('disabled'), false, 'disabled class properly removed from element');
		equal($trigger.attr('disabled'), undefined, 'disabled attribute properly removed from trigger');
	});

	test("should destroy control", function () {
		var $el = $(html).find('#picker1');

		equal(typeof( $el.picker('destroy')) , 'string', 'returns string (markup)');
		equal( $el.parent().length, false, 'control has been removed from DOM');
	});

});
<commit_msg>(picker) adds shown hidden unit tests<commit_after>/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/

define(function(require){
	var $ = require('jquery');
	var html = require('text!test/markup/picker-markup.html!strip');

	require('bootstrap');
	require('fuelux/picker');

	module('Fuel UX Picker');

	test('should be defined on jquery object', function () {
		ok($().find('#picker1').picker(), 'picker method is defined');
	});

	test('should return element', function () {
		var $picker = $(html).find('#picker1');
		ok($picker.picker() === $picker, 'picker should be initialized');
	});

	test('should behave as expected - input', function(){
		var $picker = $(html).find('#picker1');

		$('body').append($picker);
		$picker.picker();
		$picker.on('cancelled.fu.picker', function(e, helpers){
			ok(1===1, 'default action event (cancel) triggered upon external click');
		});

		var $textInputTrigger = $($picker.find('.picker-trigger')[0]);
		var $otherTrigger = $($picker.find('.picker-trigger')[1]);
		$textInputTrigger.focus().focus();
		equal($picker.hasClass('showing'), true, 'picker shows when appropriate');

		$('body').click();
		equal($picker.hasClass('showing'), false, 'picker hides when appropriate');

		$textInputTrigger.click();
		equal($picker.hasClass('showing'), true, 'picker shows when appropriate');

		$textInputTrigger.click();
		equal($picker.hasClass('showing'), true, 'picker continues showing when text input clicked and picker is already showing');

		$otherTrigger.click();
		equal($picker.hasClass('showing'), false, 'picker hides when non-text input clicked and picker is already showing');

		$picker.remove();
	});

	test('should behave as expected - button', function(){
		var $picker = $(html).find('#picker2');

		$picker.picker();
		$picker.on('cancelled.fu.picker', function(e, helpers){
			ok(1===1, 'default action event (cancel) triggered upon external click');
		});
		$('body').append($picker);

		$($picker.find('.picker-trigger')[1]).click();
		equal($picker.hasClass('showing'), true, 'picker shows when appropriate');

		$('body').click();
		equal($picker.hasClass('showing'), false, 'picker hides when appropriate');
		$picker.remove();
	});

	test('show/hide functions should behave as expected', function(){
		var $picker = $(html).find('#picker1');
		$picker.picker();

		$picker.on('shown.fu.picker', function(e, helpers){
			equal($picker.hasClass('showing'), true, 'picker shows when appropriate');
		});

		$picker.on('hidden.fu.picker', function(e, helpers){
			equal($picker.hasClass('showing'), false, 'picker shows when appropriate');
		});

		$picker.picker('show');
		equal($picker.hasClass('showing'), true, 'picker shows when appropriate');

		$picker.picker('hide');
		equal($picker.hasClass('showing'), false, 'picker hides when appropriate');
	});

	test('trigger events should fire as expected', function(){
		var $picker = $(html).find('#picker1');

		$picker.picker();
		$picker.on('accepted.fu.picker', function(e, helpers){
			ok(1===1, 'accept event triggers on accept');
			equal(typeof e, 'object', 'event object passed in accept event');
			equal(typeof helpers, 'object', 'helpers object passed in accept event');
			equal((helpers.contents!==undefined), true, 'helpers object contains correct attributes');
		});
		$picker.on('cancelled.fu.picker', function(e, helpers){
			ok(1===1, 'cancel event triggers on cancel');
			equal(typeof e, 'object', 'event object passed in cancel event');
			equal(typeof helpers, 'object', 'helpers object passed in cancel event');
			equal((helpers.contents!==undefined), true, 'helpers object contains correct attributes');
		});

		$picker.find('input').focus().focus();
		$picker.find('.picker-cancel').click();
		$picker.find('input').focus().focus();
		$picker.find('.picker-accept').click();
	});

	test('onAccept function should be called as expected', function(){
		var $picker = $(html).find('#picker1');

		$picker.picker({
			onAccept: function(helpers){
				ok(1===1, 'onAccept function called on accept');
				equal(typeof helpers, 'object', 'helpers object passed to onAccept function');
				equal((helpers.contents!==undefined), true, 'helpers object contains correct attributes');
				$picker.picker('hide');
			}
		});

		$picker.find('input').focus().focus();
		$picker.find('.picker-accept').click();
	});

	test('onCancel function should be called as expected', function(){
		var $picker = $(html).find('#picker1');

		$picker.picker({
			onCancel: function(helpers){
				ok(1===1, 'onCancel function called on cancel');
				equal(typeof helpers, 'object', 'helpers object passed to onCancel function');
				equal((helpers.contents!==undefined), true, 'helpers object contains correct attributes');
				$picker.picker('hide');
			}
		});

		$picker.find('input').focus().focus();
		$picker.find('.picker-cancel').click();
	});

	test('Enter and exit keys should trigger appropriate response', function(){
		var $picker = $(html).find('#picker1');
		var $input  = $picker.find('input');
		var e = $.Event("keydown");

		$picker.picker({
			onAccept: function(){
				ok(1===1, 'onAccept function called when enter keypress');
			},
			onCancel: function(){
				ok(1===1, 'onCancel function called when exit keypress');
			}
		});

		e.keyCode = 13;
		$input.trigger(e);
		e.keyCode = 27;
		$input.trigger(e);
	});

	test('externalClickExceptions option should work as expected', function(){
		var $picker = $(html).find('#picker1');

		$('body').append('

');
		$('body').append($picker);
		$picker.picker({
			externalClickExceptions: ['.test', '#test']
		});

		$picker.find('input').focus().focus();
		$('#test').click();
		equal($picker.hasClass('showing'), true, 'externalClick ignored for specified id');
		$('.test').click();
		equal($picker.hasClass('showing'), true, 'externalClick ignored for specified class');
		$('.innerTest').click();
		equal($picker.hasClass('showing'), true, 'externalClick ignored for child of specified selector');

		$picker.remove();
		$('.test,#test').remove();
	});

	test('explicit option should work as expected', function(){
		var $picker = $(html).find('#picker1');

		$('body').append($picker);
		$picker.picker({
			explicit: true
		});

		$picker.find('input').focus().focus();
		$('body').click();
		equal($picker.hasClass('showing'), true, 'externalClick ignored due to not being an explicit accept/cancel action');
		$picker.find('.picker-accept').click();
		equal($picker.hasClass('showing'), false, 'picker not showing after explicit action');

		$picker.remove();
	});

	test('should disable/enable as expected', function(){
		var $picker = $(html).find('#picker1');
		var $trigger = $picker.find('.picker-trigger');

		$picker.picker('disable');
		equal($picker.hasClass('disabled'), true, 'disabled class properly added to element');
		equal($trigger.attr('disabled'), 'disabled', 'disabled attribute properly added to trigger');

		$picker.picker('enable');
		equal($picker.hasClass('disabled'), false, 'disabled class properly removed from element');
		equal($trigger.attr('disabled'), undefined, 'disabled attribute properly removed from trigger');
	});

	test("should destroy control", function () {
		var $el = $(html).find('#picker1');

		equal(typeof( $el.picker('destroy')) , 'string', 'returns string (markup)');
		equal( $el.parent().length, false, 'control has been removed from DOM');
	});

});
<|endoftext|>


<commit_before>var assert = chai.assert;

describe("jQuery plugin", function() {

  it("$.fn.serializeObject is setup", function() {
    assert.strictEqual(typeof $.fn.serializeObject, "function");
    assert.strictEqual($.fn.serializeObject, FormSerializer.serializeObject);
  });

  it("$.fn.serializeJSON is setup", function() {
    assert.strictEqual(typeof $.fn.serializeJSON, "function");
    assert.strictEqual($.fn.serializeJSON, FormSerializer.serializeJSON);
  });

  it("exposes FormSerializer.patterns", function() {
    var p = FormSerializer.patterns;
    assert.typeOf(p.validate, "regexp");
    assert.typeOf(p.key,      "regexp");
    assert.typeOf(p.push,     "regexp");
    assert.typeOf(p.fixed,    "regexp");
    assert.typeOf(p.named,    "regexp");
  });

});
<commit_msg>Tests for extending the patterns<commit_after>var assert = chai.assert;

describe("jQuery plugin", function() {

  it("$.fn.serializeObject is setup", function() {
    assert.strictEqual(typeof $.fn.serializeObject, "function");
    assert.strictEqual($.fn.serializeObject, FormSerializer.serializeObject);
  });

  it("$.fn.serializeJSON is setup", function() {
    assert.strictEqual(typeof $.fn.serializeJSON, "function");
    assert.strictEqual($.fn.serializeJSON, FormSerializer.serializeJSON);
  });

  it("exposes FormSerializer.patterns", function() {
    var p = FormSerializer.patterns;
    assert.typeOf(p.validate, "regexp");
    assert.typeOf(p.key,      "regexp");
    assert.typeOf(p.push,     "regexp");
    assert.typeOf(p.fixed,    "regexp");
    assert.typeOf(p.named,    "regexp");
  });

  it("Override pattern using dot notation", function() {
    var form = $('<form><input name="a.b.c" value="d" />');

    assert.deepEqual(form.serializeObject(), {});

    $.extend(FormSerializer.patterns, {
      validate: /^[a-z][a-z0-9_]*(?:\.[a-z0-9_]+)*(?:\[\])?$/i
    });

    assert.deepEqual(form.serializeObject(), { a: { b: { c: 'd' } } });
  });

  it("Override patterns allowing hyphens", function() {
    var form = $('<form><input name="a-b[c]" value="d" />');

    assert.deepEqual(form.serializeObject(), {});

    $.extend(FormSerializer.patterns, {
      validate: /^[a-z][a-z0-9_-]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i,
      key:      /[a-z0-9_-]+|(?=\[\])/gi,
      named:    /^[a-z0-9_-]+$/i
    });

    assert.deepEqual(form.serializeObject(), { 'a-b': { c: 'd' } });
  });

});
<|endoftext|>


<commit_before>require('../init.js');
require("./prep.js");

describe('router.js testing', function(){
  this.timeout(10000);

  // ----------------------------------------------------------------------------------------
  before(function(done){
    // Wait for the config file and init.js have finished loading before starting up the server
    var delayStartup = setInterval(function(){
      if(typeof Item != 'undefined'){
        clearInterval(delayStartup);

        require('../cedilla.js');

        setTimeout(function(){
          console.log('.... pausing to wait for Cedilla startup.');
					done();
				}, 1000);
			}
		}, 500);
	});

	// ----------------------------------------------------------------------------------------
	it('should return the index.html', function(done){
	  var target = 'http://localhost:' + CONFIGS['application']['port'] + '/';

	  console.log('ROUTER: should return the index.ejs from ' + target);

	  sendRequest(url.parse(target), {}, function(status, headers, body){
	    assert.equal(status, 200);
			assert(body.indexOf('Test an OpenUrl') >= 0);

	    done();
	  });
	});

	// ----------------------------------------------------------------------------------------
	it('should call the citation echo service', function(done){
	  // This one gets a decent test of the OpenURL conversion as well
	  var qs = helper.mapToQueryString(helper.itemToMap(fullItem)),
	      target = 'http://localhost:' + CONFIGS['application']['port'] + '/citation?' + qs;

	  console.log('ROUTER: should properly echo back the openURL as a citation item (as JSON)');

		var headers = {'Accept': 'text/json', 'Accept-Charset': 'utf-8'};

	  sendRequest(url.parse(target), headers, function(status, headers, body){
	    assert.equal(status, 200);
	    assert.equal('application/json', headers['content-type']);

	    var json = JSON.parse(body),
					config = CONFIGS['data']['objects'][fullItem.getType()]['attributes'];

	    _.forEach(config, function(attribute){
	      if(attribute == 'original_citation'){
	        assert.equal(qs, json['original_citation']);

	      }else{
	        assert.equal('foo-bar', json[attribute]);
	      }
	    });

	    done();
	  });
	});

});

// ----------------------------------------------------------------------------------------
var sendRequest = function(target, headers, callback){
  var _http = require('http'),
      _response = {},
      _options = {hostname: target.hostname,
                   port: target.port,
                   path: target.path,
                   method: 'GET'};

	if(_.size(headers) > 0){
		_options['headers'] = headers;
	}

  try{
    var _request = _http.request(_options, function(response){
      var _data = '';

      response.on('data', function(chunk){
        _data += chunk;
      });

      // ---------------------------------------------------
      response.on('end', function(){
        callback(response.statusCode, response.headers, _data);
      });
    });

    _request.end();

  }catch(Error){
    console.log('Error connecting to server: ' + Error);
  }

};<commit_msg>Added some error handling to help debug test issue when run on Travis<commit_after>require('../init.js');
require("./prep.js");

describe('router.js testing', function(){
  this.timeout(10000);

  // ----------------------------------------------------------------------------------------
  before(function(done){
    // Wait for the config file and init.js have finished loading before starting up the server
    var delayStartup = setInterval(function(){
      if(typeof Item != 'undefined'){
        clearInterval(delayStartup);

        require('../cedilla.js');

        setTimeout(function(){
          console.log('.... pausing to wait for Cedilla startup.');
					done();
				}, 1000);
			}
		}, 500);
	});

	// ----------------------------------------------------------------------------------------
	it('should return the index.ejs', function(done){
	  var target = 'http://localhost:' + CONFIGS['application']['port'] + '/';

	  console.log('ROUTER: should return the index.ejs from ' + target);

	  sendRequest(url.parse(target), {}, function(status, headers, body){
	    assert.equal(status, 200);
			assert(body.indexOf('Test an OpenUrl') >= 0);

	    done();
	  });
	});

	// ----------------------------------------------------------------------------------------
	it('should call the citation echo service', function(done){
	  // This one gets a decent test of the OpenURL conversion as well
	  var qs = helper.mapToQueryString(helper.itemToMap(fullItem)),
	      target = 'http://localhost:' + CONFIGS['application']['port'] + '/citation?' + qs;

	  console.log('ROUTER: should properly echo back the openURL as a citation item (as JSON)');

		var headers = {'Accept': 'text/json', 'Accept-Charset': 'utf-8'};

	  sendRequest(url.parse(target), headers, function(status, headers, body){
	    assert.equal(status, 200);
	    assert.equal('application/json', headers['content-type']);

	    var json = JSON.parse(body),
					config = CONFIGS['data']['objects'][fullItem.getType()]['attributes'];

	    _.forEach(config, function(attribute){
	      if(attribute == 'original_citation'){
	        assert.equal(qs, json['original_citation']);

	      }else{
	        assert.equal('foo-bar', json[attribute]);
	      }
	    });

	    done();
	  });
	});

});

// ----------------------------------------------------------------------------------------
var sendRequest = function(target, headers, callback){
  var _http = require('http'),
      _response = {},
      _options = {hostname: target.hostname,
                   port: target.port,
                   path: target.path,
                   method: 'GET'};

	if(_.size(headers) > 0){
		_options['headers'] = headers;
	}

  try{
    var _request = _http.request(_options, function(response){
      var _data = '';

      response.on('data', function(chunk){
        _data += chunk;
      });

      // ---------------------------------------------------
      response.on('end', function(){
        callback(response.statusCode, response.headers, _data);
      });
    });

		_request.on('error', function(err){
			console.log(err.message);
			console.log(err.stack);
		});

    _request.end();

  }catch(Error){
    console.log('Error connecting to server: ' + Error);
  }

};<|endoftext|>


<commit_before>"use strict";
var select, xmldsig, DOMParser, XMLSerializer, readXml, assert, XmlCore;

if (typeof module !== "undefined") {
    var config = require("../config");
    var xmljs = require("xml-core");
    select = config.select;
    xmldsig = config.xmldsig;
    DOMParser = config.DOMParser;
    XMLSerializer = config.XMLSerializer;
    assert = config.assert;
    readXml = config.readXml;
    XmlCore = config.XmlCore;
}

describe("Key", function () {

    function isNode() {
        if (typeof window === "undefined") {
            warn("NodeJS");
            return true;
        }
        return false;
    }

    function warn(name) {
        console.warn("    \x1b[33mWARN:\x1b[0m Test is not supported for %s", name);
    }

    context("X509Certificate", () => {

        let cert = null;

        it("Init without params", () => {
            let cert = new xmldsig.X509Certificate();
        });

        it("Init with raw", () => {
            const certBase64 = "MIIEOzCCAyOgAwIBAgIJAKP8xLe3bmRtMA0GCSqGSIb3DQEBCwUAMFoxCzAJBgNVBAYTAkFUMS8wLQYDVQQKEyZSdW5kZnVuayB1bmQgVGVsZWtvbSBSZWd1bGllcnVuZ3MtR21iSDEaMBgGA1UEAxMRVHJ1c3RlZCBMaXN0IENBIDEwHhcNMTQwMTI4MTgzMzI5WhcNMTgwMTI4MTgzMzI5WjBXMQswCQYDVQQGEwJBVDEvMC0GA1UEChMmUnVuZGZ1bmsgdW5kIFRlbGVrb20gUmVndWxpZXJ1bmdzLUdtYkgxFzAVBgNVBAMTDlRydXN0ZWQgTGlzdCA1MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxsSAzrdy4zFiN1bypCT2LZ5O07y9nTJxNlFXERfTzf0zSEtOKXTjxuRQvXvDSfvvar2au9QDuUEdA+jO9NlBFfHfl95ON/gGhQG/NLplVfVB80y4/iX08O43ZuDXcZbBaNdg6M/2qCwflXBakkwaiF7l2kJQyPl+w9hkSi3LBLRfssJOsk5K8VxaILW680gwVX+9BeShXKn5Fr5vde1G1rAKjs6kNtIlrGLWEXyVeAcdDZNKO16MynSMAUeoyz1k74vdWV1/ixrz2DtgeD/rJOnIiDrBqReJzFyZ74iCIsC4EtiIAg5nEah0krWPH6Yhsurqo8zKYDaZAhmJ2hK39wIDAQABo4IBBTCCAQEwHwYDVR0jBBgwFoAUsJT0MPOFfU37Ha8aHJ6ELK/YXBkwHQYDVR0OBBYEFC9vHwsF0o04l9zC+UONiidHmxfJMA4GA1UdDwEB/wQEAwIHgDAWBgNVHSAEDzANMAsGCSooAA8AAQEBADAJBgNVHRMEAjAAMBEGA1UdJQQKMAgGBgQAkTcDADA2BgNVHR8ELzAtMCugKaAnhiVodHRwczovL3d3dy5zaWduYXR1ci5ydHIuYXQvdGxjYTEuY3JsMEEGCCsGAQUFBwEBBDUwMzAxBggrBgEFBQcwAoYlaHR0cHM6Ly93d3cuc2lnbmF0dXIucnRyLmF0L3RsY2ExLmNlcjANBgkqhkiG9w0BAQsFAAOCAQEAfOCwly06iznOF0juUqqXkC0YoQDwVD8OqlevpJkrvAEl+uYTEa0XzBdTCZ+zXdJW6Icgt+pces+RjeFh4tIQgBkwqPWqmnTqw37ysxgqPO0EHXGu/zLdoA2+8TLLsu9csQ+NY4qNfxFXTWoFqlaUC6Af86Tds7QyjVyqOTMjxS8QKqNfI3bLvc9dSH+oi1v2xsFAl/igoKTqWRhad79lroBRKG6SqNR6Y5WqVFMHToZMD+cdulJE6jrKp3hZQrU/8qkKlqTiem6x2NkKAsGZ13+j25P9Pb3x6hh1gV0A1urI1kG+4cj8UDqLhpPXJN/ZtF95WBaioUhiEae3gojXlA==";
            cert = new xmldsig.X509Certificate(XmlCore.Convert.FromBase64(certBase64));
            assert.equal(!!cert.simpl, true);
        });

        it("Serial number", () => {
            assert.equal(!!cert, true, "Certificate is null");

            assert.equal(cert.SerialNumber, "00a3fcc4b7b76e646d");
        });

        it("Issue/Subject names", () => {
            assert.equal(!!cert, true, "Certificate is null");

            assert.equal(cert.Issuer, "C=AT, O=Rundfunk und Telekom Regulierungs-GmbH, CN=Trusted List CA 1");
            assert.equal(cert.Subject, "C=AT, O=Rundfunk und Telekom Regulierungs-GmbH, CN=Trusted List 5");
        });

        context("Thumbprint", () => {
            [
                { digest: "SHA-1", value: "563c51e51976c06bba31040ac048765a7c3b65ce" },
                { digest: "SHA-256", value: "dfb818a07dc65a07bf67ebbf389e2d88728ae907bd60de5710d91cf031df518e" },
                { digest: "SHA-384", value: "51002a5a77917e801fb36f5ded7a311697a6b92d089089ce5300143cac3f95b85a04214b318c3df0a6de2e3b7846407b" },
                { digest: "SHA-512", value: "f4859a1f201e7d146fb709f4cae78c502f04f9579d7983c69b1e364370134d2695557625fdf27fec2dc854ffffa4b844d8b64d57a240ee0722459dd0f9b3874e" },
            ].forEach(v =>
                it(v.digest, done => {
                    assert.equal(!!cert, true, "Certificate is null");

                    cert.Thumbprint(v.digest)
                        .then(hash => {
                            assert.equal(XmlCore.Convert.ToHex(new Uint8Array(hash)), v.value)
                            done();
                        })
                        .catch(done);
                }))
        });

        it("Export key", done => {
            assert.equal(!!cert, true, "Certificate is null");

            assert.equal(!!cert.PublicKey, false);
            cert.exportKey({ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" })
                .then(key => {
                    assert.equal(!!key.algorithm, true);
                    assert.equal(key.type, "public");
                    assert.equal(!!cert.PublicKey, true);
                })
                .then(done, done);
        });

    });

});<commit_msg>Fix test error<commit_after>"use strict";
var select, xmldsig, DOMParser, XMLSerializer, readXml, assert, XmlCore;

if (typeof module !== "undefined") {
    var config = require("../config");
    var xmljs = require("xml-core");
    select = config.select;
    xmldsig = config.xmldsig;
    DOMParser = config.DOMParser;
    XMLSerializer = config.XMLSerializer;
    assert = config.assert;
    readXml = config.readXml;
    XmlCore = config.XmlCore;
}

describe("Key", function () {

    function isNode() {
        if (typeof window === "undefined") {
            warn("NodeJS");
            return true;
        }
        return false;
    }

    function warn(name) {
        console.warn("    \x1b[33mWARN:\x1b[0m Test is not supported for %s", name);
    }

    context("X509Certificate", () => {

        let cert = null;

        it("Init without params", () => {
            let cert = new xmldsig.X509Certificate();
        });

        it("Init with raw", () => {
            const certBase64 = "MIIEOzCCAyOgAwIBAgIJAKP8xLe3bmRtMA0GCSqGSIb3DQEBCwUAMFoxCzAJBgNVBAYTAkFUMS8wLQYDVQQKEyZSdW5kZnVuayB1bmQgVGVsZWtvbSBSZWd1bGllcnVuZ3MtR21iSDEaMBgGA1UEAxMRVHJ1c3RlZCBMaXN0IENBIDEwHhcNMTQwMTI4MTgzMzI5WhcNMTgwMTI4MTgzMzI5WjBXMQswCQYDVQQGEwJBVDEvMC0GA1UEChMmUnVuZGZ1bmsgdW5kIFRlbGVrb20gUmVndWxpZXJ1bmdzLUdtYkgxFzAVBgNVBAMTDlRydXN0ZWQgTGlzdCA1MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxsSAzrdy4zFiN1bypCT2LZ5O07y9nTJxNlFXERfTzf0zSEtOKXTjxuRQvXvDSfvvar2au9QDuUEdA+jO9NlBFfHfl95ON/gGhQG/NLplVfVB80y4/iX08O43ZuDXcZbBaNdg6M/2qCwflXBakkwaiF7l2kJQyPl+w9hkSi3LBLRfssJOsk5K8VxaILW680gwVX+9BeShXKn5Fr5vde1G1rAKjs6kNtIlrGLWEXyVeAcdDZNKO16MynSMAUeoyz1k74vdWV1/ixrz2DtgeD/rJOnIiDrBqReJzFyZ74iCIsC4EtiIAg5nEah0krWPH6Yhsurqo8zKYDaZAhmJ2hK39wIDAQABo4IBBTCCAQEwHwYDVR0jBBgwFoAUsJT0MPOFfU37Ha8aHJ6ELK/YXBkwHQYDVR0OBBYEFC9vHwsF0o04l9zC+UONiidHmxfJMA4GA1UdDwEB/wQEAwIHgDAWBgNVHSAEDzANMAsGCSooAA8AAQEBADAJBgNVHRMEAjAAMBEGA1UdJQQKMAgGBgQAkTcDADA2BgNVHR8ELzAtMCugKaAnhiVodHRwczovL3d3dy5zaWduYXR1ci5ydHIuYXQvdGxjYTEuY3JsMEEGCCsGAQUFBwEBBDUwMzAxBggrBgEFBQcwAoYlaHR0cHM6Ly93d3cuc2lnbmF0dXIucnRyLmF0L3RsY2ExLmNlcjANBgkqhkiG9w0BAQsFAAOCAQEAfOCwly06iznOF0juUqqXkC0YoQDwVD8OqlevpJkrvAEl+uYTEa0XzBdTCZ+zXdJW6Icgt+pces+RjeFh4tIQgBkwqPWqmnTqw37ysxgqPO0EHXGu/zLdoA2+8TLLsu9csQ+NY4qNfxFXTWoFqlaUC6Af86Tds7QyjVyqOTMjxS8QKqNfI3bLvc9dSH+oi1v2xsFAl/igoKTqWRhad79lroBRKG6SqNR6Y5WqVFMHToZMD+cdulJE6jrKp3hZQrU/8qkKlqTiem6x2NkKAsGZ13+j25P9Pb3x6hh1gV0A1urI1kG+4cj8UDqLhpPXJN/ZtF95WBaioUhiEae3gojXlA==";
            cert = new xmldsig.X509Certificate(XmlCore.Convert.FromBase64(certBase64));
            assert.equal(!!cert.simpl, true);
        });

        it("Serial number", () => {
            assert.equal(!!cert, true, "Certificate is null");

            assert.equal(cert.SerialNumber, "11816535815648863341");
        });

        it("Issue/Subject names", () => {
            assert.equal(!!cert, true, "Certificate is null");

            assert.equal(cert.Issuer, "C=AT, O=Rundfunk und Telekom Regulierungs-GmbH, CN=Trusted List CA 1");
            assert.equal(cert.Subject, "C=AT, O=Rundfunk und Telekom Regulierungs-GmbH, CN=Trusted List 5");
        });

        context("Thumbprint", () => {
            [
                { digest: "SHA-1", value: "563c51e51976c06bba31040ac048765a7c3b65ce" },
                { digest: "SHA-256", value: "dfb818a07dc65a07bf67ebbf389e2d88728ae907bd60de5710d91cf031df518e" },
                { digest: "SHA-384", value: "51002a5a77917e801fb36f5ded7a311697a6b92d089089ce5300143cac3f95b85a04214b318c3df0a6de2e3b7846407b" },
                { digest: "SHA-512", value: "f4859a1f201e7d146fb709f4cae78c502f04f9579d7983c69b1e364370134d2695557625fdf27fec2dc854ffffa4b844d8b64d57a240ee0722459dd0f9b3874e" },
            ].forEach(v =>
                it(v.digest, done => {
                    assert.equal(!!cert, true, "Certificate is null");

                    cert.Thumbprint(v.digest)
                        .then(hash => {
                            assert.equal(XmlCore.Convert.ToHex(new Uint8Array(hash)), v.value)
                            done();
                        })
                        .catch(done);
                }))
        });

        it("Export key", done => {
            assert.equal(!!cert, true, "Certificate is null");

            assert.equal(!!cert.PublicKey, false);
            cert.exportKey({ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" })
                .then(key => {
                    assert.equal(!!key.algorithm, true);
                    assert.equal(key.type, "public");
                    assert.equal(!!cert.PublicKey, true);
                })
                .then(done, done);
        });

    });

});<|endoftext|>


<commit_before>m.mount(
    document.body,
    m("div", {
        config : m.route
    }, {
        view : () => m("view")
    })
);
<commit_msg>Unused<commit_after><|endoftext|>