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 in-memory database for Users testing #154

Merged
merged 7 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
teamname="wiq_es04a"
NODE_ENV=''
1 change: 1 addition & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ app.post('/login', async (req, res) => {

app.post('/user/add', async (req, res) => {
try {
console.log(1);
// Forward the add user request to the user service
const userResponse = await axios.post(`${userServiceUrl}/user/add`, req.body);
res.json(userResponse.data);
Expand Down
87 changes: 87 additions & 0 deletions users/__tests/routes/statistics-routes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const { Statistics, sequelize } = require('../../models/user-model.js');
const request = require('supertest');
const express = require('express');
const bodyParser = require('body-parser');
const statisticsRoutes = require('../../routes/statistics-routes.js');
const { User } = require('../../models/user-model.js');

const app = express();
app.use(bodyParser.json());
app.use('/statistics', statisticsRoutes);

describe('Statistics Routes', () => {
beforeAll(async () => {
await sequelize.authenticate();
await sequelize.sync({ force: true });
});

afterAll(async () => {
await sequelize.close();
});

it('should update user statistics', async () => {
const newUser = {
username: 'testuser',
password: 'Test1234',
name: 'Test',
surname: 'User'
};

// Create user for the statistics
await User.create(newUser);

const initialStatistics = {
username: 'testuser',
earned_money: 100,
classic_correctly_answered_questions: 5,
classic_incorrectly_answered_questions: 2,
classic_total_time_played: 3600,
classic_games_played: 3
};

await Statistics.create(initialStatistics);

const updatedStatistics = {
username: 'testuser',
earned_money: 50,
classic_correctly_answered_questions: 3,
classic_incorrectly_answered_questions: 1,
classic_total_time_played: 1800,
classic_games_played: 2
};

const response = await request(app)
.post('/statistics/edit')
.send(updatedStatistics);

expect(response.status).toBe(200);
expect(response.body.message).toBe('User statics updated successfully');

// Check if the statistics are updated in the database
const userStatistics = await Statistics.findOne({ where: { username: updatedStatistics.username } });

expect(userStatistics.earned_money).toBe(initialStatistics.earned_money + updatedStatistics.earned_money);
expect(userStatistics.classic_correctly_answered_questions).toBe(initialStatistics.classic_correctly_answered_questions + updatedStatistics.classic_correctly_answered_questions);
expect(userStatistics.classic_incorrectly_answered_questions).toBe(initialStatistics.classic_incorrectly_answered_questions + updatedStatistics.classic_incorrectly_answered_questions);
expect(userStatistics.classic_total_time_played).toBe(initialStatistics.classic_total_time_played + updatedStatistics.classic_total_time_played);
expect(userStatistics.classic_games_played).toBe(initialStatistics.classic_games_played + updatedStatistics.classic_games_played);
});

it('should return error if user not found', async () => {
const nonExistingUserStatistics = {
username: 'nonexistinguser',
earned_money: 50,
classic_correctly_answered_questions: 3,
classic_incorrectly_answered_questions: 1,
classic_total_time_played: 1800,
classic_games_played: 2
};

const response = await request(app)
.post('/statistics/edit')
.send(nonExistingUserStatistics);

expect(response.status).toBe(404);
expect(response.body.error).toBe('User not found');
});
});
76 changes: 76 additions & 0 deletions users/__tests/routes/user-routes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const { User, Statistics, sequelize } = require('../../models/user-model.js');
const bcrypt = require('bcrypt');
const request = require('supertest');
const express = require('express');
const bodyParser = require('body-parser');
const userRoutes = require('../../routes/user-routes.js');

const app = express();
app.use(bodyParser.json());
app.use('/user', userRoutes);

describe('User Routes', () => {
beforeAll(async () => {
await sequelize.authenticate();
await sequelize.sync({ force: true });
});

afterAll(async () => {
await sequelize.close();
});

it('should add a new user', async () => {
const newUser = {
username: 'testuser',
password: 'Test1234',
name: 'Test',
surname: 'User'
};

const response = await request(app)
.post('/user/add')
.send(newUser);

expect(response.status).toBe(200);
expect(response.body.username).toBe(newUser.username);

// Check if the user exists in the database
const user = await User.findOne({ where: { username: newUser.username } });
expect(user).toBeDefined();

// Check if the password is hashed
const isPasswordCorrect = await bcrypt.compare(newUser.password, user.password);
expect(isPasswordCorrect).toBe(true);

// Check if statistics for the user are created
const statistics = await Statistics.findOne({ where: { username: newUser.username } });
expect(statistics).toBeDefined();
});

it('should not add a user if username already exists', async () => {
const existingUser = {
username: 'existinguser',
password: 'Test1234',
name: 'Existing',
surname: 'User'
};

// Create the existing user in the database
await User.create({
username: existingUser.username,
password: await bcrypt.hash(existingUser.password, 10),
createdAt: new Date(),
updatedAt: new Date(),
name: existingUser.name,
surname: existingUser.surname
});

// Try to add the existing user again
const response = await request(app)
.post('/user/add')
.send(existingUser);

expect(response.status).toBe(400);
expect(response.body.error).toBe('An account with that username already exists');
});
});
45 changes: 0 additions & 45 deletions users/__tests/services/auth-service.test.js

This file was deleted.

122 changes: 0 additions & 122 deletions users/__tests/services/user-service.test.js

This file was deleted.

35 changes: 24 additions & 11 deletions users/models/user-model.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
const { Sequelize, DataTypes } = require('sequelize');

// Function to create Sequelize instance with appropriate configurations
function createSequelizeInstance() {
if (process.env.NODE_ENV === 'test') {
// Use SQLite in-memory database for testing
return new Sequelize({
dialect: 'sqlite',
storage: ':memory:'
});
} else {
// Normal database configuration for production
return new Sequelize({
host: 'mariadb',
username: 'root',
password: 'R#9aLp2sWu6y',
database: 'base_de_datos_de_usuarios',
port: 3306,
dialect: 'mariadb',
dialectOptions: {
connectTimeout: 20000
}
});
}
}

// Database connection configuration
const sequelize = new Sequelize({
host: 'mariadb',
username: 'root',
password: 'R#9aLp2sWu6y',
database: 'base_de_datos_de_usuarios',
port: 3306,
dialect: 'mariadb',
dialectOptions: {
connectTimeout: 20000
}
});
const sequelize = createSequelizeInstance();

// Define the user model
const User = sequelize.define('User', {
Expand Down
Loading
Loading