Skip to content

Commit

Permalink
feat(test-utils): add functions to init and close containers from doc…
Browse files Browse the repository at this point in the history
…ker-compose for jest globaSetup
  • Loading branch information
rudemex committed Apr 15, 2023
1 parent 8693e8a commit 2acb148
Show file tree
Hide file tree
Showing 10 changed files with 185 additions and 10 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
"reflect-metadata": "^0.1.13",
"rxjs": "^7.5.5",
"shx": "^0.3.4",
"testcontainers": "^9.4.0",
"testcontainers": "^9.5.0",
"typeorm": "^0.3.13",
"uuid": "^9.0.0"
},
Expand Down Expand Up @@ -127,7 +127,7 @@
"prettier": "^2.8.7",
"rimraf": "^4.4.1",
"supertest": "^6.2.2",
"testcontainers": "^9.4.0",
"testcontainers": "^9.5.0",
"ts-jest": "^29.1.0",
"ts-loader": "^9.3.1",
"ts-node": "^10.9.0",
Expand Down
12 changes: 12 additions & 0 deletions packages/elk/src/elk/constants/elk.constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,15 @@ export const ELK_MODULE_OPTIONS = Symbol('ELK_MODULE_OPTIONS');

export const ELK_MSG_SUCCESSFULLY_CONNECTED = 'Connected successfully!:';
export const ELK_MSG_ERROR_CONNECTED = 'Could not establish a connection:';

/*
export const OMITS_IN_OPTIONS: string[] = ['indexDate', 'redact'];
export const DEFAULT_OPTIONS_REDACT = {
paths: [],
censor: '****',
remove: false,
};
export const DEFAULT_TIMEZONE = 'America/Argentina/Buenos_Aires';
export const DEFAULT_TIME_FORMAT = 'D tt'; // 4/10/2023 12:55:40 PM
*/
12 changes: 7 additions & 5 deletions packages/elk/src/elk/providers/elk-client.provider.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
import { Logger, Provider } from '@nestjs/common';
import { Client, ClientOptions } from '@elastic/elasticsearch';
import { v4 as uuid } from 'uuid';
import { InfoResponse } from '@elastic/elasticsearch/lib/api/types';

import {
ELK_MODULE_OPTIONS,
ELK_CLIENT,
ELK_MSG_ERROR_CONNECTED,
ELK_MSG_SUCCESSFULLY_CONNECTED,
} from '../constants/elk.constant';
import { v4 as uuid } from 'uuid';

export const createElkClient = (): Provider => ({
provide: ELK_CLIENT,
useFactory: async (options: ClientOptions) => {
const client = new Client({
useFactory: async (options: ClientOptions): Promise<Client> => {
const client: Client = new Client({
...options,
generateRequestId: () => uuid(),
});

/* istanbul ignore next */
client
.info()
.then((_response) =>
.then((_response: InfoResponse) =>
Logger.log(`${ELK_MSG_SUCCESSFULLY_CONNECTED} ${_response.name}`, 'ElkModule'),
)
.catch((_error) => {
.catch((_error): void => {
Logger.error(`${ELK_MSG_ERROR_CONNECTED} ${_error.message}`, 'ElkModule');
});

Expand Down
20 changes: 20 additions & 0 deletions packages/test-utils/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# docker-compose.yml - Only for local debug purposes
# docker-compose up -d elasticsearch kibana jaeger camunda redis mongo mysql postgres pgadmin
version: '3.9'

services:
mongo:
image: mongo:5.0
container_name: local-mongo
restart: always
ports:
- '27017:27017'
environment:
TZ: UTC
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: 123456
MONGO_INITDB_DATABASE: test_db
#logging:
# driver: none
#volumes:
# - ./.mongo_data:/data/db
4 changes: 2 additions & 2 deletions packages/test-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@
"@nestjs/platform-express": "^9.4.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.5.5",
"testcontainers": "^9.4.0"
"testcontainers": "^9.5.0"
},
"dependencies": {
"testcontainers": "^9.4.0"
"testcontainers": "^9.5.0"
},
"devDependencies": {
"@tresdoce-nestjs-toolkit/config": "^0.2.4",
Expand Down
2 changes: 1 addition & 1 deletion packages/test-utils/src/__mocks__/jest.mocks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { appConfigBase } from '../fixtures/appConfigBase';

export const config = jest.fn().mockImplementation(() => appConfigBase);
export const config = () => jest.fn().mockImplementation(() => appConfigBase);

export const executionContext: any = () => ({
switchToHttp: jest.fn().mockReturnThis(),
Expand Down
32 changes: 32 additions & 0 deletions packages/test-utils/src/__test__/globalTestContainers.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { closeDockerCompose, initDockerCompose } from '../testcontainers';
import path from 'path';
import { StartedDockerComposeEnvironment } from 'testcontainers';

describe('globalTestContainers', () => {
const composeFilePath = path.resolve(__dirname, '..', 'fixtures', 'docker-compose');
const composeFile = 'docker-compose.yml';

it('should be initialize service from docker-compose.yml', async () => {
const services = ['mongo'];
await initDockerCompose(services, composeFilePath, composeFile)();
expect(global.__TESTCONTAINERS__).toBeDefined();
expect(global.__TESTCONTAINERS__).toBeInstanceOf(StartedDockerComposeEnvironment);
await closeDockerCompose({ removeVolumes: false })();
});

it('should be initialize all services from docker-compose.yml', async () => {
const services = [];
await initDockerCompose(services, composeFilePath, composeFile)();
expect(global.__TESTCONTAINERS__).toBeDefined();
expect(global.__TESTCONTAINERS__).toBeInstanceOf(StartedDockerComposeEnvironment);
await closeDockerCompose({ removeVolumes: false })();
});

it('should be initialize services from docker-compose.yml in default path and filename', async () => {
const services = [];
await initDockerCompose(services)();
expect(global.__TESTCONTAINERS__).toBeDefined();
expect(global.__TESTCONTAINERS__).toBeInstanceOf(StartedDockerComposeEnvironment);
await closeDockerCompose({ removeVolumes: false })();
});
});
69 changes: 69 additions & 0 deletions packages/test-utils/src/fixtures/docker-compose/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# docker-compose.yml - Only for local debug purposes
# docker-compose up -d elasticsearch kibana jaeger camunda redis mongo mysql postgres pgadmin
version: '3.9'

services:
postgres:
image: postgres:13
container_name: local-postgres
restart: always
ports:
- '5432:5432'
environment:
TZ: UTC
POSTGRES_DB: my_db
POSTGRES_USER: root
POSTGRES_PASSWORD: 123456
#logging:
# driver: none
#volumes:
# - ./.postgres_data:/var/lib/postgresql/data

mysql:
image: mysql:5.7
container_name: local-mysql
restart: always
ports:
- '3306:3306'
environment:
TZ: UTC
MYSQL_ROOT_PASSWORD: 123456
MYSQL_DATABASE: my_db
MYSQL_PASSWORD: 123456
#MYSQL_USER: root
#volumes:
# - ./.mysql-data/db:/var/lib/mysql

mongo:
image: mongo:5.0
container_name: local-mongo
restart: always
ports:
- '27017:27017'
environment:
TZ: UTC
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: 123456
MONGO_INITDB_DATABASE: test_db
#logging:
# driver: none
#volumes:
# - ./.mongo_data:/data/db

redis:
image: redis:6.2-alpine
container_name: local-redis
restart: always
ports:
- '6379:6379'
environment:
TZ: UTC
REDIS_PORT: 6379
REDIS_PASSWORD: 123456
REDIS_HOST: cache
#REDIS_USERNAME: default
command: [ "redis-server", "--appendonly", "yes", "--requirepass","123456" ]
#logging:
# driver: none
#volumes:
# - ./.redis_data:/data
39 changes: 39 additions & 0 deletions packages/test-utils/src/testcontainers/globalTestContainersTD.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { DockerComposeEnvironment } from 'testcontainers';
import { DockerComposeDownOptions } from 'testcontainers/dist/src/test-container';
import * as _ from 'lodash';

export const initDockerCompose = (
_services?: Array<string>,
_composeFilePath = '.',
_composeFile = 'docker-compose.yml',
) => {
return async (): Promise<void> => {
console.info(`🐳 Initialize docker-compose...`);
!_.isEmpty(_services)
? console.log(`• Services from ${_composeFile}: ${_services.join(', ')}`)
: null;
try {
global.__TESTCONTAINERS__ = await new DockerComposeEnvironment(
_composeFilePath,
_composeFile,
).up(_services);
console.info(`✨ Container(s) initialized.`);
} catch (_error) {
/* istanbul ignore next */
console.error(`😰 Error initializing container(s): ${_error}`);
}
};
};

export const closeDockerCompose = (_options?: Partial<DockerComposeDownOptions>) => {
return async (): Promise<void> => {
console.info('🐳 Terminate docker-compose...');
try {
await global.__TESTCONTAINERS__.down(_options);
console.info(`👌 Container(s) stopped successfully.`);
} catch (_error) {
/* istanbul ignore next */
console.error(`😒 Container(s) not initialized.`);
}
};
};
1 change: 1 addition & 0 deletions packages/test-utils/src/testcontainers/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as testContainers } from './testContainersTD';
export * from './globalTestContainersTD';
export * from './types';

0 comments on commit 2acb148

Please sign in to comment.