loopback-datasource-juggler/test/common_test.js

564 lines
18 KiB
JavaScript
Raw Normal View History

2011-10-03 17:18:44 +00:00
var Schema = require('../index').Schema;
var Text = Schema.Text;
require('./spec_helper').init(exports);
var schemas = {
/*
riak: {},
2011-10-05 20:33:07 +00:00
*/
2011-10-03 17:18:44 +00:00
sequelize: {
database: 'sequ-test',
username: 'root'
2011-10-05 20:33:07 +00:00
},
2011-10-23 19:43:53 +00:00
mysql: {
2012-01-19 20:16:30 +00:00
database: 'myapp_test',
2011-10-23 19:43:53 +00:00
username: 'root'
},
2012-01-30 15:43:45 +00:00
postgres: {
2012-01-30 13:33:45 +00:00
database: 'myapp_test',
username: 'postgres'
2012-01-10 13:26:24 +00:00
},
2012-01-30 15:43:45 +00:00
sqlite3: {
database: ':memory:'
},
2011-10-03 17:18:44 +00:00
neo4j: { url: 'http://localhost:7474/' },
mongoose: { url: 'mongodb://travis:test@localhost:27017/myapp' },
// mongoose: { database: 'test' },
2011-10-03 17:18:44 +00:00
redis: {},
memory: {}
};
2011-10-16 17:21:08 +00:00
var specificTest = getSpecificTests();
2011-10-03 17:18:44 +00:00
Object.keys(schemas).forEach(function (schemaName) {
if (process.env.ONLY && process.env.ONLY !== schemaName) return;
if (process.env.EXCEPT && process.env.EXCEPT === schemaName) return;
2011-10-03 17:18:44 +00:00
context(schemaName, function () {
var schema = new Schema(schemaName, schemas[schemaName]);
// schema.log = console.log;
2011-10-03 17:18:44 +00:00
testOrm(schema);
2011-10-16 17:21:08 +00:00
if (specificTest[schemaName]) specificTest[schemaName](schema);
2011-10-03 17:18:44 +00:00
});
});
function testOrm(schema) {
2011-10-05 14:47:26 +00:00
var Post, User;
2011-10-03 17:18:44 +00:00
var start = Date.now();
it('should define class', function (test) {
2011-10-05 14:47:26 +00:00
User = schema.define('User', {
2011-10-03 17:18:44 +00:00
name: String,
bio: Text,
approved: Boolean,
joinedAt: Date,
2011-12-11 11:01:23 +00:00
age: Number,
2011-12-11 19:25:13 +00:00
passwd: String
2011-10-03 17:18:44 +00:00
});
Post = schema.define('Post', {
2011-10-16 17:21:08 +00:00
title: { type: String, length: 255, index: true },
2011-10-03 17:18:44 +00:00
content: { type: Text },
date: { type: Date, default: Date.now, index: true },
2011-10-03 17:18:44 +00:00
published: { type: Boolean, default: false }
});
2011-11-19 08:58:49 +00:00
Post.validateAsync('title', function (err, done) {
process.nextTick(done);
});
2011-10-05 14:47:26 +00:00
User.hasMany(Post, {as: 'posts', foreignKey: 'userId'});
// creates instance methods:
// user.posts(conds)
2011-10-15 15:57:35 +00:00
// user.posts.build(data) // like new Post({userId: user.id});
// user.posts.create(data) // build and save
// user.posts.find
2011-10-05 14:47:26 +00:00
2011-12-09 15:23:29 +00:00
// User.hasOne('latestPost', {model: Post, foreignKey: 'postId'});
// User.hasOne(Post, {as: 'latestPost', foreignKey: 'latestPostId'});
// creates instance methods:
// user.latestPost()
// user.latestPost.build(data)
// user.latestPost.create(data)
2011-10-05 14:47:26 +00:00
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
// creates instance methods:
// post.author(callback) -- getter when called with function
// post.author() -- sync getter when called without params
// post.author(user) -- setter when called with object
2011-10-03 17:18:44 +00:00
var user = new User;
test.ok(User instanceof Function);
// class methods
test.ok(User.find instanceof Function);
test.ok(User.create instanceof Function);
// instance methods
test.ok(user.save instanceof Function);
schema.automigrate(function (err) {
if (err) {
console.log('Error while migrating');
console.log(err);
} else {
test.done();
}
});
});
it('should initialize object properly', function (test) {
2011-10-11 19:51:32 +00:00
var hw = 'Hello word',
now = Date.now(),
post = new Post({title: hw}),
anotherPost = Post({title: 'Resig style constructor'});
2011-10-11 19:51:32 +00:00
2011-10-03 17:18:44 +00:00
test.equal(post.title, hw);
test.ok(!post.propertyChanged('title'));
post.title = 'Goodbye, Lenin';
test.equal(post.title_was, hw);
test.ok(post.propertyChanged('title'));
2011-10-11 19:51:32 +00:00
test.strictEqual(post.published, false);
test.ok(post.date >= now);
test.ok(post.isNewRecord());
test.ok(anotherPost instanceof Post);
test.ok(anotherPost.title, 'Resig style constructor');
2011-10-03 17:18:44 +00:00
test.done();
});
it('should be expoted to JSON', function (test) {
2011-10-11 19:51:32 +00:00
test.equal(JSON.stringify(new Post({id: 1, title: 'hello, json', date: 1})),
'{"id":1,"title":"hello, json","content":null,"date":1,"published":false,"userId":null}');
2011-10-03 17:18:44 +00:00
test.done();
});
it('should create object', function (test) {
Post.create(function (err, post) {
if (err) throw err;
2012-01-10 15:43:32 +00:00
test.ok(post.id, 'Id present');
2011-10-03 17:18:44 +00:00
test.ok(!post.title, 'Title is blank');
Post.exists(post.id, function (err, exists) {
if (err) throw err;
test.ok(exists);
test.done();
});
});
});
2012-01-27 08:48:37 +00:00
it('should create object without callback', function (test) {
var uniqueTitle = 'Unique title ' + Date.now();
Post.create({title: uniqueTitle});
setTimeout(delayedCallback, 100);
function delayedCallback() {
Post.all({where: {title: uniqueTitle}}, function (err, posts) {
test.equal(posts.length, 1);
test.done();
});
}
});
2011-10-03 17:18:44 +00:00
it('should save object', function (test) {
var title = 'Initial title', title2 = 'Hello world',
date = new Date;
Post.create({
title: title,
date: date
}, function (err, obj) {
2011-10-23 19:43:53 +00:00
test.ok(obj.id, 'Object id should present');
2011-10-03 17:18:44 +00:00
test.equals(obj.title, title);
// test.equals(obj.date, date);
obj.title = title2;
test.ok(obj.propertyChanged('title'), 'Title changed');
obj.save(function (err, obj) {
test.equal(obj.title, title2);
test.ok(!obj.propertyChanged('title'));
test.done();
});
});
});
it('should create object with initial data', function (test) {
var title = 'Initial title',
date = new Date;
2011-10-03 17:18:44 +00:00
Post.create({
title: title,
date: date
}, function (err, obj) {
test.ok(obj.id);
test.equals(obj.title, title);
test.equals(obj.date, date);
Post.find(obj.id, function () {
test.equal(obj.title, title);
2011-10-23 19:43:53 +00:00
test.equal(obj.date.toString(), date.toString());
2011-10-03 17:18:44 +00:00
test.done();
});
});
});
2011-12-11 08:58:34 +00:00
it('should save only schema-defined field in database', function (test) {
Post.create({title: '1602', nonSchemaField: 'some value'}, function (err, post) {
test.ok(!post.nonSchemaField);
post.a = 1;
post.save(function () {
test.ok(post.a);
post.reload(function (err, psto) {
test.ok(!post.a);
test.done();
});
});
});
});
2011-10-03 17:18:44 +00:00
it('should not create new instances for the same object', function (test) {
var title = 'Initial title';
Post.create({ title: title }, function (err, post) {
test.ok(post.id, 'Object should have id');
test.equals(post.title, title);
Post.find(post.id, function (err, foundPost) {
if (err) throw err;
test.equal(post.title, title);
test.strictEqual(post, foundPost);
test.done();
});
});
});
it('should not re-instantiate object on saving', function (test) {
var title = 'Initial title';
var post = new Post({title: title});
post.save(function (err, savedPost) {
test.strictEqual(post, savedPost);
test.done();
});
});
it('should destroy object', function (test) {
Post.create(function (err, post) {
Post.exists(post.id, function (err, exists) {
test.ok(exists, 'Object exists');
post.destroy(function () {
Post.exists(post.id, function (err, exists) {
2011-10-23 19:43:53 +00:00
if (err) console.log(err);
2011-10-03 17:18:44 +00:00
test.ok(!exists, 'Hey! ORM told me that object exists, but it looks like it doesn\'t. Something went wrong...');
Post.find(post.id, function (err, obj) {
test.equal(obj, null, 'Param obj should be null');
test.done();
});
});
});
});
});
});
2011-12-11 11:01:23 +00:00
it('should handle virtual attributes', function (test) {
var salt = 's0m3s3cr3t5a1t';
2011-12-11 19:25:13 +00:00
User.setter.passwd = function (password) {
this._passwd = calcHash(password, salt);
2011-12-11 11:01:23 +00:00
};
function calcHash(pass, salt) {
var crypto = require('crypto');
var hash = crypto.createHash('sha256');
hash.update(pass);
hash.update(salt);
return hash.digest('base64');
}
var u = new User;
2011-12-11 19:25:13 +00:00
u.passwd = 's3cr3t';
test.equal(u.passwd, calcHash('s3cr3t', salt));
2011-12-11 11:01:23 +00:00
test.done();
});
2011-10-03 17:18:44 +00:00
it('should update single attribute', function (test) {
Post.create({title: 'title', content: 'content', published: true}, function (err, post) {
post.content = 'New content';
post.updateAttribute('title', 'New title', function () {
test.equal(post.title, 'New title');
test.ok(!post.propertyChanged('title'));
2011-11-27 06:08:40 +00:00
test.equal(post.content, 'New content', 'dirty state saved');
2011-10-03 17:18:44 +00:00
test.ok(post.propertyChanged('content'));
post.reload(function () {
test.equal(post.title, 'New title');
test.ok(!post.propertyChanged('title'));
2011-11-27 06:08:40 +00:00
test.equal(post.content, 'content', 'real value turned back');
test.ok(!post.propertyChanged('content'), 'content unchanged');
2011-10-03 17:18:44 +00:00
test.done();
});
});
});
});
var countOfposts, countOfpostsFiltered;
2011-10-03 17:18:44 +00:00
it('should fetch collection', function (test) {
Post.all(function (err, posts) {
countOfposts = posts.length;
test.ok(countOfposts > 0);
test.ok(posts[0] instanceof Post);
countOfpostsFiltered = posts.filter(function (p) {
return p.title === 'title';
}).length;
2011-10-03 17:18:44 +00:00
test.done();
});
});
it('should fetch count of records in collection', function (test) {
Post.count(function (err, count) {
test.equal(countOfposts, count);
Post.count({title: 'title'}, function (err, count) {
test.equal(countOfpostsFiltered, count);
test.done();
});
2011-10-03 17:18:44 +00:00
});
});
it('should find filtered set of records', function (test) {
var wait = 3;
// exact match with string
Post.all({where: {title: 'New title'}}, function (err, res) {
2011-10-03 17:18:44 +00:00
var pass = true;
res.forEach(function (r) {
if (r.title != 'New title') pass = false;
});
2012-01-13 20:06:57 +00:00
test.ok(res.length > 0, 'Exact match with string returns dataset');
2011-10-03 17:18:44 +00:00
test.ok(pass, 'Exact match with string');
done();
});
// matching null
Post.all({where: {title: null}}, function (err, res) {
2012-01-10 15:43:32 +00:00
2011-10-03 17:18:44 +00:00
var pass = true;
res.forEach(function (r) {
2011-10-11 19:51:32 +00:00
if (r.title != null) pass = false;
2011-10-03 17:18:44 +00:00
});
2012-01-13 20:06:57 +00:00
test.ok(res.length > 0, 'Matching null returns dataset');
2011-10-03 17:18:44 +00:00
test.ok(pass, 'Matching null');
done();
});
// matching regexp
2012-01-30 13:54:13 +00:00
if (Post.schema.name !== 'redis') done(); else
Post.all({where: {title: /hello/i}}, function (err, res) {
2011-10-03 17:18:44 +00:00
var pass = true;
res.forEach(function (r) {
if (!r.title || !r.title.match(/hello/i)) pass = false;
});
2012-01-13 20:06:57 +00:00
test.ok(res.length > 0, 'Matching regexp returns dataset');
2011-10-03 17:18:44 +00:00
test.ok(pass, 'Matching regexp');
done();
});
function done() {
if (--wait === 0) {
test.done();
}
}
});
2011-10-05 14:47:26 +00:00
it('should handle hasMany relationship', function (test) {
User.create(function (err, u) {
if (err) return console.log(err);
test.ok(u.posts, 'Method defined: posts');
2011-10-15 15:57:35 +00:00
test.ok(u.posts.build, 'Method defined: posts.build');
test.ok(u.posts.create, 'Method defined: posts.create');
u.posts.create(function (err, post) {
2011-10-05 14:47:26 +00:00
if (err) return console.log(err);
// test.ok(post.author(), u.id);
2011-10-05 14:47:26 +00:00
u.posts(function (err, posts) {
test.strictEqual(posts.pop(), post);
test.done();
});
});
});
});
2011-12-09 15:23:29 +00:00
// it('should handle hasOne relationship', function (test) {
// User.create(function (err, u) {
// if (err) return console.log(err);
// });
// });
2011-10-15 15:57:35 +00:00
it('should support scopes', function (test) {
var wait = 2;
test.ok(Post.scope, 'Scope supported');
Post.scope('published', {where: {published: true}});
2011-10-15 15:57:35 +00:00
test.ok(typeof Post.published === 'function');
test.ok(Post.published._scope.published = true);
var post = Post.published.build();
test.ok(post.published, 'Can build');
test.ok(post.isNewRecord());
Post.published.create(function (err, psto) {
if (err) return console.log(err);
test.ok(psto.published);
test.ok(!psto.isNewRecord());
done();
});
User.create(function (err, u) {
if (err) return console.log(err);
test.ok(typeof u.posts.published == 'function');
test.ok(u.posts.published._scope.where.published);
test.equal(u.posts.published._scope.where.userId, u.id);
2011-10-15 15:57:35 +00:00
done();
});
function done() {
if (--wait === 0) test.done();
};
});
2011-10-03 17:18:44 +00:00
it('should destroy all records', function (test) {
Post.destroyAll(function (err) {
if (err) {
console.log('Error in destroyAll');
throw err;
}
2011-10-03 17:18:44 +00:00
Post.all(function (err, posts) {
test.equal(posts.length, 0);
Post.count(function (err, count) {
test.equal(count, 0);
test.done();
});
});
});
});
2012-01-18 15:20:05 +00:00
it('should return type of property', function (test) {
test.equal(Post.whatTypeName('title'), 'String');
test.equal(Post.whatTypeName('content'), 'Text');
var p = new Post;
test.equal(p.whatTypeName('title'), 'String');
test.equal(p.whatTypeName('content'), 'Text');
test.done();
});
it('should handle ORDER clause', function (test) {
var titles = [ 'Title A', 'Title Z', 'Title M', 'Title B', 'Title C' ];
2012-01-19 20:29:12 +00:00
var isRedis = Post.schema.name === 'redis' || Post.schema.name === 'memory';
2012-01-19 20:25:50 +00:00
var dates = isRedis ? [ 5, 9, 0, 17, 9 ] : [
2012-01-19 20:16:30 +00:00
new Date(1000 * 5 ),
new Date(1000 * 9),
new Date(1000 * 0),
new Date(1000 * 17),
new Date(1000 * 9)
];
titles.forEach(function (t, i) {
Post.create({title: t, date: dates[i]}, done);
});
var i = 0, tests = 0;
function done(err, obj) {
if (++i === titles.length) {
2012-01-19 20:25:50 +00:00
doFilterAndSortTest();
doStringTest();
doNumberTest();
}
}
// Post.schema.log = console.log;
function doStringTest() {
tests += 1;
Post.all({order: 'title'}, function (err, posts) {
2012-01-19 20:16:30 +00:00
if (err) console.log(err);
test.equal(posts.length, 5);
titles.sort().forEach(function (t, i) {
test.equal(posts[i].title, t);
});
finished();
});
}
function doNumberTest() {
tests += 1;
Post.all({order: 'date'}, function (err, posts) {
2012-01-19 20:16:30 +00:00
if (err) console.log(err);
test.equal(posts.length, 5);
dates.sort(numerically).forEach(function (d, i) {
// fix inappropriated tz convert
2012-01-19 20:16:30 +00:00
test.equal(posts[i].date.toString(), d.toString());
});
finished();
});
}
function doFilterAndSortTest() {
tests += 1;
2012-01-19 20:25:50 +00:00
Post.all({where: {date: isRedis ? 9 : new Date(1000 * 9)}, order: 'title', limit: 3}, function (err, posts) {
2012-01-19 20:16:30 +00:00
if (err) console.log(err);
test.equal(posts.length, 2, 'Exactly 2 posts returned by query');
[ 'Title C', 'Title Z' ].forEach(function (t, i) {
if (posts[i]) {
test.equal(posts[i].title, t);
}
});
finished();
});
}
var fin = 0;
function finished() {
if (++fin === tests) {
test.done();
}
}
// TODO: do mixed test, do real dates tests, ensure that dates stored in UNIX timestamp format
function numerically(a, b) {
return a - b;
}
});
it('all tests done', function (test) {
test.done();
process.nextTick(allTestsDone);
});
2011-10-03 17:18:44 +00:00
function allTestsDone() {
schema.disconnect();
2011-10-03 17:18:44 +00:00
console.log('Test done in %dms\n', Date.now() - start);
}
}
2011-10-16 17:21:08 +00:00
function getSpecificTests() {
var sp = {};
sp['neo4j'] = function (schema) {
it('should create methods for searching by index', function (test) {
var Post = schema.models['Post'];
test.ok(typeof Post.findByTitle === 'function');
Post.create({title: 'Catcher in the rye'}, function (err, post) {
if (err) return console.log(err);
test.ok(!post.isNewRecord());
Post.findByTitle('Catcher in the rye', function (err, foundPost) {
if (err) return console.log(err);
if (foundPost) {
test.equal(post.id, foundPost.id);
test.done();
}
});
});
});
};
return sp;
}