Skip to content

Commit

Permalink
test: fix tests after removing mock dependencies
Browse files Browse the repository at this point in the history
- fix: seed:run validate all modules before run.
- fix: re-run seed triggers unique key constraint (email)
- docs: example for vscode launch.json
  • Loading branch information
yxuo committed Jan 19, 2024
1 parent 1e5edde commit 4fced53
Show file tree
Hide file tree
Showing 26 changed files with 235 additions and 172 deletions.
93 changes: 79 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,16 @@ O [Projeto do App CCT](https://github.com/RJ-SMTR/app-cct) consome esta API.
* [API CCT](#api-cct)
* [Descrição](#descrição)
* [Table of Contents](#table-of-contents)
* [Quick run](#quick-run)
* [Executar rapidamente](#executar-rapidamente)
* [Desenvolvimento confortável](#desenvolvimento-confortável)
* [Links](#links)
* [Automatic update of dependencies](#automatic-update-of-dependencies)
* [Banco de dados](#banco-de-dados)
* [Testes](#testes)
* [Depurando testes](#depurando-testes)
* [Testes no Docker](#testes-no-docker)
* [Benchmarking de testes](#benchmarking-de-testes)

## Quick run
## Executar rapidamente

```bash
git clone --depth 1 .git my-app
Expand All @@ -38,7 +37,7 @@ cp env-example .env
docker compose up -d
```

For check status run
Para verificar status:

```bash
docker compose logs
Expand All @@ -62,6 +61,14 @@ Executar contêiner adicional:
docker compose up -d postgres adminer maildev
```

Login no adminer (login de exemplo):

- Sistema: `PostgreSQL`
- Servidor: `postgres`
- Usuário: `root`
- Senha: `secret`
- Base de dados: `api`

Configurar projeto:

```bash
Expand Down Expand Up @@ -90,10 +97,6 @@ npm run seed:run user mailhistory
- Adminer (client for DB): http://localhost:8080
- Maildev: http://localhost:1080

## Automatic update of dependencies

If you want to automatically update dependencies, you can connect [Renovate](https://github.com/marketplace/renovate) for your project.

## Banco de dados

Generate migration
Expand Down Expand Up @@ -138,7 +141,10 @@ npm run test:e2e

### Depurando testes

Exemplo de configuração no VSCode:
**Exemplo de configuração no VSCode:**

Requisitos
- Extensão [Command Variable](ttps://marketplace.visualstudio.com/items?itemName=rioj7.command-variable)

.vscode/launch.json
```jsonc
Expand All @@ -152,7 +158,7 @@ Exemplo de configuração no VSCode:
"args": [
"--runInBand"
],
"cwd": "${workspaceFolder}",
"cwd": "${fileDirname}",
"runtimeArgs": [
"--inspect-brk",
"${workspaceFolder}/node_modules/jest/bin/jest.js",
Expand All @@ -162,30 +168,89 @@ Exemplo de configuração no VSCode:
"internalConsoleOptions": "neverOpen",
"attachSimplePort": 9229,
},
{
"name": "Jest test: Teste específico",
"type": "node",
"request": "launch",
"args": [
"--runInBand"
],
"cwd": "${fileDirname}",
"runtimeArgs": [
"--inspect-brk",
"${workspaceFolder}/node_modules/jest/bin/jest.js",
"${fileBasenameNoExtension}",
"--testNamePattern",
"\".*${selectedText}\""
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"attachSimplePort": 9229,
},
{
"name": "Jest e2e: Arquivo Atual",
"type": "node",
"request": "launch",
"args": [
"--runInBand"
],
"cwd": "${workspaceFolder}/api-cct",
"cwd": "${workspaceFolder}",
"runtimeArgs": [
"--inspect-brk",
"${workspaceFolder}/node_modules/jest/bin/jest.js",
"--config",
"${workspaceFolder}/test/jest-e2e.json",
"${fileBasenameNoExtension}"
"${command:extension.commandvariable.file.relativeFilePosix}"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"attachSimplePort": 9229,
},
{
"name": "Jest e2e: Teste específico",
"type": "node",
"request": "launch",
"args": [
"--runInBand"
],
"cwd": "${workspaceFolder}",
"runtimeArgs": [
"--inspect-brk",
"${workspaceFolder}/node_modules/jest/bin/jest.js",
"--config",
"${workspaceFolder}/test/jest-e2e.json",
"${command:extension.commandvariable.file.relativeFilePosix}",
"--testNamePattern",
"\".*${selectedText}\""
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"attachSimplePort": 9229
},
{
"name": "Debug seed:run",
"type": "node",
"request": "launch",
"runtimeArgs": [
"-r",
"tsconfig-paths/register"
],
"args": [
"${workspaceFolder}/src/database/seeds/run-seed.ts"
],
"cwd": "${workspaceFolder}",
"env": {
"NODE_ENV": "development"
},
"sourceMaps": true,
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
]
}
]
],
}
```


## Testes no Docker

```bash
Expand Down
36 changes: 22 additions & 14 deletions docs/installing-and-running.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# Installation

---
# Instalação

## Table of Contents

- [Comfortable development](#comfortable-development)
- [Quick run](#quick-run)
- [Links](#links)
* [Instalação](#instalação)
* [Table of Contents](#table-of-contents)
* [Comfortable development](#comfortable-development)
* [Quick run](#quick-run)
* [Video guideline](#video-guideline)
* [Links](#links)

---

Expand All @@ -18,48 +19,55 @@
git clone --depth 1 https://github.com/brocoders/nestjs-boilerplate.git my-app
```

1. Go to folder, and copy `env-example` as `.env`.
2. Go to folder, and copy `env-example` as `.env`.

```bash
cd my-app/
cp env-example .env
```

1. Change `DATABASE_HOST=postgres` to `DATABASE_HOST=localhost`
3. Change `DATABASE_HOST=postgres` to `DATABASE_HOST=localhost`

Change `MAIL_HOST=maildev` to `MAIL_HOST=localhost`

1. Run additional container:
4. Executar gerenciador de banco Adminer:

```bash
docker compose up -d postgres adminer maildev
```

1. Install dependency
Login no adminer (login de exemplo):
- Sistema: `PostgreSQL`
- Servidor: `postgres`
- Usuário: `root`
- Senha: `secret`
- Base de dados: `api`

5. Install dependency

```bash
npm install
```

1. Run migrations
6. Run migrations

```bash
npm run migration:run
```

1. Run seeds
7. Run seeds

```bash
npm run seed:run
```

1. Run app in dev mode
8. Run app in dev mode

```bash
npm run start:dev
```

1. Open http://localhost:3000
9. Open http://localhost:3000

---

Expand Down
8 changes: 5 additions & 3 deletions src/auth-licensee/auth-licensee.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class AuthLicenseeService {
private mailHistoryService: MailHistoryService,
private baseValidator: BaseValidator,
private mailService: MailService,
) { }
) {}

async validateLogin(
loginDto: AuthLicenseeLoginDto,
Expand Down Expand Up @@ -129,8 +129,10 @@ export class AuthLicenseeService {
const user = await this.usersService.getOne({ id: invite.user.id });

if (
user.id !== invite.user.id
|| !user.permitCode || !user.fullName || !user.email
user.id !== invite.user.id ||
!user.permitCode ||
!user.fullName ||
!user.email
) {
throw new HttpException(
{
Expand Down
1 change: 1 addition & 0 deletions src/config/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
enum Environment {
Development = 'development',
Production = 'production',
Local = 'local',
Test = 'test',
}

Expand Down
4 changes: 4 additions & 0 deletions src/database/seeds/bank/bank-seed.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export class BankSeedService {
private repository: Repository<Bank>,
) {}

async validateRun() {
return Promise.resolve(true);
}

async run() {
const items = bankData
.filter((i) => !isNaN(i.ispb))
Expand Down
4 changes: 4 additions & 0 deletions src/database/seeds/info/info-seed.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export class InfoSeedService {
private repository: Repository<Info>,
) {}

async validateRun() {
return Promise.resolve(true);
}

async run() {
let id = 1;
for (const item of infoSeedData) {
Expand Down
4 changes: 4 additions & 0 deletions src/database/seeds/mail-count/mail-count-seed.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ export class MailCountSeedService {
private dataService: MailCountSeedDataService,
) {}

async validateRun() {
return Promise.resolve(true);
}

async run() {
let id = 1;
for (const item of this.dataService.getDataFromConfig()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export class InviteStatusSeedService {
private repository: Repository<InviteStatus>,
) {}

async validateRun() {
return Promise.resolve(true);
}

async run() {
for (const value in InviteStatusEnum) {
if (isNaN(Number(value))) {
Expand Down
15 changes: 5 additions & 10 deletions src/database/seeds/mail-history/mail-history-seed.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,11 @@ export class MailHistorySeedService {
private userSeedDataService: UserSeedDataService,
) {}

async validateRun() {
return global.force || (await this.usersRepository.count()) === 0;
}

async run() {
if (!(await this.validateRun())) {
this.logger.log('Database is not empty. Aborting seed...');
return;
}
this.logger.log('run()');
for (const item of this.mhSeedDataService.getDataFromConfig()) {
const itemUser = await this.getHistoryUser(item);
const itemSeedUser = this.userSeedDataService
Expand All @@ -47,7 +46,7 @@ export class MailHistorySeedService {
if (itemSeedUser?.inviteStatus) {
newItem.inviteStatus = itemSeedUser.inviteStatus;
}
this.logger.log(`Creating user: ${JSON.stringify(newItem)}`);
this.logger.log(`Creating mail history: ${JSON.stringify(newItem)}`);
await this.mailHistoryRepository.save(
this.mailHistoryRepository.create(newItem),
);
Expand Down Expand Up @@ -77,8 +76,4 @@ export class MailHistorySeedService {
});
return users[0];
}

async validateRun() {
return global.force || (await this.usersRepository.count()) === 0;
}
}
Loading

0 comments on commit 4fced53

Please sign in to comment.