@centreon/e2e-config 1.0.0 → 27.1.0

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,1111 @@
1
+ /* eslint-disable @typescript-eslint/no-namespace */
2
+ import path from 'path';
3
+ import 'cypress-wait-until';
4
+
5
+ import './commands/configuration';
6
+ import './commands/monitoring';
7
+
8
+ import installLogsCollector from 'cypress-terminal-report/src/installLogsCollector';
9
+
10
+ installLogsCollector({
11
+ commandTimings: 'seconds',
12
+ enableExtendedCollector: true
13
+ });
14
+
15
+ const apiBase = '/centreon/api';
16
+ const apiActionV1 = `${apiBase}/index.php`;
17
+ const apiLoginV2 = '/centreon/authentication/providers/configurations/local';
18
+
19
+ const artifactIllegalCharactersMatcher = /[,\s/|<>*?:"]/g;
20
+
21
+ export enum PatternType {
22
+ contains = '*',
23
+ endsWith = '$',
24
+ equals = '',
25
+ startsWith = '^'
26
+ }
27
+
28
+ interface GetByLabelProps {
29
+ label: string;
30
+ patternType?: PatternType;
31
+ tag?: string;
32
+ }
33
+
34
+ Cypress.Commands.add(
35
+ 'getByLabel',
36
+ ({
37
+ tag = '',
38
+ patternType = PatternType.equals,
39
+ label
40
+ }: GetByLabelProps): Cypress.Chainable => {
41
+ return cy.get(`${tag}[aria-label${patternType}="${label}"]`);
42
+ }
43
+ );
44
+
45
+ interface GetByTestIdProps {
46
+ patternType?: PatternType;
47
+ tag?: string;
48
+ testId: string;
49
+ }
50
+
51
+ Cypress.Commands.add(
52
+ 'getByTestId',
53
+ ({
54
+ tag = '',
55
+ patternType = PatternType.equals,
56
+ testId
57
+ }: GetByTestIdProps): Cypress.Chainable => {
58
+ return cy.get(`${tag}[data-testid${patternType}="${testId}"]`);
59
+ }
60
+ );
61
+
62
+ Cypress.Commands.add('getWebVersion', (): Cypress.Chainable => {
63
+ return cy
64
+ .exec(
65
+ `bash -c "grep version ../../www/install/insertBaseConf.sql | cut -d \\' -f 4 | awk 'NR==2'"`
66
+ )
67
+ .then(({ stdout }) => {
68
+ const found = stdout.match(/(\d+\.\d+)\.(\d+)/);
69
+ if (found) {
70
+ return cy.wrap({ major_version: found[1], minor_version: found[2] });
71
+ }
72
+
73
+ throw new Error('Current web version cannot be parsed.');
74
+ });
75
+ });
76
+
77
+ Cypress.Commands.add(
78
+ 'getIframeBody',
79
+ (iframeSelector = 'iframe#main-content'): Cypress.Chainable<JQuery<HTMLElement>> => {
80
+ return cy.waitUntil(
81
+ () =>
82
+ cy
83
+ .get<HTMLIFrameElement>(iframeSelector, { log: false })
84
+ .then($iframe => {
85
+ const doc = $iframe[0].contentDocument;
86
+
87
+ return Boolean(
88
+ doc &&
89
+ doc.readyState === 'complete' &&
90
+ doc.body &&
91
+ doc.body.children.length > 0
92
+ );
93
+ }),
94
+ {
95
+ timeout: 20000,
96
+ interval: 200,
97
+ errorMsg: 'Iframe not fully loaded (readyState !== complete)',
98
+ }
99
+ ).then(() => {
100
+ return cy
101
+ .get<HTMLIFrameElement>(iframeSelector)
102
+ .then($iframe => {
103
+ const body = $iframe[0].contentDocument!.body;
104
+ return cy.wrap(body);
105
+ });
106
+ });
107
+ }
108
+ );
109
+
110
+ Cypress.Commands.add(
111
+ 'waitForElementInIframe',
112
+ (iframeSelector, elementSelector) => {
113
+ // Return the visibility: within() yields the body, which passed the wait at once
114
+ cy.waitUntil(
115
+ () =>
116
+ cy
117
+ .get(iframeSelector)
118
+ .its('0.contentDocument.body')
119
+ .should('not.be.empty')
120
+ .then((body) => {
121
+ const element = Cypress.$(body).find(elementSelector);
122
+
123
+ return element.length > 0 && element.is(':visible');
124
+ }),
125
+ {
126
+ errorMsg: 'The element is not visible',
127
+ interval: 5000,
128
+ timeout: 100000
129
+ }
130
+ ).then((isVisible) => {
131
+ if (!isVisible) {
132
+ throw new Error('The element is not visible');
133
+ }
134
+ });
135
+ }
136
+ );
137
+
138
+ Cypress.Commands.add(
139
+ 'waitForElementToBeVisible',
140
+ (selector, timeout = 50000, interval = 2000) => {
141
+ cy.waitUntil(
142
+ () =>
143
+ cy.get('body').then(($body) => {
144
+ const element = $body.find(selector);
145
+
146
+ return element.length > 0 && element.is(':visible');
147
+ }),
148
+ {
149
+ errorMsg: `The element '${selector}' is not visible`,
150
+ interval,
151
+ timeout
152
+ }
153
+ ).then((isVisible) => {
154
+ if (!isVisible) {
155
+ throw new Error(`The element '${selector}' is not visible`);
156
+ }
157
+ });
158
+ }
159
+ );
160
+
161
+ Cypress.Commands.add(
162
+ 'hoverRootMenuItem',
163
+ (rootItemNumber: number): Cypress.Chainable => {
164
+ return cy
165
+ .get('div[data-testid="sidebar"] li')
166
+ .eq(rootItemNumber)
167
+ .trigger('mouseover');
168
+ }
169
+ );
170
+
171
+ Cypress.Commands.add(
172
+ 'clickSubRootMenuItem',
173
+ (page: string): Cypress.Chainable => {
174
+ return cy.get('div[data-cy="collapse"]').eq(1).contains(page).click();
175
+ }
176
+ );
177
+
178
+ interface NavigateToProps {
179
+ page: string;
180
+ rootItemNumber: number;
181
+ subMenu?: string;
182
+ }
183
+
184
+ Cypress.Commands.add(
185
+ 'navigateTo',
186
+ ({ rootItemNumber, subMenu, page }: NavigateToProps): void => {
187
+ if (subMenu) {
188
+ cy.hoverRootMenuItem(rootItemNumber)
189
+ .contains(subMenu)
190
+ .trigger('mouseover')
191
+ .get('.MuiCollapse-wrapper')
192
+ .find('div[data-cy="collapse"]')
193
+ .should('be.visible')
194
+ .and('contain', page);
195
+
196
+ cy.clickSubRootMenuItem(page);
197
+
198
+ return;
199
+ }
200
+ cy.hoverRootMenuItem(rootItemNumber).contains(page).click({ force: true });
201
+ }
202
+ );
203
+
204
+ Cypress.Commands.add(
205
+ 'moveSortableElement',
206
+ {
207
+ prevSubject: 'element'
208
+ },
209
+ (subject, direction): void => {
210
+ const key = `{${direction}arrow}`;
211
+
212
+ cy.wrap(subject)
213
+ .type(' ', {
214
+ force: true,
215
+ scrollBehavior: false
216
+ })
217
+ .closest('body')
218
+ .type(key, {
219
+ scrollBehavior: false
220
+ })
221
+ .type(' ', {
222
+ scrollBehavior: false
223
+ });
224
+ }
225
+ );
226
+
227
+ Cypress.Commands.add('getContainerId', (containerName: string) => {
228
+ cy.log(`Getting container id of ${containerName}`);
229
+
230
+ return cy.task('getContainerId', containerName);
231
+ });
232
+
233
+ Cypress.Commands.add('getContainerIpAddress', (containerName: string) => {
234
+ cy.log(`Getting container ip address of ${containerName}`);
235
+
236
+ return cy.task('getContainerIpAddress', containerName);
237
+ });
238
+
239
+ Cypress.Commands.add('getContainersLogs', () => {
240
+ cy.log('Getting containers logs');
241
+
242
+ return cy.task('getContainersLogs');
243
+ });
244
+
245
+ Cypress.Commands.add('getContainerMappedPort', (containerName: string, containerPort: number) => {
246
+ cy.log(`Getting mapped port ${containerPort} of container ${containerName}`);
247
+
248
+ return cy.task('getContainerMappedPort', { containerName, containerPort });
249
+ });
250
+
251
+ interface CopyFromContainerProps {
252
+ destination: string;
253
+ name?: string;
254
+ source: string;
255
+ }
256
+
257
+ Cypress.Commands.add(
258
+ 'copyFromContainer',
259
+ ({ name = 'web', source, destination }: CopyFromContainerProps) => {
260
+ cy.log(`Copy content from ${name}:${source} to ${destination}`);
261
+
262
+ return cy.task('copyFromContainer', {
263
+ destination,
264
+ serviceName: name,
265
+ source
266
+ });
267
+ }
268
+ );
269
+
270
+ export enum CopyToContainerContentType {
271
+ Directory = 'directory',
272
+ File = 'file'
273
+ }
274
+
275
+ interface CopyToContainerProps {
276
+ destination: string;
277
+ name?: string;
278
+ source: string;
279
+ type: CopyToContainerContentType;
280
+ }
281
+
282
+ Cypress.Commands.add(
283
+ 'copyToContainer',
284
+ ({ name = 'web', source, destination, type }: CopyToContainerProps) => {
285
+ cy.log(`Copy content from ${source} to ${name}:${destination}`);
286
+
287
+ return cy.task('copyToContainer', {
288
+ destination,
289
+ serviceName: name,
290
+ source,
291
+ type
292
+ });
293
+ }
294
+ );
295
+
296
+ Cypress.Commands.add('loginAsAdminViaApiV2', (): Cypress.Chainable => {
297
+ return cy.request({
298
+ body: {
299
+ login: 'admin',
300
+ password: 'Centreon!2021'
301
+ },
302
+ method: 'POST',
303
+ url: apiLoginV2
304
+ });
305
+ });
306
+
307
+ interface LoginByTypeOfUserProps {
308
+ jsonName?: string;
309
+ loginViaApi?: boolean;
310
+ }
311
+
312
+ Cypress.Commands.add(
313
+ 'loginByTypeOfUser',
314
+ ({ jsonName = 'admin', loginViaApi = false }): Cypress.Chainable => {
315
+ if (loginViaApi) {
316
+ return cy
317
+ .fixture(`users/${jsonName}.json`)
318
+ .then((user) => {
319
+ return cy.request({
320
+ body: {
321
+ login: user.login,
322
+ password: user.password
323
+ },
324
+ method: 'POST',
325
+ url: apiLoginV2
326
+ });
327
+ })
328
+ .visit(`${Cypress.config().baseUrl}`)
329
+ .wait('@getNavigationList');
330
+ }
331
+
332
+ cy.visit(`${Cypress.config().baseUrl}`)
333
+ .fixture(`users/${jsonName}.json`)
334
+ .then((credential) => {
335
+ cy.getByLabel({ label: 'Alias', tag: 'input' }).type(
336
+ `{selectAll}{backspace}${credential.login}`
337
+ );
338
+ cy.get('input[type="password"]').type(
339
+ `{selectAll}{backspace}${credential.password}`
340
+ );
341
+ })
342
+ .getByLabel({ label: 'Connect', tag: 'button' })
343
+ .click();
344
+
345
+ return cy.get('.MuiAlert-message').then(($snackbar) => {
346
+ if ($snackbar.text().includes('Login succeeded')) {
347
+ cy.wait('@getNavigationList');
348
+ cy.get('.MuiAlert-message').should('not.be.visible');
349
+ }
350
+ });
351
+ }
352
+ );
353
+
354
+ Cypress.Commands.add('logout', (): void => {
355
+ cy.getByLabel({ label: 'Profile' }).should('exist').click();
356
+
357
+ cy.intercept({
358
+ method: 'GET',
359
+ times: 1,
360
+ url: '/centreon/api/latest/authentication/logout'
361
+ }).as('logout');
362
+
363
+ cy.contains(/^Logout$/).click();
364
+
365
+ cy.waitUntil(() =>
366
+ cy.wait('@logout').then((interception) => {
367
+ return interception?.response?.statusCode === 302;
368
+ }),
369
+ {
370
+ errorMsg: 'Logout did not complete successfully',
371
+ timeout: 30000,
372
+ interval: 2000
373
+ }
374
+ );
375
+
376
+ // https://github.com/cypress-io/cypress/issues/25841
377
+ cy.clearAllCookies();
378
+ });
379
+
380
+ interface LogoutViaAPIProps {
381
+ failOnError?: boolean;
382
+ }
383
+
384
+ Cypress.Commands.add('logoutViaAPI', ({ failOnError = true }: LogoutViaAPIProps = {}): Cypress.Chainable => {
385
+ return cy
386
+ .request({
387
+ failOnStatusCode: failOnError,
388
+ method: 'GET',
389
+ url: '/centreon/authentication/logout'
390
+ })
391
+ .visit('/')
392
+ .getByLabel({ label: 'Alias', tag: 'input' });
393
+ });
394
+
395
+ Cypress.Commands.add(
396
+ 'visitEmptyPage',
397
+ (): Cypress.Chainable =>
398
+ cy
399
+ .intercept('/waiting-page', {
400
+ headers: { 'content-type': 'text/html' },
401
+ statusCode: 200
402
+ })
403
+ .visit('/waiting-page')
404
+ );
405
+
406
+ interface ExecInContainerProps {
407
+ command: string | Array<string>;
408
+ name: string;
409
+ }
410
+
411
+ interface ExecInContainerOptions {
412
+ log: boolean;
413
+ }
414
+
415
+ interface ExecInContainerResult {
416
+ exitCode: number;
417
+ output: string;
418
+ }
419
+
420
+ Cypress.Commands.add(
421
+ 'execInContainer',
422
+ ({ command, name }, { log = true } = { log: true }): Cypress.Chainable => {
423
+ const commands =
424
+ typeof command === 'string' || command instanceof String
425
+ ? [command]
426
+ : command;
427
+
428
+ const results = commands.reduce(
429
+ (acc, runCommand) => {
430
+ cy.task<ExecInContainerResult>(
431
+ 'execInContainer',
432
+ { command: runCommand, name },
433
+ { log, timeout: 600000 }
434
+ ).then((result) => {
435
+ const displayedOutput = log ? result.output : 'hidden command output';
436
+ const displayedRunCommand = log ? runCommand : 'hidden run command';
437
+
438
+ if (result.exitCode) {
439
+ cy.log(displayedOutput);
440
+
441
+ // output will not be truncated
442
+ throw new Error(`
443
+ Execution of "${displayedRunCommand}" failed
444
+ Exit code: ${result.exitCode}
445
+ Output:\n${displayedOutput}`);
446
+ }
447
+
448
+ acc.output = `${acc.output}${displayedOutput}`;
449
+ });
450
+
451
+ return acc;
452
+ },
453
+ { exitCode: 0, output: '' }
454
+ );
455
+
456
+ return cy.wrap(results);
457
+ }
458
+ );
459
+
460
+ interface RequestOnDatabaseProps {
461
+ database: string;
462
+ params?: Array<string | number>;
463
+ query: string;
464
+ }
465
+
466
+ Cypress.Commands.add(
467
+ 'requestOnDatabase',
468
+ ({ database, query, params }: RequestOnDatabaseProps): Cypress.Chainable => {
469
+ return cy.task('requestOnDatabase', { database, query, params });
470
+ }
471
+ );
472
+
473
+ interface SetUserTokenApiV1Props {
474
+ login?: string;
475
+ password?: string;
476
+ }
477
+
478
+ Cypress.Commands.add(
479
+ 'setUserTokenApiV1',
480
+ ({
481
+ login = 'admin',
482
+ password = 'Centreon!2021'
483
+ }: SetUserTokenApiV1Props = {}): Cypress.Chainable => {
484
+ return cy
485
+ .request({
486
+ body: {
487
+ password,
488
+ username: login
489
+ },
490
+ headers: {
491
+ 'Content-Type': 'application/x-www-form-urlencoded'
492
+ },
493
+ method: 'POST',
494
+ url: `${apiActionV1}?action=authenticate`
495
+ })
496
+ .then(({ body }) =>
497
+ window.localStorage.setItem('userTokenApiV1', body.authToken)
498
+ );
499
+ }
500
+ );
501
+
502
+ // The token is set once in the feature's before(), so it is missing when a
503
+ // test is retried: get it again only in that case.
504
+ Cypress.Commands.add('ensureUserTokenApiV1', (): Cypress.Chainable => {
505
+ if (window.localStorage.getItem('userTokenApiV1')) {
506
+ return cy.wrap(null);
507
+ }
508
+
509
+ return cy.setUserTokenApiV1();
510
+ });
511
+
512
+ interface PortBinding {
513
+ destination: number;
514
+ source: number;
515
+ }
516
+
517
+ interface StartContainerProps {
518
+ command?: string;
519
+ image: string;
520
+ name: string;
521
+ portBindings: Array<PortBinding>;
522
+ }
523
+
524
+ Cypress.Commands.add(
525
+ 'startContainer',
526
+ ({
527
+ command,
528
+ name,
529
+ image,
530
+ portBindings
531
+ }: StartContainerProps): Cypress.Chainable => {
532
+ cy.log(`Starting container ${name} from image ${image}`);
533
+
534
+ return cy.task(
535
+ 'startContainer',
536
+ { command, image, name, portBindings },
537
+ { timeout: 600000 } // 10 minutes because docker pull can be very slow
538
+ );
539
+ }
540
+ );
541
+
542
+ interface StartContainersProps {
543
+ composeFile?: string;
544
+ databaseImage?: string;
545
+ dbConfiguration?: string;
546
+ dbStorage?: string;
547
+ moduleName?: string;
548
+ openidImage?: string;
549
+ profiles?: Array<string>;
550
+ samlImage?: string;
551
+ useSlim?: boolean;
552
+ webOs?: string;
553
+ webVersion?: string;
554
+ }
555
+
556
+ Cypress.Commands.add(
557
+ 'startContainers',
558
+ ({
559
+ composeFile,
560
+ databaseImage = Cypress.env('DATABASE_IMAGE'),
561
+ dbConfiguration = Cypress.env('MYSQL_DB_CONFIGURATION'),
562
+ dbStorage = Cypress.env('MYSQL_DB_STORAGE'),
563
+ moduleName = 'centreon-web',
564
+ openidImage = `ghcr.io/centreon/centreon/keycloak:${Cypress.env(
565
+ 'OPENID_IMAGE_VERSION'
566
+ )}`,
567
+ profiles = [],
568
+ samlImage = `ghcr.io/centreon/centreon/keycloak:${Cypress.env(
569
+ 'SAML_IMAGE_VERSION'
570
+ )}`,
571
+ useSlim = true,
572
+ webOs = Cypress.env('WEB_IMAGE_OS'),
573
+ webVersion = Cypress.env('WEB_IMAGE_VERSION')
574
+ }: StartContainersProps = {}): Cypress.Chainable => {
575
+ cy.log('Starting containers ...');
576
+
577
+ let composeFilePath = composeFile;
578
+ if (!composeFile) {
579
+ const cypressDir = path.dirname(Cypress.config('configFile'));
580
+ composeFilePath = `${cypressDir}/../../../.github/docker/docker-compose.yml`;
581
+ }
582
+
583
+ const slimSuffix = useSlim ? '-slim' : '';
584
+
585
+ const webImage = `docker.centreon.com/centreon/${moduleName}${slimSuffix}-${webOs}:${webVersion}`;
586
+
587
+ const timeout = 1200_000; // 20 minutes because docker pull can be very slow (mainly keycloak)
588
+ const cypressTaskTimeout = Cypress.config('taskTimeout') || 600_000;
589
+ Cypress.config('taskTimeout', timeout);
590
+
591
+ cy.task(
592
+ 'startContainers',
593
+ {
594
+ composeFile: composeFilePath,
595
+ databaseImage,
596
+ dbConfiguration,
597
+ dbStorage,
598
+ openidImage,
599
+ profiles,
600
+ samlImage,
601
+ webImage
602
+ },
603
+ { timeout }
604
+ )
605
+ .then(() => {
606
+ const baseUrl = 'http://127.0.0.1:4000';
607
+
608
+ Cypress.config('baseUrl', baseUrl);
609
+
610
+ return cy.wrap(null);
611
+ })
612
+ .visit('/') // this is necessary to refresh browser cause baseUrl has changed (flash appears in video)
613
+ .setUserTokenApiV1();
614
+
615
+ Cypress.config('taskTimeout', cypressTaskTimeout);
616
+
617
+ return cy.wrap(null);
618
+ }
619
+ );
620
+
621
+ interface StopContainerProps {
622
+ name: string;
623
+ }
624
+
625
+ Cypress.Commands.add(
626
+ 'stopContainer',
627
+ ({ name }: StopContainerProps): Cypress.Chainable => {
628
+ cy.log(`Stopping container ${name}`);
629
+
630
+ return cy.task('stopContainer', { name });
631
+ }
632
+ );
633
+
634
+ Cypress.Commands.add(
635
+ 'getLogDirectory',
636
+ (): Cypress.Chainable => {
637
+ const logDirectory = `results/logs/${Cypress.spec.name.replace(
638
+ artifactIllegalCharactersMatcher,
639
+ '_'
640
+ )}/${Cypress.currentTest.title.replace(
641
+ artifactIllegalCharactersMatcher,
642
+ '_'
643
+ )}`;
644
+
645
+ return cy
646
+ .createDirectory(logDirectory)
647
+ .exec(`chmod -R 755 "${logDirectory}"`)
648
+ .wrap(logDirectory);
649
+ }
650
+ );
651
+
652
+ interface CopyWebContainerLogsProps {
653
+ name: string;
654
+ }
655
+
656
+ Cypress.Commands.add(
657
+ 'copyWebContainerLogs',
658
+ ({ name }: CopyWebContainerLogsProps): Cypress.Chainable => {
659
+ cy.log(`Getting logs from container ${name} ...`);
660
+
661
+ return cy.getLogDirectory().then((logDirectory) => {
662
+ let sourcePhpLogs = '/var/log/centreon/prod.web.log';
663
+ let targetPhpLogs = `${logDirectory}/prod.web.log`;
664
+ let sourceApacheLogs = '/var/log/apache2';
665
+ let targetApacheLogs = `${logDirectory}/apache2`;
666
+ if (Cypress.env('WEB_IMAGE_OS').includes('alma')) {
667
+ sourcePhpLogs = '/var/log/php-fpm';
668
+ targetPhpLogs = `${logDirectory}/php`;
669
+ sourceApacheLogs = '/var/log/httpd';
670
+ targetApacheLogs = `${logDirectory}/httpd`;
671
+ }
672
+
673
+ return cy
674
+ .copyFromContainer({
675
+ destination: `${logDirectory}/broker`,
676
+ name,
677
+ source: '/var/log/centreon-broker'
678
+ })
679
+ .copyFromContainer({
680
+ destination: `${logDirectory}/engine`,
681
+ name,
682
+ source: '/var/log/centreon-engine'
683
+ })
684
+ .copyFromContainer({
685
+ destination: `${logDirectory}/centreon`,
686
+ name,
687
+ source: '/var/log/centreon'
688
+ })
689
+ .copyFromContainer({
690
+ destination: `${logDirectory}/centreon-gorgone`,
691
+ name,
692
+ source: '/var/log/centreon-gorgone'
693
+ })
694
+ .copyFromContainer({
695
+ destination: targetPhpLogs,
696
+ name,
697
+ source: sourcePhpLogs,
698
+ })
699
+ .copyFromContainer({
700
+ destination: targetApacheLogs,
701
+ name,
702
+ source: sourceApacheLogs,
703
+ })
704
+ .exec(`chmod -R 755 "${logDirectory}"`);
705
+ });
706
+ });
707
+
708
+ Cypress.Commands.add('stopContainers', (): Cypress.Chainable => {
709
+ cy.log('Stopping containers ...');
710
+
711
+ const name = 'web';
712
+
713
+ return cy
714
+ .visitEmptyPage()
715
+ .getLogDirectory()
716
+ .then((logDirectory) => {
717
+ return cy
718
+ .getContainersLogs()
719
+ .then((containersLogs: Array<Array<string>>) => {
720
+ if (!containersLogs) {
721
+ return;
722
+ }
723
+
724
+ Object.entries(containersLogs).forEach(([containerName, logs]) => {
725
+ cy.writeFile(
726
+ `${logDirectory}/container-${containerName}.log`,
727
+ logs
728
+ );
729
+ });
730
+ })
731
+ .copyWebContainerLogs({ name })
732
+ .exec(`chmod -R 755 "${logDirectory}"`)
733
+ .task(
734
+ 'stopContainers',
735
+ {},
736
+ { timeout: 600000 } // 10 minutes because docker pull can be very slow
737
+ );
738
+ });
739
+ });
740
+
741
+ Cypress.Commands.add(
742
+ 'createDirectory',
743
+ (directoryPath: string): Cypress.Chainable => {
744
+ return cy.task('createDirectory', directoryPath);
745
+ }
746
+ );
747
+
748
+ interface Dashboard {
749
+ description?: string;
750
+ name: string;
751
+ }
752
+
753
+ Cypress.Commands.add(
754
+ 'insertDashboardList',
755
+ (fixtureFile: string): Cypress.Chainable => {
756
+ return cy.fixture(fixtureFile).then((dashboardList) => {
757
+ cy.wrap(
758
+ Promise.all(
759
+ dashboardList.map((dashboardBody: Dashboard) =>
760
+ cy.insertDashboard({ ...dashboardBody })
761
+ )
762
+ )
763
+ );
764
+ });
765
+ }
766
+ );
767
+
768
+ Cypress.Commands.add(
769
+ 'insertDashboard',
770
+ (dashboardBody: Dashboard): Cypress.Chainable => {
771
+ return cy.request({
772
+ body: {
773
+ ...dashboardBody
774
+ },
775
+ method: 'POST',
776
+ url: '/centreon/api/latest/configuration/dashboards'
777
+ });
778
+ }
779
+ );
780
+
781
+ Cypress.Commands.add('insertDashboardWithWidget', (dashboardBody, patchBody, widgetName, widgetType) => {
782
+ cy.request({
783
+ body: { ...dashboardBody },
784
+ method: 'POST',
785
+ url: '/centreon/api/latest/configuration/dashboards'
786
+ }).then((response) => {
787
+ const dashboardId = response.body.id;
788
+
789
+ cy.waitUntil(
790
+ () => {
791
+ return cy.request({
792
+ method: 'GET',
793
+ url: `/centreon/api/latest/configuration/dashboards/${dashboardId}`
794
+ }).then((getResponse) => {
795
+ return getResponse.body && getResponse.body.id === dashboardId;
796
+ });
797
+ },
798
+ { timeout: 10000 }
799
+ );
800
+
801
+ const formData = new FormData();
802
+
803
+ formData.append('panels[0][name]', widgetName);
804
+ formData.append('panels[0][widget_type]', widgetType);
805
+
806
+ formData.append('panels[0][layout][x]', '0');
807
+ formData.append('panels[0][layout][y]', '0');
808
+ formData.append('panels[0][layout][width]', '12');
809
+ formData.append('panels[0][layout][height]', '3');
810
+ formData.append('panels[0][layout][min_width]', '2');
811
+ formData.append('panels[0][layout][min_height]', '2');
812
+
813
+ formData.append('panels[0][widget_settings]', JSON.stringify(patchBody));
814
+
815
+ cy.request({
816
+ method: 'POST',
817
+ url: `/centreon/api/latest/configuration/dashboards/${dashboardId}`,
818
+ body: formData,
819
+ headers: {
820
+ 'Content-Type': 'multipart/form-data',
821
+ },
822
+ }).then((patchResponse) => {
823
+ console.log('Widget added successfully:', patchResponse);
824
+ });
825
+ });
826
+ });
827
+
828
+ interface ShareDashboardToUserProps {
829
+ dashboardName: string;
830
+ role: string;
831
+ userName: string;
832
+ }
833
+
834
+ interface ListingRequestResult {
835
+ body: {
836
+ result: Array<{
837
+ id: number;
838
+ }>;
839
+ };
840
+ }
841
+
842
+ type PatchDashboardBody = {
843
+ widget_settings: {
844
+ data: {
845
+ resources: Array<{
846
+ resourceType: string;
847
+ resources: Array<{
848
+ id: number;
849
+ name: string;
850
+ }>;
851
+ }>;
852
+ metrics: Array<{
853
+ criticalHighThreshold: number;
854
+ criticalLowThreshold: number;
855
+ id: number;
856
+ name: string;
857
+ unit: string;
858
+ warningHighThreshold: number;
859
+ warningLowThreshold: number;
860
+ }>;
861
+ };
862
+ options: {
863
+ timeperiod: {
864
+ start: any;
865
+ end: any;
866
+ timePeriodType: number;
867
+ };
868
+ threshold: {
869
+ enabled: boolean;
870
+ customCritical: any;
871
+ criticalType: string;
872
+ customWarning: any;
873
+ warningType: string;
874
+ };
875
+ refreshInterval: string;
876
+ curveType: string;
877
+ description: {
878
+ content: string;
879
+ enabled: boolean;
880
+ };
881
+ };
882
+ };
883
+ };
884
+
885
+ Cypress.Commands.add(
886
+ 'shareDashboardToUser',
887
+ ({ dashboardName, userName, role }: ShareDashboardToUserProps): void => {
888
+ Promise.all([
889
+ cy.request({
890
+ method: 'GET',
891
+ url: `/centreon/api/latest/configuration/users?search={"name":"${userName}"}`
892
+ }),
893
+ cy.request({
894
+ method: 'GET',
895
+ url: `/centreon/api/latest/configuration/dashboards?search={"name":"${dashboardName}"}`
896
+ })
897
+ ]).then(
898
+ ([retrievedUser, retrievedDashboard]: [
899
+ ListingRequestResult,
900
+ ListingRequestResult
901
+ ]) => {
902
+ const userId = retrievedUser.body.result[0].id;
903
+ const dashboardId = retrievedDashboard.body.result[0].id;
904
+
905
+ cy.request({
906
+ body: {
907
+ id: userId,
908
+ role: `${role}`
909
+ },
910
+ method: 'POST',
911
+ url: `/centreon/api/latest/configuration/dashboards/${dashboardId}/access_rights/contacts`
912
+ });
913
+ }
914
+ );
915
+ }
916
+ );
917
+
918
+ Cypress.Commands.add('getTimeFromHeader', (): Cypress.Chainable => {
919
+ return cy
920
+ .get('header div[data-cy="clock"]', { timeout: 20000 })
921
+ .should('be.visible')
922
+ .then(($time) => {
923
+ const headerTime = $time.children()[1].textContent;
924
+ if (headerTime?.match(/\d+:\d+/)) {
925
+ cy.log(`header time is : ${headerTime}`);
926
+
927
+ return cy.wrap(headerTime);
928
+ }
929
+
930
+ throw new Error(`header time is not displayed`);
931
+ });
932
+ });
933
+
934
+ Cypress.Commands.add('insertDashboardWithDoubleWidget', (dashboardBody, patchBody1, patchBody2, widgetName, widgetType) => {
935
+ cy.request({
936
+ body: { ...dashboardBody },
937
+ method: 'POST',
938
+ url: '/centreon/api/latest/configuration/dashboards'
939
+ }).then((response) => {
940
+ const dashboardId = response.body.id;
941
+
942
+ cy.waitUntil(
943
+ () => {
944
+ return cy.request({
945
+ method: 'GET',
946
+ url: `/centreon/api/latest/configuration/dashboards/${dashboardId}`
947
+ }).then((getResponse) => {
948
+ return getResponse.body && getResponse.body.id === dashboardId;
949
+ });
950
+ },
951
+ { timeout: 10000 }
952
+ );
953
+
954
+ const formData = new FormData();
955
+
956
+ // Panel 1
957
+ formData.append('panels[0][name]', widgetName);
958
+ formData.append('panels[0][widget_type]', widgetType);
959
+ formData.append('panels[0][layout][x]', '0');
960
+ formData.append('panels[0][layout][y]', '0');
961
+ formData.append('panels[0][layout][width]', '12');
962
+ formData.append('panels[0][layout][height]', '3');
963
+ formData.append('panels[0][layout][min_width]', '2');
964
+ formData.append('panels[0][layout][min_height]', '2');
965
+ formData.append('panels[0][widget_settings]', JSON.stringify(patchBody1));
966
+
967
+ // Panel 2
968
+ formData.append('panels[1][name]', widgetName);
969
+ formData.append('panels[1][widget_type]', widgetType);
970
+ formData.append('panels[1][layout][x]', '0');
971
+ formData.append('panels[1][layout][y]', '3');
972
+ formData.append('panels[1][layout][width]', '12');
973
+ formData.append('panels[1][layout][height]', '3');
974
+ formData.append('panels[1][layout][min_width]', '2');
975
+ formData.append('panels[1][layout][min_height]', '2');
976
+ formData.append('panels[1][widget_settings]', JSON.stringify(patchBody2));
977
+
978
+ // Log form data
979
+ const dataToLog = {};
980
+ formData.forEach((value, key) => {
981
+ dataToLog[key] = value;
982
+ });
983
+
984
+ console.log('FormData before POST:', JSON.stringify(dataToLog, null, 2));
985
+
986
+ cy.request({
987
+ method: 'POST',
988
+ url: `/centreon/api/latest/configuration/dashboards/${dashboardId}`,
989
+ body: formData,
990
+ headers: {
991
+ 'Content-Type': 'multipart/form-data',
992
+ },
993
+ }).then((patchResponse) => {
994
+ console.log('Widget added successfully:', patchResponse);
995
+ });
996
+ });
997
+ });
998
+
999
+ declare global {
1000
+ namespace Cypress {
1001
+ interface Chainable {
1002
+ clickSubRootMenuItem: (page: string) => Cypress.Chainable;
1003
+ copyFromContainer: (
1004
+ props: CopyFromContainerProps,
1005
+ options?: Partial<Cypress.ExecOptions>
1006
+ ) => Cypress.Chainable;
1007
+ copyToContainer: (
1008
+ props: CopyToContainerProps,
1009
+ options?: Partial<Cypress.ExecOptions>
1010
+ ) => Cypress.Chainable;
1011
+ copyWebContainerLogs: (props: CopyWebContainerLogsProps) => Cypress.Chainable;
1012
+ createDirectory: (directoryPath: string) => Cypress.Chainable;
1013
+ ensureUserTokenApiV1: () => Cypress.Chainable;
1014
+ execInContainer: (
1015
+ props: ExecInContainerProps,
1016
+ options?: ExecInContainerOptions
1017
+ ) => Cypress.Chainable;
1018
+ getByLabel: ({
1019
+ patternType,
1020
+ tag,
1021
+ label
1022
+ }: GetByLabelProps) => Cypress.Chainable;
1023
+ getByTestId: ({
1024
+ patternType,
1025
+ tag,
1026
+ testId
1027
+ }: GetByTestIdProps) => Cypress.Chainable;
1028
+ getContainerId: (containerName: string) => Cypress.Chainable;
1029
+ getContainerIpAddress: (containerName: string) => Cypress.Chainable;
1030
+ getContainersLogs: () => Cypress.Chainable;
1031
+ getContainerMappedPort: (containerName: string, containerPort: number) => Cypress.Chainable;
1032
+ getIframeBody: (iframeSelector?: string) => Cypress.Chainable;
1033
+ getLogDirectory: () => Cypress.Chainable;
1034
+ getTimeFromHeader: () => Cypress.Chainable;
1035
+ getWebVersion: () => Cypress.Chainable;
1036
+ hoverRootMenuItem: (rootItemNumber: number) => Cypress.Chainable;
1037
+ insertDashboard: (dashboard: Dashboard) => Cypress.Chainable;
1038
+ insertDashboardList: (fixtureFile: string) => Cypress.Chainable;
1039
+ insertDashboardWithWidget: (
1040
+ dashboard: Dashboard,
1041
+ patchBody: Record<string, any>,
1042
+ widgetName:string,
1043
+ widgetType:string
1044
+ ) => Cypress.Chainable;
1045
+ insertDashboardWithDoubleWidget: (
1046
+ dashboard: Dashboard,
1047
+ patchBody1: Record<string, any>,
1048
+ patchBody2: Record<string, any>,
1049
+ widgetName: string,
1050
+ widgetType: string
1051
+ ) => Cypress.Chainable;
1052
+ loginAsAdminViaApiV2: () => Cypress.Chainable;
1053
+ loginByTypeOfUser: ({
1054
+ jsonName,
1055
+ loginViaApi
1056
+ }: LoginByTypeOfUserProps) => Cypress.Chainable;
1057
+ logout: () => void;
1058
+ logoutViaAPI: (props?: LogoutViaAPIProps) => Cypress.Chainable;
1059
+ moveSortableElement: (direction: string) => Cypress.Chainable;
1060
+ navigateTo: ({
1061
+ page,
1062
+ rootItemNumber,
1063
+ subMenu
1064
+ }: NavigateToProps) => Cypress.Chainable;
1065
+ requestOnDatabase: ({
1066
+ database,
1067
+ query,
1068
+ params
1069
+ }: RequestOnDatabaseProps) => Cypress.Chainable;
1070
+ setUserTokenApiV1: ({
1071
+ login,
1072
+ password
1073
+ }?: SetUserTokenApiV1Props) => Cypress.Chainable;
1074
+ shareDashboardToUser: ({
1075
+ dashboardName,
1076
+ userName,
1077
+ role
1078
+ }: ShareDashboardToUserProps) => Cypress.Chainable;
1079
+ startContainer: ({
1080
+ command,
1081
+ name,
1082
+ image,
1083
+ portBindings
1084
+ }: StartContainerProps) => Cypress.Chainable;
1085
+ startContainers: ({
1086
+ composeFile,
1087
+ databaseImage,
1088
+ moduleName,
1089
+ openidImage,
1090
+ profiles,
1091
+ useSlim,
1092
+ webOs,
1093
+ webVersion
1094
+ }?: StartContainersProps) => Cypress.Chainable;
1095
+ stopContainer: ({ name }: StopContainerProps) => Cypress.Chainable;
1096
+ stopContainers: () => Cypress.Chainable;
1097
+ visitEmptyPage: () => Cypress.Chainable;
1098
+ waitForElementInIframe: (
1099
+ iframeSelector: string,
1100
+ elementSelector: string
1101
+ ) => Cypress.Chainable;
1102
+ waitForElementToBeVisible(
1103
+ selector: string,
1104
+ timeout?: number,
1105
+ interval?: number
1106
+ ): Cypress.Chainable;
1107
+ }
1108
+ }
1109
+ }
1110
+
1111
+ export {};