Skip to content

Commit

Permalink
utils tests commented out
Browse files Browse the repository at this point in the history
  • Loading branch information
izelnakri committed Jul 19, 2019
1 parent 1a40e68 commit cb6cb26
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 77 deletions.
24 changes: 11 additions & 13 deletions lib/mem-server-cjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var chalk$1 = _interopDefault(require('ansi-colors'));
var chalk = _interopDefault(require('ansi-colors'));
var FakeXMLHttpRequest = _interopDefault(require('fake-xml-http-request'));
var RouteRecognizer = _interopDefault(require('route-recognizer'));
require('pretender');
var qs = _interopDefault(require('qs'));
var Inflector = _interopDefault(require('i'));
var stringUtils = _interopDefault(require('ember-cli-string-utils'));

const chalk = require('ansi-colors');

function primaryKeyTypeSafetyCheck(targetPrimaryKeyType, primaryKey, modelName) {
const primaryKeyType = typeof primaryKey;

Expand All @@ -35,7 +33,7 @@ function startServer(Server, options={}) {
window.Pretender.prototype.timing = options.timing;

let pretender = new window.Pretender(function() {
const MemServer = chalk$1.cyan('[MemServer]');
const MemServer = chalk.cyan('[MemServer]');

if (options.logging) {
this.handledRequest = function(verb, path, request) {
Expand All @@ -50,13 +48,13 @@ function startServer(Server, options={}) {
console.log(JSON.parse(request.responseText));
};
this.passthroughRequest = function(verb, path, request) {
console.log(MemServer, chalk$1.yellow('[PASSTHROUGH]'), verb, request.url);
console.log(MemServer, chalk.yellow('[PASSTHROUGH]'), verb, request.url);
};
}

this.unhandledRequest = function(verb, path, request) {
console.log(MemServer, chalk$1.red('[UNHANDLED REQUEST]', verb, path));
console.log(chalk$1.red('UNHANDLED REQUEST WAS:\n'), request);
console.log(MemServer, chalk.red('[UNHANDLED REQUEST]', verb, path));
console.log(chalk.red('UNHANDLED REQUEST WAS:\n'), request);
console.log(request);
};
}, { trackRequests: false });
Expand Down Expand Up @@ -90,12 +88,12 @@ function startServer(Server, options={}) {

function colorStatusCode(statusCode) {
if (statusCode === 200 || statusCode === 201) {
return chalk$1.green(statusCode);
return chalk.green(statusCode);
} else if (statusCode === 404 || statusCode === 204) {
return chalk$1.cyan(statusCode);
return chalk.cyan(statusCode);
}

return chalk$1.red(statusCode);
return chalk.red(statusCode);
}

const { classify } = stringUtils;
Expand Down Expand Up @@ -265,7 +263,7 @@ function getDefaultRouteHandler(verb, path) {
const ResourceModel = targetNamespace$1.MemServer.Models[classify(resourceName)];

if (!ResourceModel) {
throw new Error(chalk$1.red(`[MemServer] ${verb} ${path} route handler cannot be generated automatically: ${classify(resourceName)} is not a valid MemServer.Model, please check that your route name matches the model reference or create a custom handler function`));
throw new Error(chalk.red(`[MemServer] ${verb} ${path} route handler cannot be generated automatically: ${classify(resourceName)} is not a valid MemServer.Model, please check that your route name matches the model reference or create a custom handler function`));
} else if (verb === 'GET') {
if (lastPath.includes(':')) {
return (request) => {
Expand Down Expand Up @@ -353,9 +351,9 @@ function resetDatabase(models, modelFixtureTree) {
const primaryKey = getModelPrimaryKey(model, existingPrimaryKey, modelName);

if (!primaryKey) {
throw new Error(chalk$1.red(`[MemServer] DATABASE ERROR: At least one of your ${modelName} fixtures missing a primary key. Please make sure all your ${modelName} fixtures have either id or uuid primaryKey`));
throw new Error(chalk.red(`[MemServer] DATABASE ERROR: At least one of your ${modelName} fixtures missing a primary key. Please make sure all your ${modelName} fixtures have either id or uuid primaryKey`));
} else if (primaryKeys.includes(model[primaryKey])) {
throw new Error(chalk$1.red(`[MemServer] DATABASE ERROR: Duplication in ${modelName} fixtures with ${primaryKey}: ${model[primaryKey]}`));
throw new Error(chalk.red(`[MemServer] DATABASE ERROR: Duplication in ${modelName} fixtures with ${primaryKey}: ${model[primaryKey]}`));
}

const existingAttributes = targetNamespace$2.MemServer.Models[modelName].attributes;
Expand Down
33 changes: 16 additions & 17 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
const chalk = require('ansi-colors');
import chalk from 'ansi-colors';

module.exports = {
generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
export function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);

return v.toString(16);
});
},
primaryKeyTypeSafetyCheck(targetPrimaryKeyType, primaryKey, modelName) {
const primaryKeyType = typeof primaryKey;
return v.toString(16);
});
}

if (targetPrimaryKeyType === 'id' && (primaryKeyType !== 'number')) {
throw new Error(chalk.red(`[MemServer] ${modelName} model primaryKey type is 'id'. Instead you've tried to enter id: ${primaryKey} with ${primaryKeyType} type`));
} else if (targetPrimaryKeyType === 'uuid' && (primaryKeyType !== 'string')) {
throw new Error(chalk.red(`[MemServer] ${modelName} model primaryKey type is 'uuid'. Instead you've tried to enter uuid: ${primaryKey} with ${primaryKeyType} type`));
}
export function primaryKeyTypeSafetyCheck(targetPrimaryKeyType, primaryKey, modelName) {
const primaryKeyType = typeof primaryKey;

return targetPrimaryKeyType;
if (targetPrimaryKeyType === 'id' && (primaryKeyType !== 'number')) {
throw new Error(chalk.red(`[MemServer] ${modelName} model primaryKey type is 'id'. Instead you've tried to enter id: ${primaryKey} with ${primaryKeyType} type`));
} else if (targetPrimaryKeyType === 'uuid' && (primaryKeyType !== 'string')) {
throw new Error(chalk.red(`[MemServer] ${modelName} model primaryKey type is 'uuid'. Instead you've tried to enter uuid: ${primaryKey} with ${primaryKeyType} type`));
}
};

return targetPrimaryKeyType;
}
34 changes: 16 additions & 18 deletions model.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var util = _interopDefault(require('util'));
var chalk$1 = _interopDefault(require('ansi-colors'));
var chalk = _interopDefault(require('ansi-colors'));
var Inflector = _interopDefault(require('i'));
var emberCliStringUtils = require('ember-cli-string-utils');

const chalk = require('ansi-colors');

function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
Expand Down Expand Up @@ -45,7 +43,7 @@ function model(options) {
},
find(param) {
if (!param) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.find(id) cannot be called without a valid id`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.find(id) cannot be called without a valid id`));
} else if (Array.isArray(param)) {
const models = Array.from(targetNamespace.MemServer.DB[this.modelName] || []);

Expand All @@ -55,7 +53,7 @@ function model(options) {
return foundModel ? result.concat([foundModel]) : result;
}, []);
} else if (typeof param !== 'number') {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.find(id) cannot be called without a valid id`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.find(id) cannot be called without a valid id`));
}

const models = Array.from(targetNamespace.MemServer.DB[this.modelName] || []);
Expand All @@ -64,7 +62,7 @@ function model(options) {
},
findBy(options) {
if (!options) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.findBy(id) cannot be called without a parameter`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.findBy(id) cannot be called without a parameter`));
}

const keys = Object.keys(options);
Expand Down Expand Up @@ -112,7 +110,7 @@ function model(options) {
const existingRecord = target.id ? this.find(target.id) : this.findBy({ uuid: target.uuid });

if (existingRecord) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName} ${this.primaryKey} ${target[this.primaryKey]} already exists in the database! ${this.modelName}.insert(${util.inspect(options)}) fails`));
throw new Error(chalk.red(`[MemServer] ${this.modelName} ${this.primaryKey} ${target[this.primaryKey]} already exists in the database! ${this.modelName}.insert(${util.inspect(options)}) fails`));
}

Object.keys(target)
Expand All @@ -125,20 +123,20 @@ function model(options) {
},
update(record) {
if (!record || (!record.id && !record.uuid)) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.update(record) requires id or uuid primary key to update a record`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.update(record) requires id or uuid primary key to update a record`));
}

const targetRecord = record.id ? this.find(record.id) : this.findBy({ uuid: record.uuid });

if (!targetRecord) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.update(record) failed because ${this.modelName} with ${this.primaryKey}: ${record[this.primaryKey]} does not exist`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.update(record) failed because ${this.modelName} with ${this.primaryKey}: ${record[this.primaryKey]} does not exist`));
}

const recordsUnknownAttribute = Object.keys(record)
.find((attribute) => !this.attributes.includes(attribute));

if (recordsUnknownAttribute) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.update ${this.primaryKey}: ${record[this.primaryKey]} fails, ${this.modelName} model does not have ${recordsUnknownAttribute} attribute to update`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.update ${this.primaryKey}: ${record[this.primaryKey]} fails, ${this.modelName} model does not have ${recordsUnknownAttribute} attribute to update`));
}

return Object.assign(targetRecord, record);
Expand All @@ -147,15 +145,15 @@ function model(options) {
const models = targetNamespace.MemServer.DB[this.modelName] || [];

if (models.length === 0) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName} has no records in the database to delete. ${this.modelName}.delete(${util.inspect(record)}) failed`));
throw new Error(chalk.red(`[MemServer] ${this.modelName} has no records in the database to delete. ${this.modelName}.delete(${util.inspect(record)}) failed`));
} else if (!record) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.delete(model) model object parameter required to delete a model`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.delete(model) model object parameter required to delete a model`));
}

const targetRecord = record.id ? this.find(record.id) : this.findBy({ uuid: record.uuid });

if (!targetRecord) {
throw new Error(chalk$1.red(`[MemServer] Could not find ${this.modelName} with ${this.primaryKey} ${record[this.primaryKey]} to delete. ${this.modelName}.delete(${util.inspect(record)}) failed`));
throw new Error(chalk.red(`[MemServer] Could not find ${this.modelName} with ${this.primaryKey} ${record[this.primaryKey]} to delete. ${this.modelName}.delete(${util.inspect(record)}) failed`));
}

const targetIndex = models.indexOf(targetRecord);
Expand All @@ -166,13 +164,13 @@ function model(options) {
},
embed(relationship) { // EXAMPLE: { comments: Comment }
if (typeof relationship !== 'object' || relationship.modelName) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.embed(relationshipObject) requires an object as a parameter: { relationshipKey: $RelationshipModel }`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.embed(relationshipObject) requires an object as a parameter: { relationshipKey: $RelationshipModel }`));
}

const key = Object.keys(relationship)[0];

if (!relationship[key]) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.embed() fails: ${key} Model reference is not a valid. Please put a valid $ModelName to ${this.modelName}.embed()`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.embed() fails: ${key} Model reference is not a valid. Please put a valid $ModelName to ${this.modelName}.embed()`));
}

return Object.assign(this.embedReferences, relationship);
Expand All @@ -189,7 +187,7 @@ function model(options) {
},
serialize(object) { // NOTE: add links object ?
if (Array.isArray(object)) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.serialize(object) expects an object not an array. Use ${this.modelName}.serializer(data) for serializing array of records`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.serialize(object) expects an object not an array. Use ${this.modelName}.serializer(data) for serializing array of records`));
}

const objectWithAllAttributes = this.attributes.reduce((result, attribute) => {
Expand All @@ -209,15 +207,15 @@ function model(options) {
},
getRelationship(parentObject, relationshipName, relationshipModel) {
if (Array.isArray(parentObject)) {
throw new Error(chalk$1.red(`[MemServer] ${this.modelName}.getRelationship expects model input to be an object not an array`));
throw new Error(chalk.red(`[MemServer] ${this.modelName}.getRelationship expects model input to be an object not an array`));
}

const targetRelationshipModel = relationshipModel ||
targetNamespace.MemServer.Models[emberCliStringUtils.classify(singularize(relationshipName))];
const hasManyRelationship = pluralize(relationshipName) === relationshipName;

if (!targetRelationshipModel) {
throw new Error(chalk$1.red(`[MemServer] ${relationshipName} relationship could not be found on ${this.modelName} model. Please put the ${relationshipName} Model object as the third parameter to ${this.modelName}.getRelationship function`));
throw new Error(chalk.red(`[MemServer] ${relationshipName} relationship could not be found on ${this.modelName} model. Please put the ${relationshipName} Model object as the third parameter to ${this.modelName}.getRelationship function`));
} else if (hasManyRelationship) {
if (parentObject.id) {
const hasManyIDRecords = targetRelationshipModel.findAll({
Expand Down
30 changes: 30 additions & 0 deletions test/cli/memserver-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import test from 'ava';
// import { generateUUID, primaryKeyTypeSafetyCheck } from '../../lib/utils';

test('memserver/lib/utils exports generateUUID correctly', (t) => {
t.is(true, true);
// t.plan(21);

// const UUIDs = Array.from({ length: 10 }).map(() => generateUUID());

// t.is(UUIDs.length, 10);

// UUIDs.forEach((currentUUID) => {
// t.is(currentUUID.length, 36);
// t.is(UUIDs.filter((uuid) => uuid === currentUUID).length, 1);
// });
});

// test('memserver/lib/utils exports primaryKeyTypeSafetyCheck correctly', (t) => {
// t.plan(6);

// const error = t.throws(() => primaryKeyTypeSafetyCheck('id', '22', 'Photo'), Error);

// t.true(/\[MemServer\] Photo model primaryKey type is 'id'. Instead you've tried to enter id: 22 with string type/.test(error.message));
// t.notThrows(() => primaryKeyTypeSafetyCheck('id', 22, 'Photo'));

// const secondError = t.throws(() => primaryKeyTypeSafetyCheck('uuid', 22, 'PhotoComment'), Error);

// t.true(/\[MemServer\] PhotoComment model primaryKey type is 'uuid'. Instead you've tried to enter uuid: 22 with number type/.test(secondError.message));
// t.notThrows(() => primaryKeyTypeSafetyCheck('uuid', '166a435d-ad3d-4662-9f6f-04373280a38b', 'PhotoComment'));
// });
29 changes: 0 additions & 29 deletions test/memserver-utils.js

This file was deleted.

0 comments on commit cb6cb26

Please sign in to comment.