-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
# 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/`.
- Loading branch information
Showing
25 changed files
with
1,237 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
name: Verify pull request | ||
|
||
on: | ||
pull_request: | ||
branches: | ||
- main | ||
jobs: | ||
install-dependencies-run-tests: | ||
runs-on: ubuntu-latest | ||
|
||
steps: | ||
- name: Checkout do código | ||
uses: actions/checkout@v4 | ||
|
||
- name: Use Node.js | ||
uses: actions/setup-node@v3 | ||
with: | ||
node-version: "18.x" | ||
|
||
- name: Install dependencies | ||
run: npm i --exact | ||
working-directory: ./src | ||
|
||
- name: Run tests | ||
run: npm test || exit 1 | ||
working-directory: ./src | ||
|
||
- name: Comment on Pull Request | ||
if: ${{ success() }} | ||
uses: actions/github-script@v7 | ||
with: | ||
github-token: ${{ secrets.GITHUB_TOKEN }} | ||
script: | | ||
const time = new Date().toLocaleString(); | ||
await github.rest.issues.createComment({ | ||
issue_number: context.issue.number, | ||
owner: context.repo.owner, | ||
repo: context.repo.repo, | ||
body: `${time}\nOs testes foram todos executados com sucesso. Aguarde a análise do PR` | ||
}) | ||
- name: Close Pull Request on Test Failure | ||
if: ${{ failure() }} | ||
uses: actions/github-script@v7 | ||
with: | ||
github-token: ${{ secrets.GITHUB_TOKEN }} | ||
script: | | ||
await github.rest.issues.createComment({ | ||
issue_number: context.payload.pull_request.number, | ||
owner: context.repo.owner, | ||
repo: context.repo.repo, | ||
body: `${new Date().toLocaleString()}\nOs testes falharam. Este pull request será fechado automaticamente.` | ||
}); | ||
await github.rest.pulls.update({ | ||
pull_number: context.payload.pull_request.number, | ||
owner: context.repo.owner, | ||
repo: context.repo.repo, | ||
state: 'closed' | ||
}); |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
/* eslint-disable no-console */ | ||
const fs = require('fs'); | ||
const { default: app } = require('../app/app'); | ||
const { sourceTestDbPath, targetTestDbPath } = require('./testUtil'); | ||
const { default: constantUtil } = require('../app/utils/constant.util'); | ||
|
||
module.exports = async () => { | ||
// Configurar a variável de ambiente NODE_ENV para 'test' no início dos testes | ||
process.env.NODE_ENV = 'test'; | ||
|
||
// Copia o banco de dados de testes para ser usado na aplicação | ||
fs.copyFileSync(sourceTestDbPath, targetTestDbPath); | ||
|
||
// Inicia o app | ||
app.start(); | ||
|
||
// Salva o resultado do server.listen em uma var para usar depois | ||
// em outros pontos dos testes automatizados | ||
global.server = app.server.listen(constantUtil.NuPort, () => { | ||
console.log(constantUtil.MsgStartAPI); | ||
}); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
/* eslint-disable no-console */ | ||
const fs = require('fs').promises; | ||
const { default: utils } = require('../app/utils'); | ||
const { targetTestDbPath, testDbFileName } = require('./testUtil'); | ||
|
||
module.exports = async () => { | ||
// Faz isso para encerrar o express no final dos testes | ||
await global.server.close(); | ||
|
||
// Apaga os arquivos zips que foram criados durante os testes | ||
await utils.deleteOldZip(); | ||
|
||
try { | ||
// Aguarda 2 segundos para remover o db de testes | ||
setTimeout(() => { | ||
fs.unlink(targetTestDbPath); | ||
console.log(`file ${testDbFileName} has been deleted`); | ||
}, 2000); | ||
} catch (err) { | ||
console.error(err); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,182 @@ | ||
import supertest from 'supertest'; | ||
|
||
const { apiKey, authorization, urlDBDelete, urlDBBackup, urlDBInfo } = require('../testUtil'); | ||
|
||
describe('Database-Delete Check BadRequest', () => { | ||
it('should return status 400 - DELETE /', async () => { | ||
const response = await supertest(global.server) | ||
.delete(`${urlDBDelete}?table_name=${apiKey}`) | ||
.set('API-KEY', `${apiKey}`) | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(400); | ||
}); | ||
|
||
it('should return status 400 - DELETE /', async () => { | ||
const response = await supertest(global.server) | ||
.delete(`${urlDBDelete}?table_name=LOG_ERRORS`) | ||
.set('API-KEY', `${apiKey}`) | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(400); | ||
}); | ||
}); | ||
|
||
describe('Database-backup Endpoints Check Authorization', () => { | ||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server).get(`${urlDBBackup}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBBackup}`) | ||
.set('x-cookie', `${authorization}`) | ||
.set('API-KEY', `${authorization}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBBackup}`) | ||
.set('API-KEY', `${apiKey}`) | ||
.set('x-cookie', `${authorization}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBBackup}`) | ||
.set('API-KEY', '') | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBBackup}`) | ||
.set('API-KEY', '') | ||
.set('AUTHORIZATION', ''); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
// | ||
}); | ||
|
||
describe('Database-Delete Endpoints Check Authorization', () => { | ||
it('should return status 401 - DELETE /', async () => { | ||
const response = await supertest(global.server).delete(`${urlDBDelete}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - DELETE /', async () => { | ||
const response = await supertest(global.server) | ||
.delete(`${urlDBDelete}`) | ||
.set('API-KEY', `${authorization}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - DELETE /', async () => { | ||
const response = await supertest(global.server) | ||
.delete(`${urlDBDelete}`) | ||
.set('API-KEY', `${apiKey}`) | ||
.set('x-cookie', `${authorization}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - DELETE /', async () => { | ||
const response = await supertest(global.server) | ||
.delete(`${urlDBDelete}`) | ||
.set('API-KEY', '') | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - DELETE /', async () => { | ||
const response = await supertest(global.server) | ||
.delete(`${urlDBDelete}`) | ||
.set('API-KEY', '') | ||
.set('AUTHORIZATION', ''); | ||
expect(response.status).toBe(401); | ||
}); | ||
}); | ||
|
||
describe('Database-Info Endpoints Check Authorization', () => { | ||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server).get(`${urlDBInfo}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBInfo}`) | ||
.set('x-cookie', `${apiKey}`) | ||
.set('API-KEY', `${authorization}`); | ||
|
||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server).get(`${urlDBInfo}`).set('API-KEY', `${apiKey}`); | ||
|
||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBInfo}`) | ||
.set('API-KEY', '') | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(401); | ||
}); | ||
|
||
it('should return status 401 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBInfo}`) | ||
.set('API-KEY', '') | ||
.set('AUTHORIZATION', ''); | ||
expect(response.status).toBe(401); | ||
}); | ||
}); | ||
|
||
describe('Database Endpoints Check OK', () => { | ||
it('should return status 200 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBInfo}`) | ||
.set('API-KEY', `${apiKey}`) | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(200); | ||
}); | ||
|
||
it('should return status 200 - DELETE /', async () => { | ||
const response = await supertest(global.server) | ||
.delete(`${urlDBDelete}?table_name=log_error`) | ||
.set('API-KEY', `${apiKey}`) | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(200); | ||
}); | ||
|
||
it('should return status 200 - DELETE /', async () => { | ||
const response = await supertest(global.server) | ||
.delete(`${urlDBDelete}?table_name=log_event`) | ||
.set('API-KEY', `${apiKey}`) | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(200); | ||
}); | ||
}); | ||
|
||
describe('Database-backup Endpoints Check 200 || 429', () => { | ||
it('should return status 200 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBBackup}`) | ||
.set('API-KEY', `${apiKey}`) | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(200); | ||
}); | ||
|
||
it('should return status 429 - GET /', async () => { | ||
const response = await supertest(global.server) | ||
.get(`${urlDBBackup}`) | ||
.set('API-KEY', `${apiKey}`) | ||
.set('AUTHORIZATION', `${authorization}`); | ||
expect(response.status).toBe(429); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import supertest from 'supertest'; | ||
|
||
describe('health-check Endpoint', () => { | ||
it('should return status 200', async () => { | ||
const response = await supertest(global.server).get('/health-check'); | ||
expect(response.status).toBe(200); | ||
}); | ||
}); |
Oops, something went wrong.