Skip to content

Commit a5885cb

Browse files
authored
V0.5 (#20)
# Nova Versão v0.5 ## Objetivo Principal: O foco principal nesta versão foi a implementação de testes unitários e de integração para facilitar futuras manutenções da aplicação. ## Novas Implementações: - Adicionados novos pacotes npm: - `babel-jest` - Introduzido um banco de dados específico para a execução dos testes da aplicação. - Adicionado o arquivo `test.env` para ser utilizado nos testes. - Implementada lógica para a cópia do banco de dados de testes para a pasta da aplicação. - Implementada lógica para remoção do banco de dados de testes copiado para dentro da aplicação. - Adicionado testes de integração para todos os endpoints da aplicação. - Adicionado testes unitários para os principais métodos de validação e de transações com banco de dados. - Implementado GitHub Action que é executada sempre que um Pull Request é aberto para a branch Main. Em caso de falha nos testes, o Pull Request é automaticamente fechado e negado. ## Refatorações: - Atualizados os arquivos `env` para que cada um contenha sua própria `API_KEY` específica. - Modificado o arquivo `jest.config.js` para atender às necessidades do projeto. - Alterado o script 'test' contido no arquivo `package.json` para execução dos testes implementados. - Adicionadas novas constantes ao projeto. ## Correções de Bugs: - Ajustes nos arquivos `env` para garantir que as propriedades `MNG_AUTHENTICATION` e `API_KEY` não sejam definidas como vazias. A mesma correção foi aplicada na classe `ConstantUtil`. - Correção no método `valDateTimeRange`: identificou-se que, caso uma das datas não fosse informada, o método retornava sucesso. - Correção no método `find` para que ele retorne insucesso caso seja informado um "param" inválido. - Correção no método `validateRequest`, onde o memo só aceitava a rota `/health-check/`.
1 parent 920aa6e commit a5885cb

25 files changed

+1237
-31
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
name: Verify pull request
2+
3+
on:
4+
pull_request:
5+
branches:
6+
- main
7+
jobs:
8+
install-dependencies-run-tests:
9+
runs-on: ubuntu-latest
10+
11+
steps:
12+
- name: Checkout do código
13+
uses: actions/checkout@v4
14+
15+
- name: Use Node.js
16+
uses: actions/setup-node@v3
17+
with:
18+
node-version: "18.x"
19+
20+
- name: Install dependencies
21+
run: npm i --exact
22+
working-directory: ./src
23+
24+
- name: Run tests
25+
run: npm test || exit 1
26+
working-directory: ./src
27+
28+
- name: Comment on Pull Request
29+
if: ${{ success() }}
30+
uses: actions/github-script@v7
31+
with:
32+
github-token: ${{ secrets.GITHUB_TOKEN }}
33+
script: |
34+
const time = new Date().toLocaleString();
35+
await github.rest.issues.createComment({
36+
issue_number: context.issue.number,
37+
owner: context.repo.owner,
38+
repo: context.repo.repo,
39+
body: `${time}\nOs testes foram todos executados com sucesso. Aguarde a análise do PR`
40+
})
41+
42+
- name: Close Pull Request on Test Failure
43+
if: ${{ failure() }}
44+
uses: actions/github-script@v7
45+
with:
46+
github-token: ${{ secrets.GITHUB_TOKEN }}
47+
script: |
48+
await github.rest.issues.createComment({
49+
issue_number: context.payload.pull_request.number,
50+
owner: context.repo.owner,
51+
repo: context.repo.repo,
52+
body: `${new Date().toLocaleString()}\nOs testes falharam. Este pull request será fechado automaticamente.`
53+
});
54+
await github.rest.pulls.update({
55+
pull_number: context.payload.pull_request.number,
56+
owner: context.repo.owner,
57+
repo: context.repo.repo,
58+
state: 'closed'
59+
});
64 KB
Binary file not shown.

src/__test__/globalSetup.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/* eslint-disable no-console */
2+
const fs = require('fs');
3+
const { default: app } = require('../app/app');
4+
const { sourceTestDbPath, targetTestDbPath } = require('./testUtil');
5+
const { default: constantUtil } = require('../app/utils/constant.util');
6+
7+
module.exports = async () => {
8+
// Configurar a variável de ambiente NODE_ENV para 'test' no início dos testes
9+
process.env.NODE_ENV = 'test';
10+
11+
// Copia o banco de dados de testes para ser usado na aplicação
12+
fs.copyFileSync(sourceTestDbPath, targetTestDbPath);
13+
14+
// Inicia o app
15+
app.start();
16+
17+
// Salva o resultado do server.listen em uma var para usar depois
18+
// em outros pontos dos testes automatizados
19+
global.server = app.server.listen(constantUtil.NuPort, () => {
20+
console.log(constantUtil.MsgStartAPI);
21+
});
22+
};

src/__test__/globalTeardown.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/* eslint-disable no-console */
2+
const fs = require('fs').promises;
3+
const { default: utils } = require('../app/utils');
4+
const { targetTestDbPath, testDbFileName } = require('./testUtil');
5+
6+
module.exports = async () => {
7+
// Faz isso para encerrar o express no final dos testes
8+
await global.server.close();
9+
10+
// Apaga os arquivos zips que foram criados durante os testes
11+
await utils.deleteOldZip();
12+
13+
try {
14+
// Aguarda 2 segundos para remover o db de testes
15+
setTimeout(() => {
16+
fs.unlink(targetTestDbPath);
17+
console.log(`file ${testDbFileName} has been deleted`);
18+
}, 2000);
19+
} catch (err) {
20+
console.error(err);
21+
}
22+
};
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
import supertest from 'supertest';
2+
3+
const { apiKey, authorization, urlDBDelete, urlDBBackup, urlDBInfo } = require('../testUtil');
4+
5+
describe('Database-Delete Check BadRequest', () => {
6+
it('should return status 400 - DELETE /', async () => {
7+
const response = await supertest(global.server)
8+
.delete(`${urlDBDelete}?table_name=${apiKey}`)
9+
.set('API-KEY', `${apiKey}`)
10+
.set('AUTHORIZATION', `${authorization}`);
11+
expect(response.status).toBe(400);
12+
});
13+
14+
it('should return status 400 - DELETE /', async () => {
15+
const response = await supertest(global.server)
16+
.delete(`${urlDBDelete}?table_name=LOG_ERRORS`)
17+
.set('API-KEY', `${apiKey}`)
18+
.set('AUTHORIZATION', `${authorization}`);
19+
expect(response.status).toBe(400);
20+
});
21+
});
22+
23+
describe('Database-backup Endpoints Check Authorization', () => {
24+
it('should return status 401 - GET /', async () => {
25+
const response = await supertest(global.server).get(`${urlDBBackup}`);
26+
expect(response.status).toBe(401);
27+
});
28+
29+
it('should return status 401 - GET /', async () => {
30+
const response = await supertest(global.server)
31+
.get(`${urlDBBackup}`)
32+
.set('x-cookie', `${authorization}`)
33+
.set('API-KEY', `${authorization}`);
34+
expect(response.status).toBe(401);
35+
});
36+
37+
it('should return status 401 - GET /', async () => {
38+
const response = await supertest(global.server)
39+
.get(`${urlDBBackup}`)
40+
.set('API-KEY', `${apiKey}`)
41+
.set('x-cookie', `${authorization}`);
42+
expect(response.status).toBe(401);
43+
});
44+
45+
it('should return status 401 - GET /', async () => {
46+
const response = await supertest(global.server)
47+
.get(`${urlDBBackup}`)
48+
.set('API-KEY', '')
49+
.set('AUTHORIZATION', `${authorization}`);
50+
expect(response.status).toBe(401);
51+
});
52+
53+
it('should return status 401 - GET /', async () => {
54+
const response = await supertest(global.server)
55+
.get(`${urlDBBackup}`)
56+
.set('API-KEY', '')
57+
.set('AUTHORIZATION', '');
58+
expect(response.status).toBe(401);
59+
});
60+
61+
//
62+
});
63+
64+
describe('Database-Delete Endpoints Check Authorization', () => {
65+
it('should return status 401 - DELETE /', async () => {
66+
const response = await supertest(global.server).delete(`${urlDBDelete}`);
67+
expect(response.status).toBe(401);
68+
});
69+
70+
it('should return status 401 - DELETE /', async () => {
71+
const response = await supertest(global.server)
72+
.delete(`${urlDBDelete}`)
73+
.set('API-KEY', `${authorization}`);
74+
expect(response.status).toBe(401);
75+
});
76+
77+
it('should return status 401 - DELETE /', async () => {
78+
const response = await supertest(global.server)
79+
.delete(`${urlDBDelete}`)
80+
.set('API-KEY', `${apiKey}`)
81+
.set('x-cookie', `${authorization}`);
82+
expect(response.status).toBe(401);
83+
});
84+
85+
it('should return status 401 - DELETE /', async () => {
86+
const response = await supertest(global.server)
87+
.delete(`${urlDBDelete}`)
88+
.set('API-KEY', '')
89+
.set('AUTHORIZATION', `${authorization}`);
90+
expect(response.status).toBe(401);
91+
});
92+
93+
it('should return status 401 - DELETE /', async () => {
94+
const response = await supertest(global.server)
95+
.delete(`${urlDBDelete}`)
96+
.set('API-KEY', '')
97+
.set('AUTHORIZATION', '');
98+
expect(response.status).toBe(401);
99+
});
100+
});
101+
102+
describe('Database-Info Endpoints Check Authorization', () => {
103+
it('should return status 401 - GET /', async () => {
104+
const response = await supertest(global.server).get(`${urlDBInfo}`);
105+
expect(response.status).toBe(401);
106+
});
107+
108+
it('should return status 401 - GET /', async () => {
109+
const response = await supertest(global.server)
110+
.get(`${urlDBInfo}`)
111+
.set('x-cookie', `${apiKey}`)
112+
.set('API-KEY', `${authorization}`);
113+
114+
expect(response.status).toBe(401);
115+
});
116+
117+
it('should return status 401 - GET /', async () => {
118+
const response = await supertest(global.server).get(`${urlDBInfo}`).set('API-KEY', `${apiKey}`);
119+
120+
expect(response.status).toBe(401);
121+
});
122+
123+
it('should return status 401 - GET /', async () => {
124+
const response = await supertest(global.server)
125+
.get(`${urlDBInfo}`)
126+
.set('API-KEY', '')
127+
.set('AUTHORIZATION', `${authorization}`);
128+
expect(response.status).toBe(401);
129+
});
130+
131+
it('should return status 401 - GET /', async () => {
132+
const response = await supertest(global.server)
133+
.get(`${urlDBInfo}`)
134+
.set('API-KEY', '')
135+
.set('AUTHORIZATION', '');
136+
expect(response.status).toBe(401);
137+
});
138+
});
139+
140+
describe('Database Endpoints Check OK', () => {
141+
it('should return status 200 - GET /', async () => {
142+
const response = await supertest(global.server)
143+
.get(`${urlDBInfo}`)
144+
.set('API-KEY', `${apiKey}`)
145+
.set('AUTHORIZATION', `${authorization}`);
146+
expect(response.status).toBe(200);
147+
});
148+
149+
it('should return status 200 - DELETE /', async () => {
150+
const response = await supertest(global.server)
151+
.delete(`${urlDBDelete}?table_name=log_error`)
152+
.set('API-KEY', `${apiKey}`)
153+
.set('AUTHORIZATION', `${authorization}`);
154+
expect(response.status).toBe(200);
155+
});
156+
157+
it('should return status 200 - DELETE /', async () => {
158+
const response = await supertest(global.server)
159+
.delete(`${urlDBDelete}?table_name=log_event`)
160+
.set('API-KEY', `${apiKey}`)
161+
.set('AUTHORIZATION', `${authorization}`);
162+
expect(response.status).toBe(200);
163+
});
164+
});
165+
166+
describe('Database-backup Endpoints Check 200 || 429', () => {
167+
it('should return status 200 - GET /', async () => {
168+
const response = await supertest(global.server)
169+
.get(`${urlDBBackup}`)
170+
.set('API-KEY', `${apiKey}`)
171+
.set('AUTHORIZATION', `${authorization}`);
172+
expect(response.status).toBe(200);
173+
});
174+
175+
it('should return status 429 - GET /', async () => {
176+
const response = await supertest(global.server)
177+
.get(`${urlDBBackup}`)
178+
.set('API-KEY', `${apiKey}`)
179+
.set('AUTHORIZATION', `${authorization}`);
180+
expect(response.status).toBe(429);
181+
});
182+
});
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import supertest from 'supertest';
2+
3+
describe('health-check Endpoint', () => {
4+
it('should return status 200', async () => {
5+
const response = await supertest(global.server).get('/health-check');
6+
expect(response.status).toBe(200);
7+
});
8+
});

0 commit comments

Comments
 (0)