Skip to content

Commit a9bf001

Browse files
test(*): add more model format checks & corresponding tests
references #63 Co-authored-by: Rachna <[email protected]>
1 parent bfa6e7c commit a9bf001

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

test/bm25-vectorizer-specs.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,9 +297,14 @@ describe( 'bm25-vectorizer', function () {
297297
} );
298298

299299
it( 'should throw error if invalid model is used', function () {
300+
// Incorrect JSON.
300301
expect( () => v3.loadModel('[]') ).to.throw( 'wink-nlp: invalid model format/version' );
302+
// No fields.
301303
expect( () => v3.loadModel('{}') ).to.throw( 'wink-nlp: invalid model format/version' );
304+
// Incorrect UID.
302305
expect( () => v3.loadModel( JSON.stringify( { uid: 'junk' } ) ) ).to.throw( 'wink-nlp: invalid model format/version' );
306+
// Missing required fields.
307+
expect( () => v3.loadModel( JSON.stringify( { uid: 'WinkNLP-BM25Vectorizer-Model/1.0.0', 0: 0, 1: 1, 2: 2, 3: 3, 4: 4 } ) ) ).to.throw( 'wink-nlp: invalid model format/version' );
303308
} );
304309
} );
305310
} );

utilities/bm25-vectorizer.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,9 @@ var bm25Vectorizer = function ( config ) {
316316
* @return {void} Nothing!
317317
*/
318318
methods.loadModel = function ( json ) {
319+
// Used to check presence of required fields; `uid` is checked separately.
320+
const modelFields = [ 'docId', 'tf', 'idf', 'terms', 'sumOfAllDLs' ];
321+
319322
let model;
320323

321324
if ( docId > 0 ) throw Error( 'wink-nlp: can not load model after learning.' );
@@ -327,11 +330,19 @@ var bm25Vectorizer = function ( config ) {
327330
}
328331

329332
if ( helper.isObject( model ) && ( Object.keys( model ).length === 6 ) && ( model.uid === 'WinkNLP-BM25Vectorizer-Model/1.0.0' ) ) {
333+
// Check presence of all required fields.
334+
modelFields.forEach( ( f ) => {
335+
if ( model[ f ] === undefined ) throw Error( 'wink-nlp: invalid model format/version' );
336+
} );
337+
338+
// All good, set fields.
330339
docId = model.docId;
331340
tf = model.tf;
332341
idf = model.idf;
333342
terms = model.terms;
334343
sumOfAllDLs = model.sumOfAllDLs;
344+
345+
// To prevent further learning.
335346
weightsComputed = true;
336347
} else {
337348
throw Error( 'wink-nlp: invalid model format/version' );

0 commit comments

Comments
 (0)