Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added tests for internal server errors #97

Merged
merged 1 commit into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions users/authservice/test/auth-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,17 @@ describe('Auth Service', () => {
const response = await request(app).post('/login').send(invalidBody);
expect(response.status).toBe(400);
});
it('Should fail if the database is not accessible', async () => {
const response = await testWithoutDatabase(() => {
return request(app).post('/login').send(user)
});
expect(response.status).toBe(500);
});
});

async function testWithoutDatabase(paramFunc : Function) {
await mongoose.connection.close();
const response : Response = await paramFunc();
await mongoose.connect(mongoServer.getUri());
return response;
}
144 changes: 116 additions & 28 deletions users/userservice/test/user-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import app from '../src/app';
import {validateHistoryBody} from "../src/utils/history-body-validation";
import { Request } from 'express';
import {verifyJWT} from "../src/utils/async-verification";
import { Request, Response } from 'express';
import { verifyJWT } from "../src/utils/async-verification";

let mongoServer: MongoMemoryServer;

beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
process.env.MONGODB_URI = mongoUri;

await mongoose.connect(mongoUri);
});

Expand Down Expand Up @@ -278,14 +279,7 @@ describe('User Service', () => {
} as Request;
const user = await User.find({ username:'testuser' });

let gotError = false;
try {
validateHistoryBody(mockRequest, user[0]);
} catch (error) {
gotError = true;
}
if (!gotError)
fail('Should get an error');
expect(() => validateHistoryBody(mockRequest, user[0])).toThrowError();
});

// Body validation util, non-numeric
Expand All @@ -299,14 +293,7 @@ describe('User Service', () => {
} as Request;
const user = await User.find({ username:'testuser' });

let gotError = false;
try {
validateHistoryBody(mockRequest, user[0]);
} catch (error) {
gotError = true;
}
if (!gotError)
fail('Should get an error');
expect(() => validateHistoryBody(mockRequest, user[0])).toThrowError();
});

// Body validation util, negative
Expand All @@ -320,22 +307,123 @@ describe('User Service', () => {
} as Request;
const user = await User.find({ username:'testuser' });

let gotError = false;
try {
validateHistoryBody(mockRequest, user[0]);
} catch (error) {
gotError = true;
}
if (!gotError)
fail('Should get an error');
expect(() => validateHistoryBody(mockRequest, user[0])).toThrowError();
});

// Token validator
it('should get an error when invoking the function with an invalid token', async () => {
let gotError = false;
try {
await verifyJWT('invalidtoken');
fail('Should get an error in the previous call');
} catch (error) {
} catch (err) {
gotError = true;
}
if (!gotError)
fail('Should get an error')
});

it('trying to retrieve a user with the database down should not work', async () => {
const newUserData = {
username: 'newUser',
password: 'testpassword',
};

const response = await testWithoutDatabase(() => {
return request(app)
.post('/adduser')
.send(newUserData)
});

expect(response.statusCode).toBe(500);
});

it('trying to add a user when cannot write to the database should not work', async () => {
const newUserData = {
username: 'newUser',
password: 'testpassword',
};

const response = await testReadOnlyDatabase(() => {
return request(app)
.post('/adduser')
.send(newUserData)
});

expect(response.statusCode).toBe(500);
});

it('trying to access the history of a user with the database down should not work', async () => {
const response = await testWithoutDatabase(() => {
return request(app)
.get('/history?user=testuser')
});

expect(response.statusCode).toBe(500);
});

it('trying to get the leaderboard with the database down should not work', async () => {
const response = await testWithoutDatabase(() => {
return request(app)
.get('/history/leaderboard')
});

expect(response.statusCode).toBe(500);
});

it('trying to update the history when the database cannot be written should not work', async () => {
const newHistory = {
history: {
passedQuestions: 2,
gamesPlayed: 6,
points: 1,
},
};

const response = await testReadOnlyDatabase(() => {
return request(app)
.post('/history')
.send(newHistory)
.set('Authorization', `Bearer ${testToken}`);
});

expect(response.statusCode).toBe(500);
});

it('trying to increment the history when the database cannot be written should not work', async () => {
const increment = {
history: {
passedQuestions: 2,
gamesPlayed: 6,
points: 1,
},
};

const response = await testReadOnlyDatabase(() => {
return request(app)
.post('/history/increment')
.send(increment)
.set('Authorization', `Bearer ${testToken}`);
});

expect(response.statusCode).toBe(500);
});
});

async function testWithoutDatabase(paramFunc : Function) {
await mongoose.connection.close();
const response : Response = await paramFunc();
await mongoose.connect(mongoServer.getUri());
return response;
}

async function testReadOnlyDatabase(paramFunc : Function) {
// Replace save function to avoid writing and trigger a server error
const previousSaveFunction = mongoose.models.User.prototype.save;
mongoose.models.User.prototype.save = function () {
throw new Error('Write operation not allowed');
};
const response : Response = await paramFunc();
// Restore the previous functionality
mongoose.models.User.prototype.save = previousSaveFunction;
return response;
}
4 changes: 2 additions & 2 deletions users/utils/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 4 additions & 26 deletions users/utils/test/users-utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Request } from 'express';
const {validateNotEmpty, validateRequiredFields, validateRequiredLength} = require("../src/field-validations");
const {validateNotEmpty, validateRequiredFields, validateRequiredLength} = require("../src/index");

describe('Users Utils', () => {
// Empty field validation
Expand All @@ -9,14 +9,7 @@ describe('Users Utils', () => {
} as Request;
mockRequest.body['history'] = '';

let gotError = false;
try {
validateNotEmpty(mockRequest, ['history']);
} catch (error) {
gotError = true
}
if (!gotError)
fail('Should get an error');
expect(() => validateNotEmpty(mockRequest, ['history'])).toThrowError();

// Should ignore field if does not exist
try {
Expand All @@ -33,14 +26,7 @@ describe('Users Utils', () => {
} as Request;
mockRequest.body['test'] = '123456789';

let gotError = false;
try {
validateRequiredLength(mockRequest, ['test'], 10);
} catch (error) {
gotError = true;
}
if (!gotError)
fail('Should get an error');
expect(() => validateRequiredLength(mockRequest, ['test'], 10)).toThrowError();

// Should ignore field if does not exist
try {
Expand Down Expand Up @@ -72,14 +58,6 @@ describe('Users Utils', () => {
mockRequest.body['test'] = 'test';

// Should get an error when the field does not exist
let gotError = false;
gotError = false;
try {
validateRequiredFields(mockRequest, ['nonexistent']);
} catch (error) {
gotError = true;
}
if (!gotError)
fail('Should get an error');
expect(() => validateRequiredFields(mockRequest, ['nonexistent'])).toThrowError();
});
});