Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x | import { createHash } from 'node:crypto';
import { type Server as CoreHttpServer } from 'node:http';
import path from 'node:path';
import { createIntl } from '@formatjs/intl';
import { createMock, type DeepMocked } from '@golevelup/ts-jest';
import { Logger, ValidationPipe, type INestApplication, type ModuleMetadata } from '@nestjs/common';
import { CommandBus, EventBus } from '@nestjs/cqrs';
import { type NestExpressApplication } from '@nestjs/platform-express';
import { Test } from '@nestjs/testing';
import { TypeOrmModule, type TypeOrmModuleOptions } from '@nestjs/typeorm';
import axios from 'axios';
import { useContainer as classValidatorUseContainer } from 'class-validator';
import { filter, last } from 'lodash-es';
import { globalConfiguration } from '@amalia/core/models';
import { assert } from '@amalia/ext/typescript';
import { IntlModule, IntlService } from '@amalia/kernel/intl/module';
import { LanguagesEnum } from '@amalia/kernel/intl/types';
import {
QueueService,
type MessageTasks,
type QueueMessageAttributes,
type QueueMessageContent,
} from '@amalia/kernel/queue/core';
import { type AuditMessage } from '@amalia/tenants/monitoring/audit/types';
import { CloudStorageCountService, CloudStorageDownloadService } from '@amalia/vendors/google-cloud/cloud-storage';
import { DatabaseTestUtils } from './database.test-utils';
import { intlServiceMock, MockTestUtils } from './mock.test-utils';
const originalGet = axios.get.bind(axios);
// Can't mock the IdentityProviderService because of circular dependencies issues
jest.spyOn(axios, 'get').mockImplementation((url, ...args) => {
if (url === 'https://amalia-ci.eu.auth0.com/userinfo') {
return Promise.resolve({ data: { picture: undefined } });
}
// Let everything else pass through to the real axios
return originalGet(url, ...args);
});
type GlobalConfiguration = ReturnType<typeof globalConfiguration>;
type MethodNames<Class> = {
[K in keyof Class as Class[K] extends (...args: unknown[]) => unknown ? K : never]: Class[K];
};
export type MockProvider<TService = unknown> = { provider: TService; override: MethodNames<TService> };
const logger = new Logger('AppUtilsBase');
interface TestBedConfiguration {
modules: ModuleMetadata['imports'];
providers?: MockProvider[];
shouldLoadFixtures?: boolean;
shouldMockCommandBus?: boolean;
}
export class TestBed {
private readonly databaseSchemaName: string;
private databaseUtils: DatabaseTestUtils | undefined;
public readonly configuration: GlobalConfiguration;
/**
* This constructor is used to create a new instance of the AppUtilsBase class, which is used to bootstrap the application
*
* The database schema name is the concatenation of the nxPackageName and the fileName.
*
* @param fileName the name of the file from which tests are run (use __filename)
* @param configuration the global configuration
*/
public constructor(fileName: string, configuration?: GlobalConfiguration) {
const nxPackageName = process.env['NX_TASK_TARGET_PROJECT'] || null;
assert(typeof nxPackageName === 'string', 'Env var NX_TASK_TARGET_PROJECT is required');
assert(typeof fileName === 'string', 'fileName is required');
this.databaseSchemaName = TestBed.getDatabaseSchemaName(nxPackageName, fileName);
this.configuration = DatabaseTestUtils.rewriteSchemasInConfiguration(
this.databaseSchemaName,
configuration || globalConfiguration(),
);
}
public commandBus = createMock<CommandBus>({
register: jest.fn(),
execute: jest.fn(() => Promise.resolve()),
});
public eventBus: DeepMocked<EventBus> = createMock<EventBus>({
registerSagas: jest.fn(),
register: jest.fn(),
publish: jest.fn().mockResolvedValue(undefined),
});
private cloudStorageDownloadService = createMock<CloudStorageDownloadService>({
streamFile: jest.fn().mockResolvedValue(null),
});
private cloudStorageCountService = createMock<CloudStorageCountService>({
countBucketFiles: jest.fn().mockResolvedValue(null),
});
private queueService: DeepMocked<QueueService> = createMock<QueueService>({
async sendToQueue(attributes: QueueMessageAttributes<MessageTasks>, message: QueueMessageContent): Promise<void> {
logger.log('Message published');
MockTestUtils.publishMessageMock?.(attributes, message);
// eslint-disable-next-line unicorn/no-useless-promise-resolve-reject
return Promise.resolve();
},
});
public async bootstrap(testBedConfigurationRaw: TestBedConfiguration): Promise<INestApplication<CoreHttpServer>> {
const testBedConfiguration: TestBedConfiguration = {
...testBedConfigurationRaw,
shouldMockCommandBus: testBedConfigurationRaw.shouldMockCommandBus ?? true,
providers: testBedConfigurationRaw.providers ?? [],
shouldLoadFixtures: testBedConfigurationRaw.shouldLoadFixtures ?? true,
};
await DatabaseTestUtils.prepareSchemas(this.databaseSchemaName, this.configuration);
const testingModule = Test.createTestingModule({
imports: [
TypeOrmModule.forRoot({
...this.configuration.database.defaultConnection,
synchronize: true,
} as TypeOrmModuleOptions),
TypeOrmModule.forRoot({
...this.configuration.database.dataConnection,
synchronize: true,
} as TypeOrmModuleOptions),
IntlModule.forRoot({
locales: {
[LanguagesEnum.de]: createIntl({ locale: 'de', defaultLocale: 'en', messages: {} }),
[LanguagesEnum.en]: createIntl({ locale: 'en', defaultLocale: 'en', messages: {} }),
[LanguagesEnum.es]: createIntl({ locale: 'es', defaultLocale: 'en', messages: {} }),
[LanguagesEnum.fr]: createIntl({ locale: 'fr', defaultLocale: 'en', messages: {} }),
[LanguagesEnum.it]: createIntl({ locale: 'it', defaultLocale: 'en', messages: {} }),
[LanguagesEnum.pt]: createIntl({ locale: 'pt', defaultLocale: 'en', messages: {} }),
},
}),
...testBedConfigurationRaw.modules!,
].filter(Boolean),
providers: [DatabaseTestUtils],
});
testingModule
.overrideProvider(EventBus)
.useValue(this.eventBus)
.overrideProvider(QueueService)
.useValue(this.queueService)
.overrideProvider(CloudStorageDownloadService)
.useValue(this.cloudStorageDownloadService)
.overrideProvider(CloudStorageCountService)
.useValue(this.cloudStorageCountService)
.overrideProvider(IntlService)
.useValue(intlServiceMock);
if (testBedConfiguration.shouldMockCommandBus) {
testingModule.overrideProvider(CommandBus).useValue(this.commandBus);
}
testBedConfiguration.providers!.forEach(({ provider, override }) => {
testingModule.overrideProvider(provider).useValue(override);
});
const module = await testingModule.compile();
const app = module.createNestApplication<NestExpressApplication>({
rawBody: true,
});
// this one was tough => https://github.com/nestjs/nest/issues/528
// used with validator in calculations
classValidatorUseContainer(app, { fallbackOnErrors: true });
app.useGlobalPipes(new ValidationPipe({ transform: true }));
app.useBodyParser('json', { limit: '10mb' });
await app.init();
this.databaseUtils = module.get<DatabaseTestUtils>(DatabaseTestUtils);
if (testBedConfiguration.shouldLoadFixtures) {
await this.databaseUtils.reloadFixtures();
}
return app;
}
public async shutdown(app?: INestApplication) {
if (!this.databaseUtils) {
// eslint-disable-next-line no-console
console.error('Cannot clean the database since it was not properly setup.');
}
await app?.close();
this.eventBus = null;
this.commandBus = null;
this.cloudStorageDownloadService = null;
this.cloudStorageCountService = null;
this.queueService = null;
}
public expectEventPublished(eventName: string, additionalCheck?: (expectedEvent: AuditMessage) => void) {
const expectedEvent = last(
filter(this.eventBus.publish.mock.calls, (call) => call[0].constructor.name === eventName),
);
expect(expectedEvent).toBeDefined();
expect(expectedEvent![0].constructor.name).toEqual(eventName);
additionalCheck?.(expectedEvent![0]);
}
public resetPublishMock() {
this.eventBus.publish.mockReset();
}
public static getDatabaseSchemaName(packageName: string, fileName: string): string {
const AMALIA_DATA_SUFFIX_LENGTH = 'amalia-data'.length;
const SHA_LENGTH = 5;
// Force schema name to be less than 64 characters including the suffix (amalia-data), as it's the maximum length for a schema name for Postgres.
const availableLength = 64 - '--'.length - AMALIA_DATA_SUFFIX_LENGTH - SHA_LENGTH;
const fileNameSha1 = createHash('sha1')
.update(fileName, 'utf8')
.digest('base64')
// Remove non word characters from the SHA1.
.replaceAll(/\W/giu, '')
// Take only the first 5, that should be unique enough.
.slice(0, SHA_LENGTH);
// Take file name.
const fileNameBase = path.basename(fileName).split('.')[0];
// Build the "ideal" name, remove all vowels to earn some space.
const name = `${packageName}--${fileNameBase}`.replaceAll(/[aeiouy]/giu, '');
// And truncate it to the max size possible. Add the sha1 to avoid conflicts.
return name.slice(0, availableLength).concat('-').concat(fileNameSha1);
}
public getDatabaseSchemaName() {
return this.databaseSchemaName;
}
}
|