Skip to content

Commit

Permalink
more test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
yawetse committed Mar 27, 2017
1 parent 8115411 commit db4358d
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 22 deletions.
2 changes: 1 addition & 1 deletion example/sampledb.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"filename":"/Users/yawetse/Developer/github/typesettin/lowkie/example/sampledb.json","collections":[{"name":"kittens","data":[],"idIndex":[201,202,208,209,210,211],"binaryIndices":{},"constraints":null,"uniqueNames":[],"transforms":{},"objType":"kittens","dirty":true,"cachedIndex":null,"cachedBinaryIndex":null,"cachedData":null,"adaptiveBinaryIndices":true,"transactional":false,"cloneObjects":false,"cloneMethod":"parse-stringify","asyncListeners":false,"disableChangesApi":true,"autoupdate":false,"ttl":null,"maxId":211,"DynamicViews":[],"events":{"insert":[null],"update":[null],"pre-insert":[],"pre-update":[],"close":[],"flushbuffer":[],"error":[],"delete":[null],"warning":[null]},"changes":[]}],"databaseVersion":1.1,"engineVersion":1.1,"autosave":false,"autosaveInterval":5000,"autosaveHandle":null,"throttledSaves":true,"options":{"serializationMethod":"normal","destructureDelimiter":"$<\n"},"persistenceMethod":"fs","persistenceAdapter":null,"verbose":false,"events":{"init":[null],"loaded":[],"flushChanges":[],"close":[],"changes":[],"warning":[]},"ENV":"NODEJS"}
{"filename":"/Users/yawetse/Developer/github/typesettin/lowkie/example/sampledb.json","collections":[{"name":"kittens","data":[],"idIndex":[201,217,218],"binaryIndices":{},"constraints":null,"uniqueNames":[],"transforms":{},"objType":"kittens","dirty":true,"cachedIndex":null,"cachedBinaryIndex":null,"cachedData":null,"adaptiveBinaryIndices":true,"transactional":false,"cloneObjects":false,"cloneMethod":"parse-stringify","asyncListeners":false,"disableChangesApi":true,"autoupdate":false,"ttl":null,"maxId":218,"DynamicViews":[],"events":{"insert":[null],"update":[null],"pre-insert":[],"pre-update":[],"close":[],"flushbuffer":[],"error":[],"delete":[null],"warning":[null]},"changes":[]}],"databaseVersion":1.1,"engineVersion":1.1,"autosave":false,"autosaveInterval":5000,"autosaveHandle":null,"throttledSaves":true,"options":{"serializationMethod":"normal","destructureDelimiter":"$<\n"},"persistenceMethod":"fs","persistenceAdapter":null,"verbose":false,"events":{"init":[null],"loaded":[],"flushChanges":[],"close":[],"changes":[],"warning":[]},"ENV":"NODEJS"}
7 changes: 2 additions & 5 deletions example/sampledb.json.0
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
{"name":"king0.2726792766487611","entitytype":"kat","_id":"fbd8080a9272ecaa15d1bb6d0f4b3314","meta":{"revision":0,"created":1490576236063,"version":0},"$loki":201}
{"name":"prince0.8735373934837287","entitytype":"kat","description":10983021,"_id":"d48e3dde06a8e758b6afa6bf2d103cb2","meta":{"revision":0,"created":1490576507732,"version":0},"$loki":202}
{"name":"queen0.8482004465847226","entitytype":"kat","description":10983021,"_id":"80a605aae9ecb2599b176f1e92dc64e8","meta":{"revision":0,"created":1490632925062,"version":0},"$loki":208}
{"name":"jester0.26873625459623796","entitytype":"kat","_id":"fdf9c37302d3a58538bea96d72584632","meta":{"revision":0,"created":1490632930071,"version":0},"$loki":209}
{"entitytype":"kat","description":10983021,"_id":"df16c9fd6451e0e4f35f4fa5dd77346f","meta":{"revision":0,"created":1490640675393,"version":0},"$loki":210}
{"entitytype":"kat","description":10983021,"_id":"c541b743b58a5db31cb8a9ea542048b4","meta":{"revision":0,"created":1490640683658,"version":0},"$loki":211}
{"name":"king0.6852135342821353","entitytype":"kat","description":10983021,"_id":"78ecce7223a8d5d1b4630d3a5266c0c2","meta":{"revision":0,"created":1490651242448,"version":0},"$loki":217}
{"name":"jester0.4021992800877401","entitytype":"kat","_id":"98ae5dfccf9835e5c5a952bd86328c1c","meta":{"revision":0,"created":1490651247456,"version":0},"$loki":218}
40 changes: 25 additions & 15 deletions lib/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,35 @@ const defaultDBPath = path.resolve(path.join(process.cwd(), './test.db.json'));
* @param {object} [options={}]
* @returns {Promise}
*/
function connect(dbpath = defaultDBPath, options = {}) {
function connect(dbpath = defaultDBPath, options = {}, lowkieConfig = {}) {
this.config = Object.assign(this.config, lowkieConfig);
const dbname = path.resolve(dbpath);
const adapter = new lokiFSAdapter(dbname);
const adapter = (this.config.adapterType === 'file')
? { adapter: new lokiFSAdapter(dbname), }
: {};
const lokiDBOptions = Object.assign({
autosave: true,
autosaveInterval: 5000, // 5 seconds
adapter,
}, options);
},
adapter, options);
const t = setImmediate(() => {
this.connection.emit('connecting', { dbname, options, });
clearImmediate(t);
});
const db = new loki(dbname, lokiDBOptions);
const ensureAdapterFilePromise = () => {
return (this.config.adapterType === 'file')
? new Promise((resolve, reject) => {
fs.ensureFile(dbname, (err) => {
if (err) reject(err);
else resolve(true);
});
})
: Promise.resolve();
if (!this.config.adapterType) {
throw new Error('Invalid Adapter Type');
} else {
return (this.config.adapterType === 'file')
? new Promise((resolve, reject) => {
fs.ensureFile(dbname, (err) => {
if (err) reject(err);
else resolve(true);
});
})
: Promise.resolve();
}
};
this.db = db;
this.connections.set('default', db);
Expand All @@ -45,7 +52,7 @@ function connect(dbpath = defaultDBPath, options = {}) {
.then(() => {
fs.readJSON(dbname, (err, dbdata) => {
clearImmediate(t);
if (err || (dbdata && !dbdata.collections.length) ) {
if (this.config.overwriteInvalidJSON && err || ( dbdata && (!dbdata.collections || !dbdata.collections.length)) ) {
db.saveDatabase((err) => {
if (err) {
reject(err);
Expand All @@ -54,6 +61,8 @@ function connect(dbpath = defaultDBPath, options = {}) {
resolve(db);
}
});
} else if (err) {
reject (err);
} else{
db.loadDatabase({}, (err) => {
if (err) {
Expand All @@ -65,9 +74,10 @@ function connect(dbpath = defaultDBPath, options = {}) {
});
}
});

})
.catch(reject);
.catch((e) => {
reject(e);
});
});
} catch (e) {
this.connection.emit('connectionError', e, { dbname, options, });
Expand Down
1 change: 1 addition & 0 deletions lib/lowkieClass.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class lowkie {
adapterType: 'file',
debug: false,
strictSchemas: true,
overwriteInvalidJSON:true,
}, options);
this.connections = new Map();
this.db = undefined;
Expand Down
1 change: 1 addition & 0 deletions test/mock/invalid.db.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions test/mock/invalid.db.jsonfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INVALID
94 changes: 94 additions & 0 deletions test/unit/connect_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const fs = require('fs-extra');
const expect = require('chai').expect;
const testConnectDBPath = path.join(__dirname, '../mock/connecttestdb.json');
const removeTestDB = require('../util/removeTestDB');
const invalidJSONPATH = path.join(__dirname, '../mock/invalid.db.json');
const invalidFILEPATH = path.join(__dirname, '../mock/invalid.db.jsonfile');
let lowkie = require('../../index');
let lowkieConnectTest = require('../../lib/connect');
let lowkieClass = require('../../lib/lowkieClass');
Expand Down Expand Up @@ -55,6 +57,17 @@ describe('Connect', function () {
done();
});
});
it('should connect and load an existing db filepath', (done) => {
let newLOWKIE = new lowkieClass({});
let lowkieConnect = lowkieConnectTest.bind(newLOWKIE);
lowkieConnect(testConnectDBPath)
.then((db) => {
expect(db).to.be.an('object');
expect(db).to.eql(newLOWKIE.db);
done();
})
.catch(done);
});
it('should emit connected event once connected to a new db filepath', (done) => {
let newLOWKIE = new lowkieClass({});
let lowkieConnect = lowkieConnectTest.bind(newLOWKIE);
Expand All @@ -66,8 +79,89 @@ describe('Connect', function () {
done();
});
});
it('should allow for custom lowkie configurations', (done) => {
let newLOWKIE = new lowkieClass({});
let lowkieConnect = lowkieConnectTest.bind(newLOWKIE);
let throwawayfilepath = path.join(__dirname, '../mock/connecttestthrowaway2.json');
lowkieConnect(throwawayfilepath, {}, { adapterType: 'default', })
.then(() => {
// console.log('newLOWKIE.config', newLOWKIE.config);
expect(newLOWKIE.config.adapterType).to.eql('default');
removeTestDB(throwawayfilepath);
done();
})
.catch(done);
});
it('should allow handle invalid database json', (done) => {
let newLOWKIE = new lowkieClass({});
let lowkieConnect = lowkieConnectTest.bind(newLOWKIE);
let throwawayfilepath = invalidJSONPATH;
lowkieConnect(throwawayfilepath, {}, { adapterType: 'default', }, {
overwriteInvalidJSON:false,
})
.then(() => {
// console.log('newLOWKIE.config', newLOWKIE.config);
expect(newLOWKIE.config.adapterType).to.eql('default');
done();
})
.catch(e => {
console.log(e);
done();
});
});
it('should throw error handling invalid database file', (done) => {
let newLOWKIE = new lowkieClass({});
let lowkieConnect = lowkieConnectTest.bind(newLOWKIE);
let throwawayfilepath = invalidFILEPATH;
lowkieConnect(throwawayfilepath, {}, {
overwriteInvalidJSON:false,
})
.then(() => {
console.log('resoved here')
// console.log('newLOWKIE.config', newLOWKIE.config);
done();
})
.catch(e => {
expect(e).to.be.instanceof(Error);
done();
});
});
// it('should emit connection error', (done) => {
// let newLOWKIE = new lowkieClass({});
// let lowkieConnect = lowkieConnectTest.bind(newLOWKIE);
// let throwawayfilepath = invalidFILEPATH;
// let nameCounter = 0;
// let configProxy = new Proxy({
// overwriteInvalidJSON: false,
// adapterType: 'default',
// }, {
// get: function (target, name) {
// if (name === 'adapterType') {
// nameCounter++;
// }
// if (nameCounter > 0) {
// // throw new Error('testing error handling');
// console.log({ target, name, nameCounter });
// return new Error('testing error handling');
// } else {
// console.log({ target, name, nameCounter });
// return target[ name ];
// }
// },
// });
// lowkieConnect('/private', {}, configProxy)
// .catch((e) => {
// console.log(e);//do nothing, wait for event
// // done();
// });
// newLOWKIE.connection.once('connectionError', (e) => {
// expect(e).to.be.instanceOf(Error);
// done();
// });
// });
});
after('remove test schema db', () => {
removeTestDB(testConnectDBPath, true);
fs.outputJsonSync(invalidJSONPATH, {});
});
});
2 changes: 1 addition & 1 deletion test/unit/model_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ describe('Model', function () {
it('should register models globally', () => {
let goodModelSchema = lowkie.Schema(testUserModelScheme);
lowkie.model('goodModel', goodModelSchema);
console.log(lowkie.models);
// console.log(lowkie.models);
expect(Object.keys(lowkie.models)).to.have.length.above(0);
});
});
Expand Down

0 comments on commit db4358d

Please sign in to comment.