Skip to content

Commit

Permalink
fix: some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
DevNono committed Aug 22, 2023
1 parent 28c68ca commit 5611702
Show file tree
Hide file tree
Showing 18 changed files with 87 additions and 48 deletions.
36 changes: 36 additions & 0 deletions src/controllers/admin/openapi.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,39 @@
/admin/auth/login:
post:
summary: Authentifie un admin même si le paramètre login est désactivé
description: Permet de s'authentifier.<br/>
**Au moins une permission requise.**
tags:
- Admin
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
username:
type: string
description: Nom d'utilisateur
password:
type: string
description: Mot de passe
responses:
200:
description: L'authentification a réussi.
Les informations de l'utilisateur et le token d'authentification sont renvoyés.
content:
application/json:
schema:
type: object
properties:
user:
$ref: '#/components/schemas/User'
token:
type: string
400:
$ref: '#/components/responses/400Errored'

/admin/auth/login/{userId}:
post:
summary: Authentifie en tant qu'un autre utilisateur
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/admin/settings/updateSetting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { hasPermission } from '../../../middlewares/authentication';
import { validateBody } from '../../../middlewares/validation';
import { notFound, success } from '../../../utils/responses';
import { Error } from '../../../types';
import { setDisplayTrombi, setLoginAllowed, setShopAllowed } from '../../../operations/settings';
import { setTrombiAllowed, setLoginAllowed, setShopAllowed } from '../../../operations/settings';

export default [
// Middlewares
Expand All @@ -29,7 +29,7 @@ export default [
break;
}
case 'trombi': {
result = await setDisplayTrombi(request.body.value === 'true');
result = await setTrombiAllowed(request.body.value === 'true');
break;
}
default: {
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/auth/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ export default [

// Controller
async (request: Request, response: Response, next: NextFunction) => {

Check warning on line 20 in src/controllers/auth/login.ts

View workflow job for this annotation

GitHub Actions / lint (18)

Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`
await loginAccount(request, response, next);
return await loginAccount(request, response, next);

Check failure on line 21 in src/controllers/auth/login.ts

View workflow job for this annotation

GitHub Actions / lint (18)

Redundant use of `await` on a return value
},
];
4 changes: 2 additions & 2 deletions src/controllers/openapi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ components:
captainId:
type: string
example: XiHGta
locked:
lockedAt:
type: string
format: date-time
nullable: true
Expand Down Expand Up @@ -434,7 +434,7 @@ components:
captainId:
type: string
example: XiHGta
locked:
lockedAt:
type: string
format: date-time
nullable: true
Expand Down
6 changes: 3 additions & 3 deletions src/controllers/partners/openapi.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/partners:
get:
summary: Renvoie la liste des partenaires.
description: Renvoie la liste des partenaires.
summary: Renvoie la liste des partenaires dont les informations sont publiques.
description: Renvoie la liste des partenaires dont les informations sont publiques.
tags:
- Partners
responses:
200:
description: Renvoie la liste des partenaires.
description: Renvoie la liste des partenaires dont les informations sont publiques.
content:
application/json:
schema:
Expand Down
6 changes: 3 additions & 3 deletions src/controllers/tournaments/openapi.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/tournaments:
get:
summary: Renvoie les informations des tournois, des teams, des casters et des joueurs.
description: Renvoie les informations des tournois, des teams, des casters et des joueurs.
summary: Renvoie les informations des tournois, des teams, des casters et des joueurs dont les informations sont publiques.
description: Renvoie les informations des tournois, des teams, des casters et des joueurs dont les informations sont publiques.
tags:
- Tournaments
responses:
200:
description: Renvoie les informations des tournois, des teams, des casters et des joueurs.
description: Renvoie les informations des tournois, des teams, des casters et des joueurs dont les informations sont publiques.
content:
application/json:
schema:
Expand Down
2 changes: 1 addition & 1 deletion src/middlewares/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const isLoginAllowed = async (request: Request, response: Response, next:
const login = (await fetchSetting('login')).value;
const { user } = getRequestInfo(response);

if (login || (user.permissions && user.permissions.length > 0)) {
if (login || (user && user.permissions && user.permissions.length > 0)) {
return next();
}
return forbidden(response, Error.LoginNotAllowed);
Expand Down
2 changes: 1 addition & 1 deletion src/operations/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ const setSettingAllowed = (id: string, allowed: boolean): PrismaPromise<Setting>

export const setLoginAllowed = (allowed: boolean): PrismaPromise<Setting> => setSettingAllowed('login', allowed);
export const setShopAllowed = (allowed: boolean): PrismaPromise<Setting> => setSettingAllowed('shop', allowed);
export const setDisplayTrombi = (allowed: boolean): PrismaPromise<Setting> => setSettingAllowed('trombi', allowed);
export const setTrombiAllowed = (allowed: boolean): PrismaPromise<Setting> => setSettingAllowed('trombi', allowed);
File renamed without changes.
6 changes: 3 additions & 3 deletions tests/admin/users/replace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ describe('POST /admin/users/:userId/replace', () => {

before(async () => {
team = await createFakeTeam({ locked: true });
registerRole(team.discordRoleId);
registerRole(team.discordRoleId!);
user = getCaptain(team);
targetUser = await createFakeUser({ paid: true });
admin = await createFakeUser({ permissions: [Permission.admin] });
Expand All @@ -39,9 +39,9 @@ describe('POST /admin/users/:userId/replace', () => {
discordRoleId: registerRole(),
},
})
).discordRoleId;
).discordRoleId!;

registerMember(user.discordId, [team.discordRoleId, tournamentDiscordId]);
registerMember(user.discordId!, [team.discordRoleId!, tournamentDiscordId]);
});

after(async () => {
Expand Down
30 changes: 16 additions & 14 deletions tests/admin/users/updateUser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe('PATCH /admin/users/:userId', () => {

before(async () => {
user = await createFakeUser();
registerMember(user.discordId);
registerMember(user.discordId!);
const admin = await createFakeUser({ permissions: [Permission.admin] });
adminToken = generateToken(admin);
const anim = await createFakeUser({ permissions: [Permission.anim] });
Expand Down Expand Up @@ -106,7 +106,7 @@ describe('PATCH /admin/users/:userId', () => {

expect(body.type).to.be.equal(validBody.type);
expect(body.place).to.be.equal(validBody.place);
expect(body.permissions).to.have.same.members(validBody.permissions);
expect(body.permissions).to.have.same.members(validBody.permissions!);
expect(body.age).to.be.equal(validBody.age);
expect(body.customMessage).to.be.equal(validBody.customMessage);
expect(body.email).to.be.equal(validBody.email);
Expand All @@ -131,7 +131,7 @@ describe('PATCH /admin/users/:userId', () => {

it('should update the user and remove him from his team', async () => {
const team = await createFakeTeam({ members: 2, locked: true });
registerRole(team.discordRoleId);
registerRole(team.discordRoleId!);

tournamentDiscordId = registerRole();

Expand All @@ -144,17 +144,17 @@ describe('PATCH /admin/users/:userId', () => {
},
});
const teamMember = team.players.find((member) => member.id !== team.captainId);
registerMember(teamMember.discordId, [team.discordRoleId, tournamentDiscordId]);
registerMember(teamMember!.discordId!, [team.discordRoleId!, tournamentDiscordId]);

const { body } = await request(app)
.patch(`/admin/users/${teamMember.id}`)
.patch(`/admin/users/${teamMember!.id}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({
type: UserType.spectator,
})
.expect(200);

const updatedUser = await userOperations.fetchUser(teamMember.id);
const updatedUser = await userOperations.fetchUser(teamMember!.id);

expect(body.type).to.be.equal(UserType.spectator);
expect(body.type).to.be.equal(updatedUser.type);
Expand Down Expand Up @@ -192,8 +192,8 @@ describe('PATCH /admin/users/:userId', () => {
const team = await createFakeTeam({ members: 1, locked: true });
// tournament id has already been given
const [teamMember] = team.players;
registerRole(team.discordRoleId);
registerMember(teamMember.discordId, [team.discordRoleId, tournamentDiscordId]);
registerRole(team.discordRoleId!);
registerMember(teamMember!.discordId!, [team.discordRoleId!, tournamentDiscordId]);

const newAccount = registerMember();

Expand All @@ -206,18 +206,20 @@ describe('PATCH /admin/users/:userId', () => {
.expect(200);

expect(body.discordId).to.be.equal(newAccount);
deleteRole(team.discordRoleId);
deleteRole(team.discordRoleId!);
});

it('should be able to update discordId only (team locked, was not synced)', async () => {
const team = await createFakeTeam({ members: 1, locked: true });
// tournament id has already been given
const [teamMember] = team.players;
registerRole(team.discordRoleId);
registerMember(teamMember.discordId);
registerRole(team.discordRoleId!);
registerMember(teamMember!.discordId!);

const newAccount = registerMember();

console.log(newAccount);

Check warning on line 221 in tests/admin/users/updateUser.test.ts

View workflow job for this annotation

GitHub Actions / lint (18)

Unexpected console statement

const { body } = await request(app)
.patch(`/admin/users/${teamMember.id}`)
.send({
Expand All @@ -227,15 +229,15 @@ describe('PATCH /admin/users/:userId', () => {
.expect(200);

expect(body.discordId).to.be.equal(newAccount);
deleteRole(team.discordRoleId);
deleteRole(team.discordRoleId!);
});

it('should be able to update discordId only (team locked, left discord server)', async () => {
const team = await createFakeTeam({ members: 1, locked: true });
// tournament id has already been given
const [teamMember] = team.players;
kickMember(teamMember.discordId);
registerRole(team.discordRoleId);
kickMember(teamMember!.discordId!);
registerRole(team.discordRoleId!);

const newDiscordId = registerMember();

Expand Down
16 changes: 7 additions & 9 deletions tests/discord.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { decode } from 'querystring';
// import axios from 'axios';
import axios from 'axios';
import nock from 'nock';
import type {
DiscordAuthorizationData,
Expand Down Expand Up @@ -148,17 +148,15 @@ const computeRateLimitHeader = (enforceRateLimit = false): nock.ReplyHeaders =>
* and enables/handles http requests to the 'fake discord api'.
*/
const listen = () => {
// eslint-disable-next-line global-require
// TODO: fix this for nexts versions of axios
// axios.defaults.adapter = require('axios/lib/adapters/http');
axios.defaults.adapter = 'http';
nock('https://discord.com/api/v9')
.persist()

// Get GuildMember https://discord.com/developers/docs/resources/guild#get-guild-member
.get(/\/guilds\/\d+\/members\/\d+/)
.reply((uri) => {
if (rateLimitRemainingRequests < 0) return [429, null, computeRateLimitHeader(true)];
const discordMemberId = uri.match(/\d+$/)[0];
const discordMemberId = uri.match(/\d+$/)![0];
const discordMember = members.find((member) => member.user.id === discordMemberId);
return [
discordMember ? 200 : 404,
Expand All @@ -174,10 +172,10 @@ const listen = () => {
.delete(/\/guilds\/\d+\/members\/\d+\/roles\/\d+/)
.reply((uri) => {
if (rateLimitRemainingRequests < 0) return [429, null, computeRateLimitHeader(true)];
const [, discordMemberId, discordRoleId] = /(\d+)\/[^/]*\/(\d+)$/.exec(uri);
const [, discordMemberId, discordRoleId] = /(\d+)\/[^/]*\/(\d+)$/.exec(uri)!;
const discordMember = members.find((member) => member.user.id === discordMemberId);
const roleExists = roles.includes(discordRoleId);
if (roleExists) discordMember.roles.splice(discordMember.roles.indexOf(discordRoleId, 1));
if (roleExists) discordMember!.roles.splice(discordMember!.roles.indexOf(discordRoleId, 1));
return [
roleExists && discordMember ? 204 : 404,
roleExists && discordMember
Expand Down Expand Up @@ -286,10 +284,10 @@ const listen = () => {
.put(/\/guilds\/\d+\/members\/\d+\/roles\/\d+/)
.reply((uri) => {
if (rateLimitRemainingRequests < 0) return [429, null, computeRateLimitHeader(true)];
const [, discordMemberId, discordRoleId] = /(\d+)\/[^/]*\/(\d+)$/.exec(uri);
const [, discordMemberId, discordRoleId] = /(\d+)\/[^/]*\/(\d+)$/.exec(uri)!;
const discordMember = members.find((member) => member.user.id === discordMemberId);
const roleExists = roles.includes(discordRoleId);
if (roleExists) discordMember.roles.push(discordRoleId);
if (roleExists) discordMember!.roles.push(discordRoleId);
return [
roleExists && discordMember ? 204 : 404,
roleExists && discordMember
Expand Down
2 changes: 1 addition & 1 deletion tests/fake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ import { createFakeTeam, createFakeUser } from './utils';

// Create 10 users without team and 30 orgas
for (let standAloneUser = 0; standAloneUser < 10; standAloneUser += 1) {
await createFakeUser({ type: null, password: defaultPassword });
await createFakeUser({ type: undefined, password: defaultPassword });
}

// Add fake users (with sufficient length to be allowed in the database)
Expand Down
4 changes: 2 additions & 2 deletions tests/middlewares.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe('Test middlewares', () => {
});

it("should reject a wrong token because it's expired", async () => {
const token = jwt.sign({ userId: 'A1B2C3' }, env.jwt.secret, {
const token = jwt.sign({ userId: 'A1B2C3' }, env.jwt.secret!, {
expiresIn: '1ms',
});

Expand All @@ -63,7 +63,7 @@ describe('Test middlewares', () => {

// This case should never happen. (Auth as a deleted user)
it('should tell the user does not exists', async () => {
const token = jwt.sign({ userId: 'A1B2C3' }, env.jwt.secret, {
const token = jwt.sign({ userId: 'A1B2C3' }, env.jwt.secret!, {
expiresIn: env.jwt.expires,
});

Expand Down
7 changes: 5 additions & 2 deletions tests/root/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@ describe('GET /settings', () => {
it('should return 200 with an object', async () => {
await settingsOperations.setLoginAllowed(false);
await settingsOperations.setShopAllowed(false);
await settingsOperations.setTrombiAllowed(false);

await request(app).get('/settings').expect(200, { shop: false, login: false });
await request(app).get('/settings').expect(200, { shop: false, login: false, trombi: false });
});

it('should return the updated value', async () => {
await settingsOperations.setLoginAllowed(true);
await settingsOperations.setShopAllowed(true);
await request(app).get('/settings').expect(200, { shop: true, login: true });
await settingsOperations.setTrombiAllowed(true);

await request(app).get('/settings').expect(200, { shop: true, login: true, trombi: true });
});

it('should return an internal server error', async () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const generateFakeUserData = (data: FakeUserData, salt: Promise<string>) => {
* https://github.com/faker-js/faker/blob/main/src/modules/internet/index.ts#L129)
* We update the result to match our username regular expression:
* replace dots with dashes and remove trailing chars */
username: data.username || faker.internet.userName().replaceAll('.', '-').slice(0, 16),
username: data.username || faker.internet.userName().replace('.', '-').slice(0, 16),
firstname: data.firstname || faker.person.firstName(),
lastname: data.lastname || faker.person.lastName(),
email: data.email || faker.internet.email(),
Expand Down
4 changes: 2 additions & 2 deletions tests/utils/pdf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ describe('Tests the PDF utils', () => {
{
itemId: 'ticket-player',
quantity: 1,
price: (await fetchAllItems()).find((item) => item.id === 'ticket-player').price,
price: (await fetchAllItems()).find((item) => item.id === 'ticket-player')!.price,
forUserId: user.id,
},
]);
Expand All @@ -54,7 +54,7 @@ describe('Tests the PDF utils', () => {
{
itemId: 'ticket-player',
quantity: 1,
price: (await fetchAllItems()).find((item) => item.id === 'ticket-player').price,
price: (await fetchAllItems()).find((item) => item.id === 'ticket-player')!.price,
forUserId: user.id,
},
]);
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"removeComments": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es2021",
"target": "ES2021",
"strict": true,
"strictNullChecks": false,
"emitDecoratorMetadata": true,
Expand Down

0 comments on commit 5611702

Please sign in to comment.