From e2c53b59cefb5e5478163cb303b2ed7e84fa7115 Mon Sep 17 00:00:00 2001 From: Lovell Fuller Date: Mon, 1 Jun 2015 14:48:57 +0100 Subject: [PATCH] Tighten constructor and quality param checks #221 --- index.js | 6 ++++-- test/unit/io.js | 48 +++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/index.js b/index.js index dad2db7d..f933261c 100755 --- a/index.js +++ b/index.js @@ -87,9 +87,11 @@ var Sharp = function(input) { } else if (typeof input === 'object' && input instanceof Buffer) { // input=buffer this.options.bufferIn = input; - } else { + } else if (typeof input === 'undefined') { // input=stream this.options.streamIn = true; + } else { + throw new Error('Unsupported input ' + typeof input); } return this; }; @@ -394,7 +396,7 @@ Sharp.prototype.sequentialRead = function(sequentialRead) { }; Sharp.prototype.quality = function(quality) { - if (!Number.isNaN(quality) && quality >= 1 && quality <= 100) { + if (!Number.isNaN(quality) && quality >= 1 && quality <= 100 && quality % 1 === 0) { this.options.quality = quality; } else { throw new Error('Invalid quality (1 to 100) ' + quality); diff --git a/test/unit/io.js b/test/unit/io.js index c9f28057..52c35104 100755 --- a/test/unit/io.js +++ b/test/unit/io.js @@ -221,6 +221,29 @@ describe('Input/output', function() { }); }); + describe('Fail for unsupported input', function() { + it('Numeric', function() { + assert.throws(function() { + sharp(1); + }); + }); + it('Boolean', function() { + assert.throws(function() { + sharp(true); + }); + }); + it('Empty Object', function() { + assert.throws(function() { + sharp({}); + }); + }); + it('Error Object', function() { + assert.throws(function() { + sharp(new Error()); + }); + }); + }); + it('Promises/A+', function(done) { sharp(fixtures.inputJpg).resize(320, 240).toBuffer().then(function(data) { sharp(data).toBuffer(function(err, data, info) { @@ -252,15 +275,22 @@ describe('Input/output', function() { }); }); - it('Invalid quality', function(done) { - var isValid = true; - try { - sharp(fixtures.inputJpg).quality(-1); - } catch (err) { - isValid = false; - } - assert.strictEqual(false, isValid); - done(); + describe('Invalid quality', function() { + it('Negative integer', function() { + assert.throws(function() { + sharp(fixtures.inputJpg).quality(-1); + }); + }); + it('Non integral', function() { + assert.throws(function() { + sharp(fixtures.inputJpg).quality(88.2); + }); + }); + it('String', function() { + assert.throws(function() { + sharp(fixtures.inputJpg).quality('test'); + }); + }); }); it('Progressive JPEG image', function(done) {