diff options
| author | Tom Harley | 2018-03-27 19:19:16 +0100 |
|---|---|---|
| committer | Tom Harley | 2018-03-27 19:19:16 +0100 |
| commit | 150115e855e2c406b23aa569dd675597d6957570 (patch) | |
| tree | 7cb6cbbc7e7f2911596bb1f03dbcedd8b10e0e49 /test | |
| parent | Merge branch 'cjd24/conversion' into development (diff) | |
| parent | Centralise test configuration and introduce SQLite (diff) | |
| download | medicine-150115e855e2c406b23aa569dd675597d6957570.tar.gz medicine-150115e855e2c406b23aa569dd675597d6957570.zip | |
Merge branch ‘testing-middleware’ into development
Diffstat (limited to 'test')
| -rw-r--r-- | test/integration/auth.routes.test.ts | 173 | ||||
| -rw-r--r-- | test/integration/index.routes.test.ts | 79 | ||||
| -rw-r--r-- | test/integration/protocol.routes.test.ts | 167 | ||||
| -rw-r--r-- | test/test-db.ts | 41 |
4 files changed, 260 insertions, 200 deletions
diff --git a/test/integration/auth.routes.test.ts b/test/integration/auth.routes.test.ts index 888883f..e3f8113 100644 --- a/test/integration/auth.routes.test.ts +++ b/test/integration/auth.routes.test.ts @@ -2,10 +2,12 @@ /* Chai assertions look silly when formatted multiline. */ /* tslint:disable:no-unused-expression */ /* Chai assertions do not require assignation. */ +/* tslint:disable:typedef */ +/* Mocha tests do not require strong typing. */ import * as chai from 'chai'; const expect: Chai.ExpectStatic = chai.expect; -import { default as seq } from '../../src/db/orm'; +import { Credentials, Database, addUser, initDB, resetDB } from '../test-db'; import { default as User } from '../../src/db/model/User'; // Chai-http must be imported this way: @@ -19,135 +21,158 @@ import 'mocha'; import * as App from '../../src/app'; const app = App.TestApp(); -const badRequestErr = - { status: 'error', - error: 'invalid_request', - error_description: 'Missing parameters' }; -const unsupportedGrantTypeErr = - { status: 'error', - error: 'unsupported_grant_type', - error_description: 'invalid grant type' } -const authorisationErr = - { status: 'error', - error: 'not_authorised', - error_description: 'user does not have correct authorisation for task' } - +let database: Database; +let mockUser: Credentials; +let token: string; -const bobbyCredentials = { - username: 'bobby', - password: 'tables', - grant_type: 'password' +const initDatabase = async() => { + database = initDB(); + await database.authenticate(); }; -let bobbyToken: string; +const populateDatabase = async() => { + await resetDB(database); + mockUser = await addUser(database); +}; -async function resetDatabase(done: any){ - await seq.sync({ - force: true +const getToken = async() => { + return chai.request(app) + .post('/cs3099group-be-4/login') + .send({ + username: mockUser.username, + password: mockUser.password, + grant_type: 'password' + }) + .then((res) => { + token = res.body.access_token; }); - const u: string = bobbyCredentials.username - const p: string = bobbyCredentials.password +}; - const newUser: User = new User({ - username: u, - password: p, - userGroups: [] - }); - await newUser.save(); - done(); -} +const badRequestErr = { + status: 'error', + error: 'invalid_request', + error_description: 'Missing parameters' +}; -async function setupDatabase(done: any) { - await seq.authenticate(); - await seq.sync({ - force: true - }); - done(); -} +const unsupportedGrantTypeErr = { + status: 'error', + error: 'unsupported_grant_type', + error_description: 'invalid grant type' +}; -// Add user -before((done: any) => { - setupDatabase(done); -}); +const authorisationErr = { + status: 'error', + error: 'not_authorised', + error_description: 'user does not have correct authorisation for task' +}; describe('authentication', () => { + before(initDatabase); context('invalid password authentication', () => { + before(populateDatabase); + it('should reject login to invalid endpoints', () => { + return chai.request(app) + .post('/') + .send({ + username: mockUser.username, + password: mockUser.password, + grant_type: 'password' + }) + .then((res) => { + expect(res).to.have.status(400); + }); + }); it('should reject invalid usernames', () => { - chai.request(app) + return chai.request(app) .post('/cs3099group-be-4/login') - .send({...bobbyCredentials, username: 'invalid'}) + .send({ + username: 'invalid', + password: mockUser.password, + grant_type: 'password' + }) .then((res) => { expect(res).to.have.status(401); }); }); it('should reject invalid passwords', () => { - chai.request(app) + return chai.request(app) .post('/cs3099group-be-4/login') - .send({...bobbyCredentials, password: 'asasasas'}) + .send({ + username: mockUser.username, + password: 'asasasas', + grant_type: 'password' + }) .then((res) => { expect(res).to.have.status(401); }); }); it('should reject invalid grant_type', () => { - chai.request(app) + return chai.request(app) .post('/cs3099group-be-4/login') - .send({...bobbyCredentials, grant_type: 'invalid'}) + .send({ + username: mockUser.username, + password: mockUser.password, + grant_type: 'invalid' + }) .catch((reason) => { expect(reason.response.body).to.eql(unsupportedGrantTypeErr); }); }); it('should reject empty usernames', () => { - chai.request(app) + return chai.request(app) .post('/cs3099group-be-4/login') - .send({...bobbyCredentials, username: ''}) + .send({ + username: '', + password: mockUser.password, + grant_type: 'password' + }) .catch((reason) => { expect(reason.response.body).to.eql(badRequestErr); }); }); it('should reject empty passwords', () => { - chai.request(app) + return chai.request(app) .post('/cs3099group-be-4/login') - .send({...bobbyCredentials, password: ''}) + .send({ + username: mockUser.username, + password: '', + grant_type: 'password' + }) .catch((reason) => { expect(reason.response.body).to.eql(badRequestErr); }); }); it('should reject empty grant_type', () => { - chai.request(app) + return chai.request(app) .post('/cs3099group-be-4/login') - .send({...bobbyCredentials, grant_type: ''}) + .send({ + username: mockUser.username, + password: mockUser.password, + grant_type: '' + }) .catch((reason) => { expect(reason.response.body).to.eql(badRequestErr); }); }); }); context('valid password authentication', () => { - before((done: any) => { - resetDatabase(done); - }); + before(populateDatabase); it('should accept correct credentials', () => { - chai.request(app) + return chai.request(app) .post('/cs3099group-be-4/login') - .send(bobbyCredentials) + .send({ + username: mockUser.username, + password: mockUser.password, + grant_type: 'password' + }) .then((res) => { expect(res).to.have.status(200); }); }); }); context('token authentication', () => { - let bobbyToken: string; - before((done: any) => { - resetDatabase(() => { - chai.request(app) - .post('/cs3099group-be-4/login') - .send(bobbyCredentials) - .end((err, res) => { - if (err) { throw err; } - bobbyToken = res.body.access_token; - done(); - }); - }); - }); + beforeEach(populateDatabase); + beforeEach(getToken); it('should reject invalid tokens', () => { return chai.request(app).get('/') .set('Authorization', 'Bearer ' + 'invalid') @@ -159,7 +184,7 @@ describe('authentication', () => { }); it('should accept valid tokens', () => { return chai.request(app).get('/') - .set('Authorization', 'Bearer ' + bobbyToken) + .set('Authorization', `Bearer ${token}`) .then((res) => { expect(res).to.have.status(200); }); diff --git a/test/integration/index.routes.test.ts b/test/integration/index.routes.test.ts index 70671d8..aa30586 100644 --- a/test/integration/index.routes.test.ts +++ b/test/integration/index.routes.test.ts @@ -2,12 +2,12 @@ /* Chai assertions look silly when formatted multiline. */ /* tslint:disable:no-unused-expression */ /* Chai assertions do not require assignation. */ +/* tslint:disable:typedef */ +/* Mocha tests do not require strong typing. */ import * as chai from 'chai'; const expect: Chai.ExpectStatic = chai.expect; -const should = chai.should(); -import * as ex from 'express'; -import { default as seq } from '../../src/db/orm'; +import { Credentials, Database, addUser, initDB, resetDB } from '../test-db'; import { default as User } from '../../src/db/model/User'; // Chai-http must be imported this way: @@ -19,66 +19,58 @@ chai.use(require('chai-http')); import 'mocha'; import * as App from '../../src/app'; -const app: ex.Express = App.TestApp(); - -const userCredentials: Object = { - username: 'bobby', - password: 'pass', - grant_type: 'password' -}; +const app = App.TestApp(); +let database: Database; +let mockUser: Credentials; let token: string; -async function startDatabase(done: any) { - await seq.authenticate(); - await seq.sync({ - force: true - }); +const initDatabase = async() => { + database = initDB(); + await database.authenticate(); +}; - const newUser: User = new User({ - username: 'bobby', - password: 'pass', - userGroups: [] - }); - await newUser.save(); - done(); -} +const populateDatabase = async() => { + await resetDB(database); + mockUser = await addUser(database); +}; -// Add user -before(function(done: any) { - startDatabase(done); -}); +const getToken = async() => { + return chai.request(app) + .post('/cs3099group-be-4/login') + .send({ + username: mockUser.username, + password: mockUser.password, + grant_type: 'password' + }) + .then((res) => { + token = res.body.access_token; + }); +}; describe('routes : index', () => { + before(initDatabase); describe('GET /', () => { + before(populateDatabase); it('should return 401 without authentication', () => { chai.request(app).get('/') - .catch(function(err: any) { + .catch((err) => { return expect(err).to.have.status(401); }); }); context('with authentication', () => { - before(function(done) { - chai.request(app) - .post('/cs3099group-be-4/login') - .send(userCredentials) - .end(function(err, res) { - if (err) { throw err; } - token = res.body.access_token; - done(); - }); - }); + beforeEach(getToken); it('should return 200', () => { return chai.request(app).get('/') - .set('Authorization', 'Bearer ' + token) + .set('Authorization', `Bearer ${token}`) .then((res: ChaiHttp.Response) => { - res.status.should.eql(200); + expect(res).to.have.status(200); }); }); it('should return json', () => { return chai.request(app).get('/') - .set('Authorization', 'Bearer ' + token) + .set('Authorization', `Bearer ${token}`) .then((res: ChaiHttp.Response) => { expect(res.type).to.eql('application/json'); }); @@ -86,7 +78,7 @@ describe('routes : index', () => { it('should return a message prop', () => { return chai.request(app).get('/') - .set('Authorization', 'Bearer ' + token) + .set('Authorization', `Bearer ${token}`) .then((res: ChaiHttp.Response) => { expect(res.body.message).to.eql('Welcome to the CS3099 BE4 server!'); }); @@ -94,7 +86,7 @@ describe('routes : index', () => { it('should return an important prop', () => { return chai.request(app).get('/') - .set('Authorization', 'Bearer ' + token) + .set('Authorization', `Bearer ${token}`) .then((res: ChaiHttp.Response) => { expect(res.body.important) .to.eql('Endpoints start from /cs3099group-be-4/'); @@ -103,5 +95,4 @@ describe('routes : index', () => { }); }); - }); diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 863bec9..a08f977 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -1,19 +1,60 @@ +/* tslint:disable:newline-per-chained-call */ +/* Chai assertions look silly when formatted multiline. */ +/* tslint:disable:no-unused-expression */ +/* Chai assertions do not require assignation. */ +/* tslint:disable:typedef */ +/* Mocha tests do not require strong typing. */ + import * as chai from 'chai'; -import * as mocha from 'mocha'; const expect: Chai.ExpectStatic = chai.expect; +import { Credentials, Database, addUser, initDB, resetDB } from '../test-db'; +import { default as User } from '../../src/db/model/User'; +// Chai-http must be imported this way: +// tslint:disable-next-line:no-var-requires no-require-imports chai.use(require('chai-http')); + +// Mocha must be imported as a side-effect library: +// tslint:disable-next-line:no-import-side-effect import 'mocha'; + +// Mocha-each must be imported using a require: +// tslint:disable-next-line:no-require-imports import forEach = require('mocha-each'); import * as App from '../../src/app'; -import * as ex from 'express'; +const app = App.TestApp(); + +let database: Database; +let mockUser: Credentials; +let token: string; + +const initDatabase = async() => { + database = initDB(); + await database.authenticate(); +}; + +const populateDatabase = async() => { + await resetDB(database); + mockUser = await addUser(database); +}; + +const getToken = async() => { + return chai.request(app) + .post('/cs3099group-be-4/login') + .send({ + username: mockUser.username, + password: mockUser.password, + grant_type: 'password' + }) + .then((res) => { + token = res.body.access_token; + }); +}; + import { Template, alternative, array, exact, match, optional } from '../../src/matcher/options'; -import { default as seq } from '../../src/db/orm'; import { default as types } from '../../src/matcher/types'; -import { default as User } from '../../src/db/model/User'; -const app = App.TestApp(); // The general response template according to protocol const responseTemplate: Template = { @@ -36,78 +77,32 @@ const errorResponseTemplate: Template = { type MochaForEachInput = [ string, string, Template, number ]; -const bobbyCredentials = { - username: 'bobby', - password: 'tables', - grant_type: 'password' -}; - -let bobbyToken: string; - -async function resetDatabase(done: any){ - await seq.sync({ - force: true - }); - const u: string = bobbyCredentials.username - const p: string = bobbyCredentials.password - - const newUser: User = new User({ - username: u, - password: p, - userGroups: [] - }); - await newUser.save(); - done(); -} - -async function setupDatabase(done: any) { - await seq.authenticate(); - await seq.sync({ - force: true - }); - done(); -} - -// Add user -before((done: any) => { - setupDatabase(() => { - resetDatabase(() => { - chai.request(app) - .post('/cs3099group-be-4/login') - .send(bobbyCredentials) - .end((err, res) => { - if (err) { throw err; } - bobbyToken = res.body.access_token; - done(); - }); - }); - }); - -}); - describe('routes : errors', () => { - describe('GET invalid routes', function() { + before(initDatabase); + describe('GET invalid routes', () => { it('should have response code 404', () => { return chai.request(app).get('/invalid/route') - .set('Authorization', 'Bearer ' + bobbyToken) - .catch(function(err: any) { + .set('Authorization', `Bearer ${token}`) + .catch((err) => { expect(err.status).to.equal(404); }); }); - it('should conform to the error protocol', function() { + it('should conform to the error protocol', () => { return chai.request(app).get('/invalid/route') - .set('Authorization', 'Bearer ' + bobbyToken) - .catch(function(err: any) { - match(errorResponseTemplate)(err.response.body).should.be.true; + .set('Authorization', `Bearer ${token}`) + .catch((err) => { + expect(match(errorResponseTemplate)(err.response.body)).to.be.true; }); }); }); - }); describe('routes : protocol', () => { const base: string = '/cs3099group-be-4'; - // format: + + /* tslint:disable:align */ + + // Format: // <method> <route> <json-response-template> <response-code> const completeProtocol: MochaForEachInput[] = [ ['get', '/_supported_protocols_', exact({ @@ -166,7 +161,7 @@ describe('routes : protocol', () => { public_admin_metadata: types.anything, private_admin_metadata: types.anything }), 401], - // todo types.metadata + // TODO types.metadata ['get', '/users/:username', { username: types.string, privileges: array(types.string), @@ -230,55 +225,63 @@ describe('routes : protocol', () => { ['get', '/projects/:project_name/files_by_id/:id', null, 200] ]; + /* tslint:enable:align */ + + before(initDatabase); + beforeEach(populateDatabase); + beforeEach(getToken); + describe('Access all valid routes', () => { forEach(completeProtocol).it( '%s %s should be json', - (method: string, path: string, temp: Template, res_code: number) => { + (method: string, path: string, temp: Template, resCode: number) => { const request: ChaiHttp.Request = method === 'get' ? chai.request(app).get(base + path) : chai.request(app).post(base + path); - request.set('Authorization', 'Bearer ' + bobbyToken); + request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { expect(res.type).to.equal('application/json'); - }).catch(function(err: any) { - match(errorResponseTemplate)(err.response.body).should.be.true; + }).catch((err) => { + expect(match(errorResponseTemplate)(err.response.body)).to.be.true; }); }); forEach(completeProtocol).it( '%s %s should have a status %4$d', - (method: string, path: string, temp: Template, res_code: number) => { + (method: string, path: string, temp: Template, resCode: number) => { const request: ChaiHttp.Request = method === 'get' ? chai.request(app).get(base + path) : chai.request(app).post(base + path); - request.set('Authorization', 'Bearer ' + bobbyToken); + request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { - expect(res).to.have.status(res_code); - }).catch(function(err: any) { - match(errorResponseTemplate)(err.response.body).should.be.true; + expect(res).to.have.status(resCode); + }).catch((err) => { + expect(match(errorResponseTemplate)(err.response.body)).to.be.true; }); }); forEach(completeProtocol).it( '%s %s should conform to the general response protocol', - (method: string, path: string, temp: Template, res_code: number) => { + (method: string, path: string, temp: Template, resCode: number) => { const request: ChaiHttp.Request = method === 'get' ? chai.request(app).get(base + path) : chai.request(app).post(base + path); - request.set('Authorization', 'Bearer ' + bobbyToken); + request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { match(responseTemplate, JSON.parse(res.body)).shoul.be.true; - }).catch(function(err: any) { - match(errorResponseTemplate)(err.response.body).should.be.true; + }).catch((err) => { + expect(match(errorResponseTemplate)(err.response.body)).to.be.true; }); }); forEach(completeProtocol).it( 'the response for %s %s should conform to its specific response protocol', - (method: string, path: string, temp: Template, res_code: number) => { + (method: string, path: string, temp: Template, resCode: number) => { if (method === 'get' && temp != null) { - return chai.request(app).get(base + path).set('Authorization', 'Bearer ' + bobbyToken) + return chai.request(app) + .get(base + path) + .set('Authorization', `Bearer ${token}`) .then((res: ChaiHttp.Response) => { - match(temp)(JSON.parse(res.body)).should.be.true; - }).catch(function(err: any) { - match(errorResponseTemplate)(err.response.body).should.be.true; + expect(match(temp)(JSON.parse(res.body))).to.be.true; + }).catch((err) => { + expect(match(errorResponseTemplate)(err.response.body)).to.be.true; }); } else { return true; diff --git a/test/test-db.ts b/test/test-db.ts new file mode 100644 index 0000000..fe8ae4d --- /dev/null +++ b/test/test-db.ts @@ -0,0 +1,41 @@ +import { default as User } from '../src/db/model/User'; +import { default as UserGroup } from '../src/db/model/UserGroup'; + +import { Sequelize } from 'sequelize-typescript'; +import * as sqlite from 'sqlite3'; + +export type Database = Sequelize; + +export const initDB: () => Database = (): Database => { + const dataFile: string = ':memory:'; + const db: sqlite.Database = new sqlite.Database(dataFile); + const seq: Database = new Sequelize(`sqlite:${dataFile}`); + seq.addModels([`${__dirname}/../src/db/model`]); + seq.options.logging = false; + return seq; +}; + +export const resetDB: (database: Database) => Promise<void> = async( + database: Database +): Promise<void> => { + await database.sync({ + force: true + }); +}; + +export interface Credentials { + username: string; + password: string; + usergroups: UserGroup[]; +} + +export const addUser: (database?: Database) => Promise<Credentials> = async( +): Promise<Credentials> => { + const mockUser: Credentials = { + username: 'mock_user', + password: 'mock_password', + usergroups: [] + }; + await new User(mockUser).save(); + return mockUser; +}; |
