Skip to content

Commit

Permalink
Add GET /api/v1/info/users e2e test
Browse files Browse the repository at this point in the history
  • Loading branch information
Cow-Van committed Jan 19, 2024
1 parent 21056a4 commit 9c6bcca
Show file tree
Hide file tree
Showing 8 changed files with 1,002 additions and 959 deletions.
905 changes: 905 additions & 0 deletions src/e2e/data/fakeUsers.ts

Large diffs are not rendered by default.

902 changes: 0 additions & 902 deletions src/e2e/fake-data/users.json

This file was deleted.

38 changes: 29 additions & 9 deletions src/e2e/get-all-users.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,44 @@ dotenv.config();
import request from "supertest";

import app from "../app";
import { cleanUpDatabase, resetTables, setupDatabase } from "./helpers/database";
import fakeUsers from "./data/fakeUsers";
import User from "../models/User.model";

describe("/api/v1/info/users", () => {
beforeEach(() => {

before(async () => {
await cleanUpDatabase();
await setupDatabase();
});

after(async () => {
await cleanUpDatabase();
});

beforeEach(async () => {
await resetTables();
});

describe("GET request", () => {
it("should return all users when database is not empty", () => {
request(app)
.GET("/api/v1/info/users")
.get("/api/v1/info/users")
.set("Accept", "application/json")
.send()
.expect(200)
.expect({ description: "Returning all users" });

.expect({
description: "Returning all users",
users: structuredClone(fakeUsers).map((user: Partial<User>) => {
delete user.password;
user.signed_in = (user.signed_in) ? 1 : 0 as any;
return user;
}),
})
.end((err) => {
if (err) {
throw err;
}
});
});
it("should return no users when database is empty", () => {

})
});
});
});
16 changes: 10 additions & 6 deletions src/e2e/helpers/create-fake-data.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { faker } from "@faker-js/faker";
import fs from "fs";

function removeSpecialCharacters(s: string): string { // TODO: Untested
return s.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "");
}

function generateFakeUser(userId: number) {
return {
user_id: userId,
first_name: faker.person.firstName(),
last_name: faker.person.lastName(),
password: faker.internet.password(),
first_name: removeSpecialCharacters(faker.person.firstName()),
last_name: removeSpecialCharacters(faker.person.lastName()),
password: removeSpecialCharacters(faker.internet.password()),
signed_in: faker.datatype.boolean(),
last_signed_in: faker.date.past().valueOf(),
total_time: faker.date.anytime().valueOf(),
Expand All @@ -17,9 +21,9 @@ export default () => { // UNUSED (ONLY USE ONCE AND SAVE THE DATA)
let userData = [];
let id = 1;
for (let i = 0; i < 100; i++) {
id += faker.number.int(10);
id += faker.number.int(10) + 1;
userData.push(generateFakeUser(id));
}
console.log(userData);
fs.writeFile(__dirname + "/fakeData.json", JSON.stringify(userData), () => {});

fs.writeFile("fakeData.ts", "export default " + JSON.stringify(userData), "utf-8", () => {});
}
45 changes: 45 additions & 0 deletions src/e2e/helpers/database.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import db from "../../database";
import User from "../../models/User.model";
import fakeUsers from "../data/fakeUsers";

async function setupDatabase() {
await db.query(`
CREATE TABLE users (
user_id INT(11) PRIMARY KEY,
first_name VARCHAR(200) NOT NULL,
last_name VARCHAR(200) NOT NULL,
password VARCHAR(200) UNIQUE NOT NULL,
signed_in BOOL NOT NULL,
last_signed_in BIGINT(20) NOT NULL,
total_time BIGINT(20) NOT NULL
)
`);
}

async function cleanUpDatabase() {
await db.query("DROP TABLE IF EXISTS users, sessions, configs");
}

async function resetTables() {
let usersParamList: any[][] = [];
fakeUsers.forEach((user: User) => {
usersParamList.push([
user.user_id,
user.first_name,
user.last_name,
user.password,
user.signed_in,
user.last_signed_in,
user.total_time,
]);
});

await db.query("TRUNCATE TABLE users");

const sql = `INSERT INTO users
(user_id, first_name, last_name, password, signed_in, last_signed_in, total_time)
VALUES ?`;
await db.query(sql, [usersParamList]);
}

export { setupDatabase, cleanUpDatabase, resetTables };
Empty file removed src/e2e/helpers/setup-database.ts
Empty file.
44 changes: 9 additions & 35 deletions src/models/Session.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ async function getAllSessions(): Promise<Session[]> {

async function getSessionsByUserId(user_id: number): Promise<Session[]> {
const sql = "SELECT * FROM `sessions` WHERE user_id = ?";
const [sessions] = await database.query<SessionRowDataPacket[]>(sql, [
user_id,
]);
const [sessions] = await database.query<SessionRowDataPacket[]>(sql, [user_id]);

if (sessions.length < 1) {
throw new RowNotFoundError("Session not found in table: sessions!");
Expand All @@ -34,59 +32,35 @@ async function getSessionsByUserId(user_id: number): Promise<Session[]> {
return sessions;
}

async function createSession(
user_id: number,
start_time: number,
end_time: number,
amended: boolean
): Promise<boolean> {
const sql =
"INSERT INTO `sessions` (user_id, start_time, end_time, amended) SELECT user_id, ?, ?, ? FROM users WHERE user_id = ?)";
async function createSession(user_id: number, start_time: number, end_time: number, amended: boolean): Promise<boolean> {
const sql = "INSERT INTO `sessions` (user_id, start_time, end_time, amended) SELECT user_id, ?, ?, ? FROM users WHERE user_id = ?)";
const params = [start_time, end_time, amended, user_id];

const [resHeader] = await database.query<ResultSetHeader>(sql, params);

return resHeader.affectedRows === 1;
}

async function updateSession(
session_id: number,
values: Partial<Session>
): Promise<boolean> {
async function updateSession(session_id: number, values: Partial<Session>): Promise<boolean> {
const update = updateBuilder("sessions", values, { session_id });
const [resHeader] = await database.query<ResultSetHeader>(
update.query,
update.params
);
const [resHeader] = await database.query<ResultSetHeader>(update.query, update.params);

return resHeader.affectedRows === 1;
}

async function deleteSession(session_id: number): Promise<boolean> {
const sql = "DELETE FROM `sessions` WHERE session_id = ?";
const [resHeader] = await database.query<ResultSetHeader>(sql, [
session_id,
]);
const [resHeader] = await database.query<ResultSetHeader>(sql, [session_id]);

return resHeader.affectedRows === 1;
}

async function deleteSessionsByUserPassword(
password: number
): Promise<boolean> {
const sql =
"DELETE FROM `sessions` WHERE user_id = (SELECT user_id from users WHERE password = ?)";
async function deleteSessionsByUserPassword(password: number): Promise<boolean> {
const sql = "DELETE FROM `sessions` WHERE user_id = (SELECT user_id from users WHERE password = ?)";
const [resHeader] = await database.query<ResultSetHeader>(sql, [password]);

return resHeader.affectedRows > 0;
}

export default Session;
export {
getAllSessions,
getSessionsByUserId,
createSession,
updateSession,
deleteSession,
deleteSessionsByUserPassword,
};
export { getAllSessions, getSessionsByUserId, createSession, updateSession, deleteSession, deleteSessionsByUserPassword };
11 changes: 4 additions & 7 deletions src/utils/update-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,11 @@ function updateBuilder(table: string, updates: { [key: string]: any }, condition
});
}

let query = "UPDATE ? SET ?"
let params = [
table,
updateList.join(", "),
];
let query = "UPDATE ? SET ?";
let params = [table, updateList.join(", ")];

if (conditionList.length > 0) {
query += " WHERE ?"
query += " WHERE ?";
params.push(conditionList.join(" AND "));
}

Expand All @@ -28,4 +25,4 @@ function updateBuilder(table: string, updates: { [key: string]: any }, condition
};
}

export default updateBuilder;
export default updateBuilder;

0 comments on commit 9c6bcca

Please sign in to comment.