Skip to content

Commit

Permalink
some test cases written
Browse files Browse the repository at this point in the history
  • Loading branch information
izelnakri committed Oct 22, 2017
1 parent 98656e2 commit 7d2a5c0
Show file tree
Hide file tree
Showing 13 changed files with 158 additions and 56 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# What is MemServer?
MemServer is an in-memory database/ORM and http mock server you can run in-browser and node environments. Extremely useful library for fast tests, rapid prototyping, single-file SPA demo deployments.
MemServer is an in-memory database/ORM and http mock server you can run in-browser and node environments. Extremely useful library for fast frontend tests, rapid prototyping, single-file SPA demo deployments.
7 changes: 2 additions & 5 deletions examples/photo-album/memserver/server.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
export default function() {
export default function(Models) {
// this.namespace = '';

this.get('/photos', () => {
return {
authors: [
]
};
return { photos: Models.Photo.findAll() };
});
}
29 changes: 0 additions & 29 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,9 @@ import MemServer from './lib/mem-server.js';
export default MemServer;

// scenario starts

// configurations

// register routes

// let PHOTOS = {
// '10': {
// id: 10,
// src: 'http://media.giphy.com/media/UdqUo8xvEcvgA/giphy.gif'
// },
// '42': {
// id: 42,
// src: 'http://media0.giphy.com/media/Ko2pyD26RdYRi/giphy.gif'
// }
// };

// let server = new window.Pretender(function(){
// this.get('/photos', (request) => {
Expand Down Expand Up @@ -80,23 +68,6 @@ export default MemServer;
// window.$.getJSON('/photos/10');
// window.$.getJSON('/lol');

// setTimeout(() => console.log('done'), 10000);


// export function start() {
//
// // parse all the models
//
//
// // inject all the fixture data to memory
//
// // parse and inject pretender routes
//
// // NOTE: do we need shutdown?
//
// // returns db and routes
// }


// NOTE: namespace addition, this.timing, this.logging, this.passthrough, this.loadFixtures(?)
// this.pretender
43 changes: 38 additions & 5 deletions lib/mem-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,66 @@ if (!fs.existsSync('memserver')) {
throw new Error(chalk.red('/memserver folder doesn\'t exist for this directory!'));
}

if (!fs.existsSync('memserver/server.js')) {
throw new Error(chalk.red('/memserver/server.js doesn\'t exist for this directory!'));
}

const Server = require('./memserver/server.js').default; // NOTE: make this ES6 import
const modelFileNames = fs.readdirSync('memserver/models');
const targetNamespace = ENVIRONMENT_IS_NODE ? global : window;

targetNamespace.MemServer = {
DB: {},
Pretender: {},
Routes: [],
Models: registerModels(modelFileNames),
start(options) {
start(options={ logging: true }) {
this.DB = resetDatabase(this.Models);
delete this.start;
this.Pretender = new window.Pretender(Server); // NOTE: maybe customize it here, make it shorter

const MemServer = chalk.cyan('MemServer');

if (options.logging) {
this.Pretender.handledRequest = function(verb, path, request) {
console.log(MemServer, verb.toUpperCase(), request.url, colorStatusCode(request.status));
console.log(JSON.parse(request.responseText));
}
this.Pretender.passthroughRequest = function(verb, path, request) {
console.log(MemServer, chalk.yellow('[PASSTHROUGH]'), verb, path);
}
}

this.Pretender.unhandledRequest = function(verb, path, request) {
console.log(MemServer, chalk.red('[UNHANDLED REQUEST]', verb, path));
console.log('REQUEST:');
console.log(request);
}

return this;
},
shutdown() {
this.Pretender.shutdown();

return this;
}
};

export default MemServer;
export default targetNamespace.MemServer;

function colorStatusCode(statusCode) {
if (statusCode === 200 || statusCode === 201) {
return chalk.green(statusCode);
}

return chalk.red(statusCode);
}

function registerModels(modelFileNames) {
return modelFileNames.reduce((result, modelFileName) => {
const ModelName = stringUtils.classify(modelFileName.slice(0, -3));

result[ModelName] = require(`./memserver/models/${modelFileName}`).default; // NOTE: make this ES6 import
result[ModelName].modelName = ModelName;

return result;
}, {});
}
Expand All @@ -57,4 +90,4 @@ function resetDatabase(models) {
}, {});
}

// BUILD A CLI
// TODO: BUILD A CLI
File renamed without changes.
32 changes: 16 additions & 16 deletions lib/mem-server/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,6 @@ const targetNamespace = ENVIRONMENT_IS_NODE ? global : window;
export default {
modelName: '',
attributes: [],
insert(options) { // NOTE: what if there is same id?
const models = targetNamespace.MemServer.DB[this.modelName] || [];

// TODO: auto-increment ids
const defaultAttributes = this.attributes.reduce((result, attribute) => {
// TODO: enable functions
result[attribute] = this[attribute];
}, {});

const targetAttributes = Object.assign(defaultAttributes, options);

models.push(targetAttributes);
},
bulkInsert(count, options) {
return Array.from({ length: count }).map(() => this.insert(options));
},
find(id) {
const models = targetNamespace.MemServer.DB[this.modelName] || [];

Expand All @@ -42,6 +26,22 @@ export default {

return models.find((model) => comparison(model, options, keys, 0));
},
insert(options) { // NOTE: what if there is same id?
const models = targetNamespace.MemServer.DB[this.modelName] || [];

// TODO: auto-increment ids
const defaultAttributes = this.attributes.reduce((result, attribute) => {
// TODO: enable functions
result[attribute] = this[attribute];
}, {});

const targetAttributes = Object.assign(defaultAttributes, options);

models.push(targetAttributes);
},
bulkInsert(count, options) {
return Array.from({ length: count }).map(() => this.insert(options));
},
update(record) {
const targetRecord = record.id ? this.find(record.id) : this.findBy({ uuid: record.uuid });

Expand Down
7 changes: 7 additions & 0 deletions lib/mem-server/response.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function(statusCode=200, headers={}, data={}) {
return [
statusCode,
Object.assign({ 'Content-Type': 'application/json' }, headers),
JSON.stringify(data)
];
}
7 changes: 7 additions & 0 deletions lib/mem-server/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default class Server {
constructor(options={}) {

}


}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
},
"devDependencies": {
"jquery": "^3.2.1",
"mocha": "^4.0.1",
"pryjs": "^1.0.3"
},
"@std/esm": {
Expand Down
33 changes: 33 additions & 0 deletions test/mem-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// const assert = require('assert');
//
// describe('MemServer', () => {
// describe('requiring MemServer', () => {
// it('should throw error if /memserver folder doesnt exist', () => {
// // assert.equal(-1, [1,2,3].indexOf(4));
// });
//
// it('should throw error if /memserver/server.js doesnt exist', () => {
// // assert.equal(-1, [1,2,3].indexOf(4));
// });
//
// it('exports not yet started MemServer with right functions, registered Models and empty DB', () => {
//
// });
// });
//
// it('can be started with default options', () => {
//
// });
//
// it('can be started with different options', () => {
//
// });
//
// it('can be shut down', () => {
//
// });
//
// it('can be shut down and started again with correct state', () => {
//
// });
// });
38 changes: 38 additions & 0 deletions test/mem-server.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// const assert = require('assert');
//
// describe('MemServer.Model', () => {
// describe('Query interface', () => {
// it('find() throws without an id', () => {
// assert.equal(-1, [1,2,3].indexOf(4));
// });
//
// it('find(id) works for different models', () => {
// assert.equal(-1, [1,2,3].indexOf(4));
// });
//
// it('findBy() throws without params', () => {
//
// });
//
// it('findBy(options) returns a single model for the options', () => {
//
// });
//
// it('findAll() without parameters returns all the models in the database', () => {
//
// })
//
// it('findAll(options) returns right models in the database', () => {
//
// });
// });
//
// // describe('insert factory interface');
// // describe('update factory interface');
// // describe('destroy factory interface');
//
// // describe('serialization interface');
//
// // describe('complex operations') // multiple edit updates at once
// // describe('custom query interface') // adding new queries etc
// });
Empty file added test/mem-server.response.js
Empty file.
15 changes: 15 additions & 0 deletions test/mem-server.server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// const assert = require('assert');
//
// describe('MemServer.Server', () => {
// // this options work
//
// // NOTE: multiple times:
// // POST works multiple times
// // PUT works
// // DELETE works
// // GET works
//
// // test based one-off mocking works
//
// // passthrough works
// });

0 comments on commit 7d2a5c0

Please sign in to comment.