@centreon/e2e-config 1.0.0 → 26.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2
+ /* eslint-disable import/extensions */
3
+ /* eslint-disable import/no-unresolved */
4
+
5
+ import { execSync } from 'child_process';
6
+
7
+ import { defineConfig } from 'cypress';
8
+ import installLogsPrinter from 'cypress-terminal-report/src/installLogsPrinter';
9
+ import { config as configDotenv } from 'dotenv';
10
+
11
+ import esbuildPreprocessor from './esbuild-preprocessor';
12
+ import plugins from './plugins';
13
+ import tasks from './tasks';
14
+
15
+ interface ConfigurationOptions {
16
+ cypressFolder?: string;
17
+ env?: Record<string, unknown>;
18
+ envFile?: string;
19
+ isDevelopment?: boolean;
20
+ specPattern: string;
21
+ }
22
+
23
+ export default ({
24
+ specPattern,
25
+ cypressFolder,
26
+ isDevelopment,
27
+ env,
28
+ envFile
29
+ }: ConfigurationOptions): Cypress.ConfigOptions => {
30
+ if (envFile) {
31
+ configDotenv({ path: envFile });
32
+ }
33
+
34
+ const resultsFolder = `${cypressFolder || '.'}/results`;
35
+
36
+ const webImageVersion = execSync('git rev-parse --abbrev-ref HEAD')
37
+ .toString('utf8')
38
+ .replace(/[\n\r\s]+$/, '');
39
+
40
+ return defineConfig({
41
+ chromeWebSecurity: false,
42
+ defaultCommandTimeout: 20000,
43
+ downloadsFolder: `${resultsFolder}/downloads`,
44
+ e2e: {
45
+ excludeSpecPattern: ['*.js', '*.ts', '*.md'],
46
+ fixturesFolder: 'fixtures',
47
+ reporter: require.resolve('cypress-multi-reporters'),
48
+ reporterOptions: {
49
+ configFile: `${__dirname}/reporter-config.js`
50
+ },
51
+ setupNodeEvents: async (cypressOn, config) => {
52
+ const on = require('cypress-on-fix')(cypressOn)
53
+ installLogsPrinter(on, {
54
+ commandTrimLength: 5000,
55
+ defaultTrimLength: 5000,
56
+ });
57
+ on("task", {
58
+ logVersion(message) {
59
+ console.log(`[LOG]: ${message}`);
60
+ return null;
61
+ },
62
+ });
63
+ await esbuildPreprocessor(on, config);
64
+ tasks(on);
65
+
66
+ return plugins(on, config);
67
+ },
68
+ specPattern,
69
+ supportFile: 'support/e2e.{js,jsx,ts,tsx}',
70
+ testIsolation: true,
71
+ },
72
+ env: {
73
+ ...env,
74
+ DATABASE_IMAGE: 'bitnamilegacy/mariadb:11.8',
75
+ OPENID_IMAGE_VERSION: process.env.MAJOR || '24.04',
76
+ SAML_IMAGE_VERSION: process.env.MAJOR || '24.04',
77
+ STABILITY: 'unstable',
78
+ TARGET_STABILITY: 'unstable',
79
+ WEB_IMAGE_OS: 'alma9',
80
+ WEB_IMAGE_VERSION: webImageVersion
81
+ },
82
+ execTimeout: 60000,
83
+ requestTimeout: 20000,
84
+ retries: {
85
+ openMode: 0,
86
+ runMode: process.env.CI ? 2 : 0
87
+ },
88
+ screenshotsFolder: `${resultsFolder}/screenshots`,
89
+ // Ensure previous run assets are removed to avoid accumulation
90
+ trashAssetsBeforeRuns: true,
91
+ video: true,
92
+ // Keep files small in CI, but fast locally
93
+ videoCompression: process.env.CI ? 32 : 0,
94
+ videosFolder: `${resultsFolder}/videos`,
95
+ viewportHeight: 1080,
96
+ viewportWidth: 1920
97
+ });
98
+ };
@@ -0,0 +1,26 @@
1
+ import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';
2
+ import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill';
3
+ import { addCucumberPreprocessorPlugin } from '@badeball/cypress-cucumber-preprocessor';
4
+ import createBundler from '@bahmutov/cypress-esbuild-preprocessor';
5
+ import createEsbuildPlugin from '@badeball/cypress-cucumber-preprocessor/esbuild';
6
+
7
+ export default async (
8
+ on: Cypress.PluginEvents,
9
+ config: Cypress.PluginConfigOptions
10
+ ): Promise<void> => {
11
+ await addCucumberPreprocessorPlugin(on, config);
12
+
13
+ on(
14
+ 'file:preprocessor',
15
+ createBundler({
16
+ plugins: [
17
+ createEsbuildPlugin(config),
18
+ NodeModulesPolyfillPlugin(),
19
+ NodeGlobalsPolyfillPlugin({
20
+ buffer: true,
21
+ process: true
22
+ })
23
+ ]
24
+ })
25
+ );
26
+ };
@@ -0,0 +1,64 @@
1
+ /* eslint-disable default-param-last */
2
+ /* eslint-disable global-require */
3
+ /* eslint-disable @typescript-eslint/no-var-requires */
4
+ /* eslint-disable no-param-reassign */
5
+
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+
9
+ export default (
10
+ on: Cypress.PluginEvents,
11
+ config: Cypress.PluginConfigOptions
12
+ ): Cypress.PluginConfigOptions => {
13
+ on('before:browser:launch', (browser, launchOptions) => {
14
+ const width = 1920;
15
+ const height = 1080;
16
+
17
+ if (browser.family === 'chromium' && browser.name !== 'electron') {
18
+ if (browser.isHeadless) {
19
+ launchOptions.args.push('--headless=new');
20
+ }
21
+
22
+ // flags description : https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md
23
+ launchOptions.args.push('--disable-gpu');
24
+ launchOptions.args.push('--auto-open-devtools-for-tabs');
25
+ launchOptions.args.push('--disable-extensions');
26
+ launchOptions.args.push('--hide-scrollbars');
27
+ launchOptions.args.push('--mute-audio');
28
+
29
+ // force screen to be non-retina and just use our given resolution
30
+ launchOptions.args.push('--force-device-scale-factor=1');
31
+
32
+ launchOptions.args.push(`--window-size=${width},${height}`);
33
+ }
34
+
35
+ return launchOptions;
36
+ });
37
+
38
+ on('after:run', (results) => {
39
+ const testRetries: { [key: string]: Number } = {};
40
+ if ('runs' in results) {
41
+ results.runs.forEach((run) => {
42
+ run.tests.forEach((test) => {
43
+ console.log(test)
44
+ if (test.attempts && test.attempts.length > 1 && test.state === 'passed') {
45
+ const testTitle = test.title.join(' > '); // Convert the array to a string
46
+ testRetries[testTitle] = test.attempts.length - 1;
47
+ }
48
+ });
49
+ });
50
+ }
51
+
52
+ // Save the testRetries object in the results directory of the consuming
53
+ // e2e project, wherever this package is installed.
54
+ const resultsDirectory = path.join(config.projectRoot, 'results');
55
+ fs.mkdirSync(resultsDirectory, { recursive: true });
56
+
57
+ fs.writeFileSync(
58
+ path.join(resultsDirectory, 'retries.json'),
59
+ JSON.stringify(testRetries, null, 2)
60
+ );
61
+ });
62
+
63
+ return config;
64
+ };
@@ -0,0 +1,13 @@
1
+ module.exports = {
2
+ mochawesomeReporterOptions: {
3
+ consoleReporter: 'none',
4
+ html: false,
5
+ json: true,
6
+ overwrite: true,
7
+ reportDir: 'results/reports',
8
+ reportFilename: '[name]-report.json'
9
+ },
10
+ reporterEnabled: `mochawesome,${require.resolve(
11
+ '@badeball/cypress-cucumber-preprocessor/pretty-reporter'
12
+ )}`
13
+ };
@@ -0,0 +1,372 @@
1
+ /* eslint-disable no-console */
2
+ import { execSync } from 'child_process';
3
+ import { existsSync, mkdirSync } from 'fs';
4
+ import path from 'path';
5
+ import fs from "fs";
6
+
7
+ import tar from 'tar-fs';
8
+ import {
9
+ DockerComposeEnvironment,
10
+ GenericContainer,
11
+ StartedDockerComposeEnvironment,
12
+ StartedTestContainer,
13
+ Wait,
14
+ getContainerRuntimeClient
15
+ } from 'testcontainers';
16
+ import { createConnection } from 'mysql2/promise';
17
+
18
+ interface Containers {
19
+ [key: string]: StartedTestContainer;
20
+ }
21
+
22
+ class NotFoundContainerError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = 'NotFoundContainerError';
26
+ }
27
+ }
28
+
29
+ export default (on: Cypress.PluginEvents): void => {
30
+ let dockerEnvironment: StartedDockerComposeEnvironment | null = null;
31
+ const containers: Containers = {};
32
+
33
+ const getContainer = (containerName): StartedTestContainer => {
34
+ let container;
35
+
36
+ if (dockerEnvironment !== null) {
37
+ container = dockerEnvironment.getContainer(`${containerName}-1`);
38
+ } else if (containers[containerName]) {
39
+ container = containers[containerName];
40
+ } else {
41
+ throw new NotFoundContainerError(`Cannot get container ${containerName}`);
42
+ }
43
+
44
+ return container;
45
+ };
46
+
47
+ interface PortBinding {
48
+ destination: number;
49
+ source: number;
50
+ }
51
+
52
+ interface StartContainerProps {
53
+ command?: string;
54
+ image: string;
55
+ name: string;
56
+ portBindings: Array<PortBinding>;
57
+ }
58
+
59
+ interface StopContainerProps {
60
+ name: string;
61
+ }
62
+
63
+ on("task", {
64
+ copyFromContainer: async ({ destination, serviceName, source }) => {
65
+ try {
66
+ const container = getContainer(serviceName);
67
+
68
+ await container
69
+ .copyArchiveFromContainer(source)
70
+ .then((archiveStream) => {
71
+ return new Promise<void>((resolve) => {
72
+ const dest = tar.extract(destination);
73
+ archiveStream.pipe(dest);
74
+ dest.on("finish", resolve);
75
+ });
76
+ });
77
+ } catch (error) {
78
+ if (error instanceof NotFoundContainerError) {
79
+ console.log(`Cannot get ${source} from container ${serviceName} because it doesn't exist.`);
80
+ } else {
81
+ console.error(error);
82
+ }
83
+ }
84
+
85
+ return null;
86
+ },
87
+ copyToContainer: async ({ destination, serviceName, source, type }) => {
88
+ const container = getContainer(serviceName);
89
+
90
+ if (type === "directory") {
91
+ await container.copyDirectoriesToContainer([
92
+ {
93
+ source,
94
+ target: destination,
95
+ },
96
+ ]);
97
+ } else if (type === "file") {
98
+ await container.copyFilesToContainer([
99
+ {
100
+ source,
101
+ target: destination,
102
+ },
103
+ ]);
104
+ }
105
+
106
+ return null;
107
+ },
108
+ createDirectory: async (directoryPath: string) => {
109
+ if (!existsSync(directoryPath)) {
110
+ mkdirSync(directoryPath, { recursive: true });
111
+ }
112
+
113
+ return null;
114
+ },
115
+ execInContainer: async ({ command, name }) => {
116
+ const { exitCode, output } = await getContainer(name).exec([
117
+ "bash",
118
+ "-c",
119
+ `${command}${command.match(/[\n\r]/) ? "" : " 2>&1"}`,
120
+ ]);
121
+
122
+ return { exitCode, output };
123
+ },
124
+ getContainerId: (containerName: string) =>
125
+ getContainer(containerName).getId(),
126
+ getContainerIpAddress: (containerName: string) => {
127
+ const container = getContainer(containerName);
128
+
129
+ const networkNames = container.getNetworkNames();
130
+
131
+ return container.getIpAddress(networkNames[0]);
132
+ },
133
+ getContainersLogs: async () => {
134
+ try {
135
+ const { dockerode } = (await getContainerRuntimeClient()).container;
136
+ const loggedContainers = await dockerode.listContainers();
137
+
138
+ return loggedContainers.reduce((acc, container) => {
139
+ const containerName = container.Names[0].replace("/", "");
140
+ acc[containerName] = execSync(`docker logs -t ${container.Id}`, {
141
+ stdio: "pipe",
142
+ }).toString("utf8");
143
+
144
+ return acc;
145
+ }, {});
146
+ } catch (error) {
147
+ console.warn("Cannot get containers logs");
148
+ console.warn(error);
149
+
150
+ return null;
151
+ }
152
+ },
153
+ getContainerMappedPort: async ({ containerName, containerPort }) => {
154
+ const container = getContainer(containerName);
155
+
156
+ return container.getMappedPort(containerPort);
157
+ },
158
+ requestOnDatabase: async ({ database, query, params }) => {
159
+ let container: StartedTestContainer | null = null;
160
+
161
+ if (dockerEnvironment !== null) {
162
+ container = dockerEnvironment.getContainer("db-1");
163
+ } else {
164
+ container = getContainer("web");
165
+ }
166
+
167
+ const client = await createConnection({
168
+ database,
169
+ host: container.getHost(),
170
+ password: "centreon",
171
+ port: container.getMappedPort(3306),
172
+ user: "centreon",
173
+ });
174
+
175
+ try {
176
+ const [rows, fields] = params
177
+ ? await client.execute(query, params)
178
+ : await client.query(query);
179
+
180
+ return [rows, fields];
181
+ } finally {
182
+ await client.end();
183
+ }
184
+ },
185
+ startContainer: async ({
186
+ command,
187
+ image,
188
+ name,
189
+ portBindings = [],
190
+ }: StartContainerProps) => {
191
+ let container = await new GenericContainer(image).withName(name);
192
+
193
+ portBindings.forEach(({ source, destination }) => {
194
+ container = container.withExposedPorts({
195
+ container: source,
196
+ host: destination,
197
+ });
198
+ });
199
+
200
+ if (command) {
201
+ container
202
+ .withCommand(["bash", "-c", command])
203
+ .withWaitStrategy(Wait.forSuccessfulCommand("ls"));
204
+ }
205
+
206
+ containers[name] = await container.start();
207
+
208
+ return container;
209
+ },
210
+ startContainers: async ({
211
+ composeFile,
212
+ databaseImage,
213
+ dbConfiguration,
214
+ dbStorage,
215
+ openidImage,
216
+ profiles,
217
+ samlImage,
218
+ webImage,
219
+ }) => {
220
+ try {
221
+ const composeFileDir = path.dirname(composeFile);
222
+ const composeFileName = path.basename(composeFile);
223
+
224
+ const environment: Record<string, string> = {
225
+ MYSQL_IMAGE: databaseImage,
226
+ OPENID_IMAGE: openidImage,
227
+ SAML_IMAGE: samlImage,
228
+ WEB_IMAGE: webImage,
229
+ };
230
+ if (dbConfiguration) {
231
+ environment.MYSQL_DB_CONFIGURATION = dbConfiguration;
232
+ }
233
+ if (dbStorage) {
234
+ environment.MYSQL_DB_STORAGE = dbStorage;
235
+ }
236
+
237
+ dockerEnvironment = await new DockerComposeEnvironment(
238
+ composeFileDir,
239
+ composeFileName,
240
+ )
241
+ .withEnvironment(environment)
242
+ .withProfiles(...profiles)
243
+ .withStartupTimeout(900_000) // 15 minutes
244
+ .withWaitStrategy(
245
+ "web-1",
246
+ Wait.forAll([
247
+ Wait.forHealthCheck(),
248
+ Wait.forLogMessage("Centreon is ready"),
249
+ ]),
250
+ )
251
+ .up();
252
+
253
+ return null;
254
+ } catch (error) {
255
+ console.error(error);
256
+
257
+ // Best-effort teardown: keep the original startup error if cleanup fails.
258
+ try {
259
+ await dockerEnvironment?.down();
260
+ } catch (teardownError) {
261
+ console.error(teardownError);
262
+ } finally {
263
+ dockerEnvironment = null;
264
+ }
265
+
266
+ throw error;
267
+ }
268
+ },
269
+ stopContainer: async ({ name }: StopContainerProps) => {
270
+ if (containers[name]) {
271
+ const container = containers[name];
272
+
273
+ await container.stop();
274
+
275
+ delete containers[name];
276
+ }
277
+
278
+ return null;
279
+ },
280
+ stopContainers: async () => {
281
+ if (dockerEnvironment !== null) {
282
+ await dockerEnvironment.down({ timeout: 0 });
283
+
284
+ dockerEnvironment = null;
285
+ }
286
+
287
+ return null;
288
+ },
289
+ waitOn: async (url: string) => {
290
+ execSync(`npx wait-on ${url}`);
291
+
292
+ return null;
293
+ },
294
+ listFilesInDirectory: async ( directoryPath ) => {
295
+ return new Promise((resolve, reject) => {
296
+ fs.readdir(directoryPath, (err, files) => {
297
+ if (err) {
298
+ reject(err);
299
+ } else {
300
+ resolve(files);
301
+ }
302
+ });
303
+ });
304
+ },
305
+ fileExists: async ( filePath ) => {
306
+ return fs.existsSync(filePath);
307
+ },
308
+ getExportedFile({ downloadsFolder }: { downloadsFolder: string }): string {
309
+ const files = fs
310
+ .readdirSync(downloadsFolder)
311
+ .filter((name) => name.startsWith("ResourceStatusExport_all") && name.endsWith(".csv"))
312
+ .map((name) => ({
313
+ name,
314
+ time: fs.statSync(path.join(downloadsFolder, name)).mtime.getTime()
315
+ }))
316
+ .sort((a, b) => b.time - a.time);
317
+
318
+ if (files.length === 0) {
319
+ throw new Error("No exported file found");
320
+ }
321
+
322
+ return path.join(downloadsFolder, files[0].name);
323
+ },
324
+ readCsvFile({ filePath }: { filePath: string }): Promise<string> {
325
+ const projectRoot = path.resolve(process.cwd());
326
+ const resolvedPath = path.resolve(filePath);
327
+ if (resolvedPath !== projectRoot && !resolvedPath.startsWith(projectRoot + path.sep)) {
328
+ return Promise.reject(new Error("Path is outside of the project directory"));
329
+ }
330
+
331
+ return new Promise((resolve, reject) => {
332
+ fs.readFile(resolvedPath, "utf8", (err, data) => {
333
+ if (err) return reject(err);
334
+ resolve(data);
335
+ });
336
+ });
337
+ },
338
+ clearDownloadsFolder({ downloadsFolder }: { downloadsFolder: string }): null {
339
+ const projectRoot = path.resolve(process.cwd());
340
+ const resolvedFolder = path.resolve(downloadsFolder);
341
+ if (resolvedFolder !== projectRoot && !resolvedFolder.startsWith(projectRoot + path.sep)) {
342
+ throw new Error("Path is outside of the project directory");
343
+ }
344
+
345
+ if (!fs.existsSync(resolvedFolder)) {
346
+ return null;
347
+ }
348
+
349
+ const files = fs.readdirSync(resolvedFolder);
350
+ for (const file of files) {
351
+ const filePath = path.join(resolvedFolder, file);
352
+ if (!filePath.startsWith(resolvedFolder + path.sep)) {
353
+ continue;
354
+ }
355
+ fs.unlinkSync(filePath);
356
+ }
357
+
358
+ return null;
359
+ },
360
+ isDownloadComplete({ downloadsFolder }: { downloadsFolder: string }): boolean {
361
+ if (!fs.existsSync(downloadsFolder)) return false;
362
+
363
+ const files = fs
364
+ .readdirSync(downloadsFolder)
365
+ .filter(
366
+ (name) => !name.endsWith(".crdownload") && !name.endsWith(".tmp")
367
+ );
368
+
369
+ return files.length > 0;
370
+ },
371
+ });
372
+ };
package/package.json CHANGED
@@ -1,20 +1,42 @@
1
1
  {
2
- "name": "@centreon/e2e-config",
3
- "description": "Centreon shared end-to-end tests configuration",
4
- "version": "1.0.0",
5
- "repository": {
6
- "type": "git",
7
- "url": "git+https://github.com/centreon/centreon.git",
8
- "directory": "centreon/packages/e2e-config"
9
- },
10
- "keywords": [
11
- "centreon",
12
- "e2e"
13
- ],
14
- "author": "centreon@centreon.com",
15
- "license": "MIT",
16
- "bugs": {
17
- "url": "https://github.com/centreon/centreon/issues"
18
- },
19
- "homepage": "https://github.com/centreon/centreon#readme"
2
+ "name": "@centreon/e2e-config",
3
+ "description": "Centreon shared Cypress e2e configuration, commands and tasks (QA-owned)",
4
+ "version": "26.10.1",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/centreon/centreon.git",
8
+ "directory": "centreon/tests/e2e-config"
9
+ },
10
+ "keywords": [
11
+ "centreon",
12
+ "cypress",
13
+ "e2e"
14
+ ],
15
+ "author": "centreon@centreon.com",
16
+ "license": "MIT",
17
+ "bugs": {
18
+ "url": "https://github.com/centreon/centreon/issues"
19
+ },
20
+ "homepage": "https://github.com/centreon/centreon#readme",
21
+ "files": [
22
+ "cypress/e2e"
23
+ ],
24
+ "dependencies": {
25
+ "@badeball/cypress-cucumber-preprocessor": "23.2.1",
26
+ "@bahmutov/cypress-esbuild-preprocessor": "2.2.7",
27
+ "@esbuild-plugins/node-globals-polyfill": "0.2.3",
28
+ "@esbuild-plugins/node-modules-polyfill": "0.2.2",
29
+ "@types/cypress-cucumber-preprocessor": "4.0.5",
30
+ "cypress": "15.5.0",
31
+ "cypress-multi-reporters": "2.0.5",
32
+ "cypress-on-fix": "1.1.0",
33
+ "cypress-terminal-report": "7.3.3",
34
+ "cypress-wait-until": "3.0.2",
35
+ "dotenv": "16.6.1",
36
+ "esbuild": "0.21.5",
37
+ "mochawesome": "7.1.4",
38
+ "mysql2": "3.22.0",
39
+ "tar-fs": "3.1.1",
40
+ "testcontainers": "10.28.0"
41
+ }
20
42
  }