tests: Extract api objects to separate files

This commit is contained in:
Blade Barringer
2016-01-16 14:06:47 -06:00
parent 29415441f7
commit e9f618da5e
3 changed files with 136 additions and 118 deletions

View File

@@ -0,0 +1,70 @@
/* eslint-disable no-use-before-define */
import { requester } from './requester';
import {
assign,
each,
isEmpty,
set,
} from 'lodash';
import { MongoClient as mongo } from 'mongodb';
class ApiObject {
constructor (options) {
assign(this, options);
}
update (options) {
return new Promise((resolve) => {
_updateDocument(this._docType, this, options, resolve);
});
}
}
export class ApiUser extends ApiObject {
constructor (options) {
super(options);
this._docType = 'users';
let _requester = requester(this);
this.get = _requester.get;
this.post = _requester.post;
this.put = _requester.put;
this.del = _requester.del;
}
}
export class ApiGroup extends ApiObject {
constructor (options) {
super(options);
this._docType = 'groups';
}
}
function _updateDocument (collectionName, doc, update, cb) {
if (isEmpty(update)) {
return cb();
}
mongo.connect('mongodb://localhost/habitrpg_test', (connectErr, db) => {
if (connectErr) throw new Error(`Error connecting to database when updating ${collectionName} collection: ${connectErr}`);
let collection = db.collection(collectionName);
collection.updateOne({ _id: doc._id }, { $set: update }, (updateErr) => {
if (updateErr) throw new Error(`Error updating ${collectionName}: ${updateErr}`);
_updateLocalDocument(doc, update);
db.close();
cb();
});
});
}
function _updateLocalDocument (doc, update) {
each(update, (value, param) => {
set(doc, param, value);
});
}

View File

@@ -0,0 +1,57 @@
import superagent from 'superagent';
const API_TEST_SERVER_PORT = 3003;
var apiVersion;
// Sets up an abject that can make all REST requests
// If a user is passed in, the uuid and api token of
// the user are used to make the requests
export function requester (user = {}, additionalSets) {
return {
get: _requestMaker(user, 'get', additionalSets),
post: _requestMaker(user, 'post', additionalSets),
put: _requestMaker(user, 'put', additionalSets),
del: _requestMaker(user, 'del', additionalSets),
};
}
requester.setApiVersion = (version) => {
apiVersion = version;
}
function _requestMaker (user, method, additionalSets) {
if (!apiVersion) throw new Error('apiVersion not set');
return (route, send, query) => {
return new Promise((resolve, reject) => {
let request = superagent[method](`http://localhost:${API_TEST_SERVER_PORT}/api/${apiVersion}${route}`)
.accept('application/json');
if (user && user._id && user.apiToken) {
request
.set('x-api-user', user._id)
.set('x-api-key', user.apiToken);
}
if (additionalSets) {
request.set(additionalSets);
}
request
.query(query)
.send(send)
.end((err, response) => {
if (err) {
if (!err.response) return reject(err);
return reject({
code: err.status,
text: err.response.body.err,
});
}
resolve(response.body);
});
});
};
}