@centreon/js-config 24.4.1-MON-23368-containers.127 → 24.4.1-MON-34691-improve-code-coverage.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.
@@ -31,6 +31,7 @@ module.exports = ({
31
31
  on('before:browser:launch', (browser, launchOptions) => {
32
32
  if (browser.name === 'chrome' && browser.isHeadless) {
33
33
  launchOptions.args.push('--headless=new');
34
+ launchOptions.args.push('--force-color-profile=srgb');
34
35
  }
35
36
 
36
37
  return launchOptions;
@@ -1,6 +1,4 @@
1
1
  /* eslint-disable @typescript-eslint/no-namespace */
2
- import path from 'path';
3
- import 'cypress-wait-until';
4
2
 
5
3
  import './commands/configuration';
6
4
  import './commands/monitoring';
@@ -9,53 +7,10 @@ import installLogsCollector from 'cypress-terminal-report/src/installLogsCollect
9
7
 
10
8
  installLogsCollector({ enableExtendedCollector: true });
11
9
 
12
- const apiBase = '/centreon/api';
13
- const apiActionV1 = `${apiBase}/index.php`;
14
10
  const apiLoginV2 = '/centreon/authentication/providers/configurations/local';
15
11
 
16
12
  const artifactIllegalCharactersMatcher = /[,\s/|<>*?:"]/g;
17
13
 
18
- export enum PatternType {
19
- contains = '*',
20
- endsWith = '$',
21
- equals = '',
22
- startsWith = '^'
23
- }
24
-
25
- interface GetByLabelProps {
26
- label: string;
27
- patternType?: PatternType;
28
- tag?: string;
29
- }
30
-
31
- Cypress.Commands.add(
32
- 'getByLabel',
33
- ({
34
- tag = '',
35
- patternType = PatternType.equals,
36
- label
37
- }: GetByLabelProps): Cypress.Chainable => {
38
- return cy.get(`${tag}[aria-label${patternType}="${label}"]`);
39
- }
40
- );
41
-
42
- interface GetByTestIdProps {
43
- patternType?: PatternType;
44
- tag?: string;
45
- testId: string;
46
- }
47
-
48
- Cypress.Commands.add(
49
- 'getByTestId',
50
- ({
51
- tag = '',
52
- patternType = PatternType.equals,
53
- testId
54
- }: GetByTestIdProps): Cypress.Chainable => {
55
- return cy.get(`${tag}[data-testid${patternType}="${testId}"]`);
56
- }
57
- );
58
-
59
14
  Cypress.Commands.add('getWebVersion', (): Cypress.Chainable => {
60
15
  return cy
61
16
  .exec(
@@ -104,7 +59,7 @@ interface NavigateToProps {
104
59
 
105
60
  Cypress.Commands.add(
106
61
  'navigateTo',
107
- ({ rootItemNumber, subMenu, page }: NavigateToProps): void => {
62
+ ({ rootItemNumber, subMenu, page }): void => {
108
63
  if (subMenu) {
109
64
  cy.hoverRootMenuItem(rootItemNumber)
110
65
  .contains(subMenu)
@@ -145,24 +100,6 @@ Cypress.Commands.add(
145
100
  }
146
101
  );
147
102
 
148
- Cypress.Commands.add('getContainerId', (containerName: string) => {
149
- cy.log(`Getting container id of ${containerName}`);
150
-
151
- return cy.task('getContainerId', containerName);
152
- });
153
-
154
- Cypress.Commands.add('getContainerIpAddress', (containerName: string) => {
155
- cy.log(`Getting container ip address of ${containerName}`);
156
-
157
- return cy.task('getContainerIpAddress', containerName);
158
- });
159
-
160
- Cypress.Commands.add('getContainersLogs', () => {
161
- cy.log('Getting containers logs');
162
-
163
- return cy.task('getContainersLogs');
164
- });
165
-
166
103
  interface CopyFromContainerProps {
167
104
  destination: string;
168
105
  name?: string;
@@ -171,54 +108,38 @@ interface CopyFromContainerProps {
171
108
 
172
109
  Cypress.Commands.add(
173
110
  'copyFromContainer',
174
- ({ name = 'web', source, destination }: CopyFromContainerProps) => {
175
- cy.log(`Copy content from ${name}:${source} to ${destination}`);
176
-
177
- return cy.task('copyFromContainer', {
178
- destination,
179
- serviceName: name,
180
- source
181
- });
111
+ (
112
+ {
113
+ name = Cypress.env('dockerName'),
114
+ source,
115
+ destination
116
+ }: CopyFromContainerProps,
117
+ options?: Partial<Cypress.ExecOptions>
118
+ ) => {
119
+ return cy.exec(`docker cp ${name}:${source} "${destination}"`, options);
182
120
  }
183
121
  );
184
122
 
185
- export enum CopyToContainerContentType {
186
- Directory = 'directory',
187
- File = 'file'
188
- }
189
-
190
123
  interface CopyToContainerProps {
191
124
  destination: string;
192
125
  name?: string;
193
126
  source: string;
194
- type: CopyToContainerContentType;
195
127
  }
196
128
 
197
129
  Cypress.Commands.add(
198
130
  'copyToContainer',
199
- ({ name = 'web', source, destination, type }: CopyToContainerProps) => {
200
- cy.log(`Copy content from ${source} to ${name}:${destination}`);
201
-
202
- return cy.task('copyToContainer', {
203
- destination,
204
- serviceName: name,
131
+ (
132
+ {
133
+ name = Cypress.env('dockerName'),
205
134
  source,
206
- type
207
- });
135
+ destination
136
+ }: CopyToContainerProps,
137
+ options?: Partial<Cypress.ExecOptions>
138
+ ) => {
139
+ return cy.exec(`docker cp ${source} ${name}:${destination}`, options);
208
140
  }
209
141
  );
210
142
 
211
- Cypress.Commands.add('loginAsAdminViaApiV2', (): Cypress.Chainable => {
212
- return cy.request({
213
- body: {
214
- login: 'admin',
215
- password: 'Centreon!2021'
216
- },
217
- method: 'POST',
218
- url: apiLoginV2
219
- });
220
- });
221
-
222
143
  interface LoginByTypeOfUserProps {
223
144
  jsonName?: string;
224
145
  loginViaApi?: boolean;
@@ -265,33 +186,6 @@ Cypress.Commands.add(
265
186
  }
266
187
  );
267
188
 
268
- Cypress.Commands.add('logout', (): void => {
269
- cy.getByLabel({ label: 'Profile' }).should('exist').click();
270
-
271
- cy.intercept({
272
- method: 'GET',
273
- times: 1,
274
- url: '/centreon/api/latest/authentication/logout'
275
- }).as('logout');
276
-
277
- cy.contains(/^Logout$/).click();
278
-
279
- cy.wait('@logout').its('response.statusCode').should('eq', 302);
280
-
281
- // https://github.com/cypress-io/cypress/issues/25841
282
- cy.clearAllCookies();
283
- });
284
-
285
- Cypress.Commands.add('logoutViaAPI', (): Cypress.Chainable => {
286
- return cy
287
- .request({
288
- method: 'GET',
289
- url: '/centreon/authentication/logout'
290
- })
291
- .visit('/')
292
- .getByLabel({ label: 'Alias', tag: 'input' });
293
- });
294
-
295
189
  Cypress.Commands.add(
296
190
  'visitEmptyPage',
297
191
  (): Cypress.Chainable =>
@@ -303,91 +197,32 @@ Cypress.Commands.add(
303
197
  .visit('/waiting-page')
304
198
  );
305
199
 
200
+ Cypress.Commands.add('waitForContainerAndSetToken', (): Cypress.Chainable => {
201
+ return cy.setUserTokenApiV1();
202
+ });
203
+
306
204
  interface ExecInContainerProps {
307
- command: string | Array<string>;
205
+ command: string;
308
206
  name: string;
309
207
  }
310
208
 
311
- interface ExecInContainerResult {
312
- exitCode: number;
313
- output: string;
314
- }
315
-
316
209
  Cypress.Commands.add(
317
210
  'execInContainer',
318
211
  ({ command, name }: ExecInContainerProps): Cypress.Chainable => {
319
- const commands =
320
- typeof command === 'string' || command instanceof String
321
- ? [command]
322
- : command;
323
-
324
- const results = commands.reduce(
325
- (acc, runCommand) => {
326
- cy.task<ExecInContainerResult>(
327
- 'execInContainer',
328
- { command: runCommand, name },
329
- { timeout: 600000 }
330
- ).then((result) => {
331
- if (result.exitCode) {
332
- cy.log(result.output);
333
-
334
- // output will not be truncated
335
- throw new Error(`
336
- Execution of "${runCommand}" failed
337
- Exit code: ${result.exitCode}
338
- Output:\n${result.output}`);
339
- }
340
-
341
- acc.output = `${acc.output}${result.output}`;
342
- });
343
-
344
- return acc;
345
- },
346
- { exitCode: 0, output: '' }
347
- );
348
-
349
- return cy.wrap(results);
350
- }
351
- );
352
-
353
- interface RequestOnDatabaseProps {
354
- database: string;
355
- query: string;
356
- }
357
-
358
- Cypress.Commands.add(
359
- 'requestOnDatabase',
360
- ({ database, query }: RequestOnDatabaseProps): Cypress.Chainable => {
361
- return cy.task('requestOnDatabase', { database, query });
362
- }
363
- );
364
-
365
- interface SetUserTokenApiV1Props {
366
- login?: string;
367
- password?: string;
368
- }
369
-
370
- Cypress.Commands.add(
371
- 'setUserTokenApiV1',
372
- ({
373
- login = 'admin',
374
- password = 'Centreon!2021'
375
- }: SetUserTokenApiV1Props = {}): Cypress.Chainable => {
376
212
  return cy
377
- .request({
378
- body: {
379
- password,
380
- username: login
381
- },
382
- headers: {
383
- 'Content-Type': 'application/x-www-form-urlencoded'
384
- },
385
- method: 'POST',
386
- url: `${apiActionV1}?action=authenticate`
387
- })
388
- .then(({ body }) =>
389
- window.localStorage.setItem('userTokenApiV1', body.authToken)
390
- );
213
+ .exec(`docker exec -i ${name} ${command}`, { failOnNonZeroExit: false })
214
+ .then((result) => {
215
+ if (result.code) {
216
+ // output will not be truncated
217
+ throw new Error(`
218
+ Execution of "${command}" failed
219
+ Exit code: ${result.code}
220
+ Stdout:\n${result.stdout}
221
+ Stderr:\n${result.stderr}`);
222
+ }
223
+
224
+ return cy.wrap(result);
225
+ });
391
226
  }
392
227
  );
393
228
 
@@ -397,7 +232,6 @@ interface PortBinding {
397
232
  }
398
233
 
399
234
  interface StartContainerProps {
400
- command?: string;
401
235
  image: string;
402
236
  name: string;
403
237
  portBindings: Array<PortBinding>;
@@ -405,200 +239,168 @@ interface StartContainerProps {
405
239
 
406
240
  Cypress.Commands.add(
407
241
  'startContainer',
408
- ({
409
- command,
410
- name,
411
- image,
412
- portBindings
413
- }: StartContainerProps): Cypress.Chainable => {
242
+ ({ name, image, portBindings }: StartContainerProps): Cypress.Chainable => {
414
243
  cy.log(`Starting container ${name} from image ${image}`);
415
244
 
416
245
  return cy.task(
417
246
  'startContainer',
418
- { command, image, name, portBindings },
247
+ { image, name, portBindings },
419
248
  { timeout: 600000 } // 10 minutes because docker pull can be very slow
420
249
  );
421
250
  }
422
251
  );
423
252
 
424
- interface StartContainersProps {
425
- composeFile?: string;
426
- databaseImage?: string;
427
- moduleName?: string;
428
- openidImage?: string;
429
- profiles?: Array<string>;
430
- samlImage?: string;
253
+ Cypress.Commands.add(
254
+ 'createDirectory',
255
+ (directoryPath: string): Cypress.Chainable => {
256
+ return cy.task('createDirectory', directoryPath);
257
+ }
258
+ );
259
+
260
+ interface StartWebContainerProps {
261
+ name?: string;
262
+ os?: string;
431
263
  useSlim?: boolean;
432
- webOs?: string;
433
- webVersion?: string;
264
+ version?: string;
434
265
  }
435
266
 
436
267
  Cypress.Commands.add(
437
- 'startContainers',
268
+ 'startWebContainer',
438
269
  ({
439
- composeFile,
440
- databaseImage = Cypress.env('DATABASE_IMAGE'),
441
- moduleName = 'centreon-web',
442
- openidImage = `docker.centreon.com/centreon/keycloak:${Cypress.env(
443
- 'OPENID_IMAGE_VERSION'
444
- )}`,
445
- profiles = [],
446
- samlImage = `docker.centreon.com/centreon/keycloak:${Cypress.env(
447
- 'SAML_IMAGE_VERSION'
448
- )}`,
270
+ name = Cypress.env('dockerName'),
271
+ os = Cypress.env('WEB_IMAGE_OS'),
449
272
  useSlim = true,
450
- webOs = Cypress.env('WEB_IMAGE_OS'),
451
- webVersion = Cypress.env('WEB_IMAGE_VERSION')
452
- }: StartContainersProps = {}): Cypress.Chainable => {
453
- cy.log('Starting containers ...');
454
-
455
- let composeFilePath = composeFile;
456
- if (!composeFile) {
457
- const cypressDir = path.dirname(Cypress.config('configFile'));
458
- composeFilePath = `${cypressDir}/../../../.github/docker/docker-compose.yml`;
459
- }
460
-
273
+ version = Cypress.env('WEB_IMAGE_VERSION')
274
+ }: StartWebContainerProps = {}): Cypress.Chainable => {
461
275
  const slimSuffix = useSlim ? '-slim' : '';
462
276
 
463
- const webImage = `docker.centreon.com/centreon/${moduleName}${slimSuffix}-${webOs}:${webVersion}`;
277
+ const image = `docker.centreon.com/centreon/centreon-web${slimSuffix}-${os}:${version}`;
464
278
 
465
279
  return cy
466
- .task(
467
- 'startContainers',
468
- {
469
- composeFile: composeFilePath,
470
- databaseImage,
471
- openidImage,
472
- profiles,
473
- samlImage,
474
- webImage
475
- },
476
- { timeout: 600000 } // 10 minutes because docker pull can be very slow
477
- )
280
+ .startContainer({
281
+ image,
282
+ name,
283
+ portBindings: [{ destination: 4000, source: 80 }]
284
+ })
478
285
  .then(() => {
479
286
  const baseUrl = 'http://127.0.0.1:4000';
480
287
 
481
288
  Cypress.config('baseUrl', baseUrl);
482
289
 
483
- return cy.wrap(null);
290
+ return cy.task(
291
+ 'waitOn',
292
+ `${baseUrl}/centreon/api/latest/platform/installation/status`
293
+ );
484
294
  })
485
295
  .visit('/') // this is necessary to refresh browser cause baseUrl has changed (flash appears in video)
486
296
  .setUserTokenApiV1();
487
297
  }
488
298
  );
489
299
 
490
- interface StopContainerProps {
491
- name: string;
300
+ interface StopWebContainerProps {
301
+ name?: string;
492
302
  }
493
303
 
494
304
  Cypress.Commands.add(
495
- 'stopContainer',
496
- ({ name }: StopContainerProps): Cypress.Chainable => {
497
- cy.log(`Stopping container ${name}`);
498
-
499
- return cy.task('stopContainer', { name });
500
- }
501
- );
502
-
503
- Cypress.Commands.add('stopContainers', (): Cypress.Chainable => {
504
- cy.log('Stopping containers ...');
305
+ 'stopWebContainer',
306
+ ({
307
+ name = Cypress.env('dockerName')
308
+ }: StopWebContainerProps = {}): Cypress.Chainable => {
309
+ const logDirectory = `results/logs/${Cypress.spec.name.replace(
310
+ artifactIllegalCharactersMatcher,
311
+ '_'
312
+ )}/${Cypress.currentTest.title.replace(
313
+ artifactIllegalCharactersMatcher,
314
+ '_'
315
+ )}`;
505
316
 
506
- const logDirectory = `results/logs/${Cypress.spec.name.replace(
507
- artifactIllegalCharactersMatcher,
508
- '_'
509
- )}/${Cypress.currentTest.title.replace(
510
- artifactIllegalCharactersMatcher,
511
- '_'
512
- )}`;
317
+ return cy
318
+ .visitEmptyPage()
319
+ .createDirectory(logDirectory)
320
+ .copyFromContainer({
321
+ destination: `${logDirectory}/broker`,
322
+ name,
323
+ source: '/var/log/centreon-broker'
324
+ })
325
+ .copyFromContainer({
326
+ destination: `${logDirectory}/engine`,
327
+ name,
328
+ source: '/var/log/centreon-engine'
329
+ })
330
+ .copyFromContainer({
331
+ destination: `${logDirectory}/centreon`,
332
+ name,
333
+ source: '/var/log/centreon'
334
+ })
335
+ .copyFromContainer({
336
+ destination: `${logDirectory}/centreon-gorgone`,
337
+ name,
338
+ source: '/var/log/centreon-gorgone'
339
+ })
340
+ .then(() => {
341
+ if (Cypress.env('WEB_IMAGE_OS').includes('alma')) {
342
+ return cy.copyFromContainer({
343
+ destination: `${logDirectory}/php`,
344
+ name,
345
+ source: '/var/log/php-fpm'
346
+ });
347
+ }
513
348
 
514
- const name = 'web';
349
+ return cy.copyFromContainer(
350
+ {
351
+ destination: `${logDirectory}/php8.1-fpm-centreon-error.log`,
352
+ name,
353
+ source: '/var/log/php8.1-fpm-centreon-error.log'
354
+ },
355
+ { failOnNonZeroExit: false }
356
+ );
357
+ })
358
+ .then(() => {
359
+ if (Cypress.env('WEB_IMAGE_OS').includes('alma')) {
360
+ return cy.copyFromContainer({
361
+ destination: `${logDirectory}/httpd`,
362
+ name,
363
+ source: '/var/log/httpd'
364
+ });
365
+ }
515
366
 
516
- return cy
517
- .visitEmptyPage()
518
- .createDirectory(logDirectory)
519
- .getContainersLogs()
520
- .then((containersLogs: Array<Array<string>>) => {
521
- Object.entries(containersLogs).forEach(([containerName, logs]) => {
522
- cy.writeFile(
523
- `results/logs/${Cypress.spec.name.replace(
524
- artifactIllegalCharactersMatcher,
525
- '_'
526
- )}/${Cypress.currentTest.title.replace(
527
- artifactIllegalCharactersMatcher,
528
- '_'
529
- )}/container-${containerName}.log`,
530
- logs
367
+ return cy.copyFromContainer(
368
+ {
369
+ destination: `${logDirectory}/apache2`,
370
+ name,
371
+ source: '/var/log/apache2'
372
+ },
373
+ { failOnNonZeroExit: false }
531
374
  );
532
- });
533
- })
534
- .copyFromContainer({
535
- destination: `${logDirectory}/broker`,
536
- name,
537
- source: '/var/log/centreon-broker'
538
- })
539
- .copyFromContainer({
540
- destination: `${logDirectory}/engine`,
541
- name,
542
- source: '/var/log/centreon-engine'
543
- })
544
- .copyFromContainer({
545
- destination: `${logDirectory}/centreon`,
546
- name,
547
- source: '/var/log/centreon'
548
- })
549
- .copyFromContainer({
550
- destination: `${logDirectory}/centreon-gorgone`,
551
- name,
552
- source: '/var/log/centreon-gorgone'
553
- })
554
- .then(() => {
555
- if (Cypress.env('WEB_IMAGE_OS').includes('alma')) {
556
- return cy.copyFromContainer({
557
- destination: `${logDirectory}/php`,
558
- name,
559
- source: '/var/log/php-fpm'
560
- });
561
- }
375
+ })
376
+ .exec(`chmod -R 755 "${logDirectory}"`)
377
+ .stopContainer({ name });
378
+ }
379
+ );
562
380
 
563
- return cy.copyFromContainer(
564
- {
565
- destination: `${logDirectory}/php8.1-fpm-centreon-error.log`,
566
- name,
567
- source: '/var/log/php8.1-fpm-centreon-error.log'
568
- },
569
- { failOnNonZeroExit: false }
570
- );
571
- })
572
- .then(() => {
573
- if (Cypress.env('WEB_IMAGE_OS').includes('alma')) {
574
- return cy.copyFromContainer({
575
- destination: `${logDirectory}/httpd`,
576
- name,
577
- source: '/var/log/httpd'
578
- });
579
- }
381
+ interface StopContainerProps {
382
+ name: string;
383
+ }
580
384
 
581
- return cy.copyFromContainer(
582
- {
583
- destination: `${logDirectory}/apache2`,
584
- name,
585
- source: '/var/log/apache2'
586
- },
587
- { failOnNonZeroExit: false }
385
+ Cypress.Commands.add(
386
+ 'stopContainer',
387
+ ({ name }: StopContainerProps): Cypress.Chainable => {
388
+ cy.log(`Stopping container ${name}`);
389
+
390
+ cy.exec(`docker logs ${name}`).then(({ stdout }) => {
391
+ cy.writeFile(
392
+ `results/logs/${Cypress.spec.name.replace(
393
+ artifactIllegalCharactersMatcher,
394
+ '_'
395
+ )}/${Cypress.currentTest.title.replace(
396
+ artifactIllegalCharactersMatcher,
397
+ '_'
398
+ )}/container-${name}.log`,
399
+ stdout
588
400
  );
589
- })
590
- .exec(`chmod -R 755 "${logDirectory}"`)
591
- .task(
592
- 'stopContainers',
593
- {},
594
- { timeout: 600000 } // 10 minutes because docker pull can be very slow
595
- );
596
- });
401
+ });
597
402
 
598
- Cypress.Commands.add(
599
- 'createDirectory',
600
- (directoryPath: string): Cypress.Chainable => {
601
- return cy.task('createDirectory', directoryPath);
403
+ return cy.task('stopContainer', { name });
602
404
  }
603
405
  );
604
406
 
@@ -774,19 +576,6 @@ declare global {
774
576
  command,
775
577
  name
776
578
  }: ExecInContainerProps) => Cypress.Chainable;
777
- getByLabel: ({
778
- patternType,
779
- tag,
780
- label
781
- }: GetByLabelProps) => Cypress.Chainable;
782
- getByTestId: ({
783
- patternType,
784
- tag,
785
- testId
786
- }: GetByTestIdProps) => Cypress.Chainable;
787
- getContainerId: (containerName: string) => Cypress.Chainable;
788
- getContainerIpAddress: (containerName: string) => Cypress.Chainable;
789
- getContainersLogs: () => Cypress.Chainable;
790
579
  getIframeBody: () => Cypress.Chainable;
791
580
  getTimeFromHeader: () => Cypress.Chainable;
792
581
  getWebVersion: () => Cypress.Chainable;
@@ -797,51 +586,36 @@ declare global {
797
586
  dashboard: Dashboard,
798
587
  patch: PatchDashboardBody
799
588
  ) => Cypress.Chainable;
800
- loginAsAdminViaApiV2: () => Cypress.Chainable;
589
+
801
590
  loginByTypeOfUser: ({
802
591
  jsonName,
803
592
  loginViaApi
804
593
  }: LoginByTypeOfUserProps) => Cypress.Chainable;
805
- logout: () => void;
806
- logoutViaAPI: () => Cypress.Chainable;
807
594
  moveSortableElement: (direction: string) => Cypress.Chainable;
808
595
  navigateTo: ({
809
596
  page,
810
597
  rootItemNumber,
811
598
  subMenu
812
599
  }: NavigateToProps) => Cypress.Chainable;
813
- requestOnDatabase: ({
814
- database,
815
- query
816
- }: RequestOnDatabaseProps) => Cypress.Chainable;
817
- setUserTokenApiV1: ({
818
- login,
819
- password
820
- }?: SetUserTokenApiV1Props) => Cypress.Chainable;
821
600
  shareDashboardToUser: ({
822
601
  dashboardName,
823
602
  userName,
824
603
  role
825
604
  }: ShareDashboardToUserProps) => Cypress.Chainable;
826
605
  startContainer: ({
827
- command,
828
606
  name,
829
- image,
830
- portBindings
607
+ image
831
608
  }: StartContainerProps) => Cypress.Chainable;
832
- startContainers: ({
833
- composeFile,
834
- databaseImage,
835
- moduleName,
836
- openidImage,
837
- profiles,
609
+ startWebContainer: ({
610
+ name,
611
+ os,
838
612
  useSlim,
839
- webOs,
840
- webVersion
841
- }?: StartContainersProps) => Cypress.Chainable;
613
+ version
614
+ }?: StartWebContainerProps) => Cypress.Chainable;
842
615
  stopContainer: ({ name }: StopContainerProps) => Cypress.Chainable;
843
- stopContainers: () => Cypress.Chainable;
616
+ stopWebContainer: ({ name }?: StopWebContainerProps) => Cypress.Chainable;
844
617
  visitEmptyPage: () => Cypress.Chainable;
618
+ waitForContainerAndSetToken: () => Cypress.Chainable;
845
619
  }
846
620
  }
847
621
  }
@@ -13,6 +13,7 @@ import tasks from './tasks';
13
13
 
14
14
  interface ConfigurationOptions {
15
15
  cypressFolder?: string;
16
+ dockerName?: string;
16
17
  env?: Record<string, unknown>;
17
18
  envFile?: string;
18
19
  isDevelopment?: boolean;
@@ -23,6 +24,7 @@ export default ({
23
24
  specPattern,
24
25
  cypressFolder,
25
26
  isDevelopment,
27
+ dockerName,
26
28
  env,
27
29
  envFile
28
30
  }: ConfigurationOptions): Cypress.ConfigOptions => {
@@ -39,7 +41,6 @@ export default ({
39
41
  return defineConfig({
40
42
  chromeWebSecurity: false,
41
43
  defaultCommandTimeout: 6000,
42
- downloadsFolder: `${resultsFolder}/downloads`,
43
44
  e2e: {
44
45
  excludeSpecPattern: ['*.js', '*.ts', '*.md'],
45
46
  fixturesFolder: 'fixtures',
@@ -59,17 +60,16 @@ export default ({
59
60
  },
60
61
  env: {
61
62
  ...env,
62
- DATABASE_IMAGE: 'bitnami/mariadb:10.5',
63
63
  OPENID_IMAGE_VERSION: process.env.MAJOR || '24.04',
64
- SAML_IMAGE_VERSION: process.env.MAJOR || '24.04',
65
64
  WEB_IMAGE_OS: 'alma9',
66
- WEB_IMAGE_VERSION: webImageVersion
65
+ WEB_IMAGE_VERSION: webImageVersion,
66
+ dockerName: dockerName || 'centreon-dev'
67
67
  },
68
68
  execTimeout: 60000,
69
69
  requestTimeout: 10000,
70
70
  retries: 0,
71
71
  screenshotsFolder: `${resultsFolder}/screenshots`,
72
- video: isDevelopment,
72
+ video: true,
73
73
  videoCompression: 0,
74
74
  videosFolder: `${resultsFolder}/videos`
75
75
  });
@@ -11,7 +11,7 @@ export default (
11
11
  const width = 1920;
12
12
  const height = 1080;
13
13
 
14
- if (browser.family === 'chromium' && browser.name !== 'electron') {
14
+ if (browser.family === 'chromium') {
15
15
  if (browser.isHeadless) {
16
16
  launchOptions.args.push('--headless=new');
17
17
  }
@@ -1,40 +1,10 @@
1
- /* eslint-disable no-console */
2
1
  import { execSync } from 'child_process';
3
2
  import { existsSync, mkdirSync } from 'fs';
4
- import path from 'path';
5
3
 
6
- import tar from 'tar-fs';
7
- import {
8
- DockerComposeEnvironment,
9
- GenericContainer,
10
- StartedDockerComposeEnvironment,
11
- StartedTestContainer,
12
- Wait,
13
- getContainerRuntimeClient
14
- } from 'testcontainers';
15
- import { createConnection } from 'mysql2/promise';
16
-
17
- interface Containers {
18
- [key: string]: StartedTestContainer;
19
- }
4
+ import Docker from 'dockerode';
20
5
 
21
6
  export default (on: Cypress.PluginEvents): void => {
22
- let dockerEnvironment: StartedDockerComposeEnvironment | null = null;
23
- const containers: Containers = {};
24
-
25
- const getContainer = (containerName): StartedTestContainer => {
26
- let container;
27
-
28
- if (dockerEnvironment !== null) {
29
- container = dockerEnvironment.getContainer(`${containerName}-1`);
30
- } else if (containers[containerName]) {
31
- container = containers[containerName];
32
- } else {
33
- throw new Error(`Cannot get container ${containerName}`);
34
- }
35
-
36
- return container;
37
- };
7
+ const docker = new Docker();
38
8
 
39
9
  interface PortBinding {
40
10
  destination: number;
@@ -42,7 +12,6 @@ export default (on: Cypress.PluginEvents): void => {
42
12
  }
43
13
 
44
14
  interface StartContainerProps {
45
- command?: string;
46
15
  image: string;
47
16
  name: string;
48
17
  portBindings: Array<PortBinding>;
@@ -53,48 +22,6 @@ export default (on: Cypress.PluginEvents): void => {
53
22
  }
54
23
 
55
24
  on('task', {
56
- copyFromContainer: async ({ destination, serviceName, source }) => {
57
- try {
58
- if (dockerEnvironment !== null) {
59
- const container = dockerEnvironment.getContainer(`${serviceName}-1`);
60
-
61
- await container
62
- .copyArchiveFromContainer(source)
63
- .then((archiveStream) => {
64
- return new Promise<void>((resolve) => {
65
- const dest = tar.extract(destination);
66
- archiveStream.pipe(dest);
67
- dest.on('finish', resolve);
68
- });
69
- });
70
- }
71
- } catch (error) {
72
- console.error(error);
73
- }
74
-
75
- return null;
76
- },
77
- copyToContainer: async ({ destination, serviceName, source, type }) => {
78
- const container = getContainer(serviceName);
79
-
80
- if (type === 'directory') {
81
- await container.copyDirectoriesToContainer([
82
- {
83
- source,
84
- target: destination
85
- }
86
- ]);
87
- } else if (type === 'file') {
88
- await container.copyFilesToContainer([
89
- {
90
- source,
91
- target: destination
92
- }
93
- ]);
94
- }
95
-
96
- return null;
97
- },
98
25
  createDirectory: async (directoryPath: string) => {
99
26
  if (!existsSync(directoryPath)) {
100
27
  mkdirSync(directoryPath, { recursive: true });
@@ -102,150 +29,70 @@ export default (on: Cypress.PluginEvents): void => {
102
29
 
103
30
  return null;
104
31
  },
105
- execInContainer: async ({ command, name }) => {
106
- const { exitCode, output } = await getContainer(name).exec([
107
- 'bash',
108
- '-c',
109
- command
110
- ]);
111
-
112
- return { exitCode, output };
113
- },
114
- getContainerId: (containerName: string) =>
115
- getContainer(containerName).getId(),
116
- getContainerIpAddress: (containerName: string) => {
117
- const container = getContainer(containerName);
118
-
119
- const networkNames = container.getNetworkNames();
120
-
121
- return container.getIpAddress(networkNames[0]);
122
- },
123
- getContainersLogs: async () => {
124
- try {
125
- const { dockerode } = (await getContainerRuntimeClient()).container;
126
- const loggedContainers = await dockerode.listContainers();
127
-
128
- return loggedContainers.reduce((acc, container) => {
129
- const containerName = container.Names[0].replace('/', '');
130
- acc[containerName] = execSync(`docker logs -t ${container.Id}`, {
131
- stdio: 'pipe'
132
- }).toString('utf8');
133
-
134
- return acc;
135
- }, {});
136
- } catch (error) {
137
- console.warn('Cannot get containers logs');
138
- console.warn(error);
139
-
140
- return null;
141
- }
142
- },
143
- requestOnDatabase: async ({ database, query }) => {
144
- let container: StartedTestContainer | null = null;
145
-
146
- if (dockerEnvironment !== null) {
147
- container = dockerEnvironment.getContainer('db-1');
148
- } else {
149
- container = getContainer('web');
150
- }
151
-
152
- const client = await createConnection({
153
- database,
154
- host: container.getHost(),
155
- password: 'centreon',
156
- port: container.getMappedPort(3306),
157
- user: 'centreon'
158
- });
159
-
160
- const [rows, fields] = await client.execute(query);
161
-
162
- await client.end();
163
-
164
- return [rows, fields];
165
- },
166
32
  startContainer: async ({
167
- command,
168
33
  image,
169
34
  name,
170
35
  portBindings = []
171
36
  }: StartContainerProps) => {
172
- let container = await new GenericContainer(image).withName(name);
37
+ const imageList = execSync(
38
+ 'docker image list --format "{{.Repository}}:{{.Tag}}"'
39
+ ).toString('utf8');
40
+
41
+ if (
42
+ !imageList.match(
43
+ new RegExp(
44
+ `^${image.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')}`,
45
+ 'm'
46
+ )
47
+ )
48
+ ) {
49
+ execSync(`docker pull ${image}`);
50
+ }
173
51
 
174
- portBindings.forEach(({ source, destination }) => {
175
- container = container.withExposedPorts({
176
- container: source,
177
- host: destination
178
- });
52
+ const webContainers = await docker.listContainers({
53
+ all: true,
54
+ filters: { name: [name] }
179
55
  });
180
-
181
- if (command) {
182
- container
183
- .withCommand(['bash', '-c', command])
184
- .withWaitStrategy(Wait.forSuccessfulCommand('ls'));
56
+ if (webContainers.length) {
57
+ return webContainers[0];
185
58
  }
186
59
 
187
- containers[name] = await container.start();
188
-
189
- return container;
190
- },
191
- startContainers: async ({
192
- composeFile,
193
- databaseImage,
194
- openidImage,
195
- profiles,
196
- samlImage,
197
- webImage
198
- }) => {
199
- try {
200
- const composeFileDir = path.dirname(composeFile);
201
- const composeFileName = path.basename(composeFile);
202
-
203
- dockerEnvironment = await new DockerComposeEnvironment(
204
- composeFileDir,
205
- composeFileName
206
- )
207
- .withEnvironment({
208
- MYSQL_IMAGE: databaseImage,
209
- OPENID_IMAGE: openidImage,
210
- SAML_IMAGE: samlImage,
211
- WEB_IMAGE: webImage
212
- })
213
- .withProfiles(...profiles)
214
- .withWaitStrategy(
215
- 'web-1',
216
- Wait.forAll([
217
- Wait.forHealthCheck(),
218
- Wait.forLogMessage('Centreon is ready')
219
- ])
220
- )
221
- .up();
60
+ const container = await docker.createContainer({
61
+ AttachStderr: true,
62
+ AttachStdin: false,
63
+ AttachStdout: true,
64
+ ExposedPorts: portBindings.reduce((accumulator, currentValue) => {
65
+ accumulator[`${currentValue.source}/tcp`] = {};
66
+
67
+ return accumulator;
68
+ }, {}),
69
+ HostConfig: {
70
+ PortBindings: portBindings.reduce((accumulator, currentValue) => {
71
+ accumulator[`${currentValue.source}/tcp`] = [
72
+ {
73
+ HostIP: '127.0.0.1',
74
+ HostPort: `${currentValue.destination}`
75
+ }
76
+ ];
77
+
78
+ return accumulator;
79
+ }, {})
80
+ },
81
+ Image: image,
82
+ OpenStdin: false,
83
+ StdinOnce: false,
84
+ Tty: true,
85
+ name
86
+ });
222
87
 
223
- return null;
224
- } catch (error) {
225
- if (error instanceof Error) {
226
- console.error(error.message);
227
- }
88
+ await container.start();
228
89
 
229
- throw error;
230
- }
90
+ return container;
231
91
  },
232
92
  stopContainer: async ({ name }: StopContainerProps) => {
233
- if (containers[name]) {
234
- const container = containers[name];
235
-
236
- await container.stop();
237
-
238
- delete containers[name];
239
- }
240
-
241
- return null;
242
- },
243
- stopContainers: async () => {
244
- if (dockerEnvironment !== null) {
245
- await dockerEnvironment.down();
246
-
247
- dockerEnvironment = null;
248
- }
93
+ const container = await docker.getContainer(name);
94
+ await container.kill();
95
+ await container.remove();
249
96
 
250
97
  return null;
251
98
  },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@centreon/js-config",
3
3
  "description": "Centreon Frontend shared build configuration",
4
- "version": "24.4.1-MON-23368-containers.127",
4
+ "version": "24.4.1-MON-34691-improve-code-coverage.1",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/centreon/centreon-frontend.git"
@@ -24,23 +24,23 @@
24
24
  "cypress"
25
25
  ],
26
26
  "peerDependencies": {
27
- "eslint": "^8.53.0",
28
- "prettier": "^3.0.0"
27
+ "prettier": "^3.0.0",
28
+ "eslint": "^8.53.0"
29
29
  },
30
30
  "dependencies": {
31
- "@badeball/cypress-cucumber-preprocessor": "^20.0.1",
31
+ "@badeball/cypress-cucumber-preprocessor": "^19.1.0",
32
32
  "@bahmutov/cypress-esbuild-preprocessor": "^2.2.0",
33
33
  "@esbuild-plugins/node-globals-polyfill": "^0.2.3",
34
34
  "@esbuild-plugins/node-modules-polyfill": "^0.2.2",
35
35
  "@tsconfig/node16": "^16.1.1",
36
36
  "@tsconfig/node20": "^20.1.2",
37
37
  "@types/cypress-cucumber-preprocessor": "^4.0.5",
38
- "cypress": "^13.6.4",
38
+ "@types/dockerode": "^3.3.23",
39
39
  "cypress-multi-reporters": "^1.6.4",
40
- "cypress-terminal-report": "^6.0.0",
41
- "cypress-wait-until": "^3.0.1",
42
- "dotenv": "^16.4.1",
43
- "esbuild": "^0.20.0",
40
+ "cypress-terminal-report": "^5.3.9",
41
+ "dockerode": "^4.0.0",
42
+ "dotenv": "^16.3.1",
43
+ "esbuild": "^0.19.5",
44
44
  "eslint": "^8.53.0",
45
45
  "eslint-config-airbnb": "19.0.4",
46
46
  "eslint-config-prettier": "^8.5.0",
@@ -58,9 +58,6 @@
58
58
  "eslint-plugin-react-hooks": "^4.5.0",
59
59
  "eslint-plugin-sort-keys-fix": "^1.1.2",
60
60
  "eslint-plugin-typescript-sort-keys": "^2.1.0",
61
- "mochawesome": "^7.1.3",
62
- "mysql2": "^3.9.1",
63
- "tar-fs": "^3.0.4",
64
- "testcontainers": "^10.7.1"
61
+ "mochawesome": "^7.1.3"
65
62
  }
66
63
  }