-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-generation-page.ts
More file actions
1245 lines (1120 loc) · 43.8 KB
/
example-generation-page.ts
File metadata and controls
1245 lines (1120 loc) · 43.8 KB
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { OpenAPISpecTabPage } from "./openapi-spec-tab-page";
import {
Locator,
expect,
type TestInfo,
Page,
type Frame,
test,
FrameLocator,
} from "@playwright/test";
import { takeAndAttachScreenshot } from "../utils/screenshotUtils";
import { BasePage } from "./base-page";
import { Edit } from "../utils/types/json-edit.types";
import { SpecEditorPage } from "./spec-editor-page";
export class ExampleGenerationPage extends BasePage {
readonly openApiTabPage: OpenAPISpecTabPage;
protected readonly specTree: Locator;
private readonly generateExamplesBtn: Locator;
private readonly validExamplesTable: Locator;
private readonly invalidExamplesTable: Locator;
private readonly downloadExamplesBtn: Locator;
private readonly exampleDiv: Locator;
private readonly examplesIframe: Locator;
private readonly selectAllCheckboxSelector: string;
private readonly bulkDeleteBtnSelector: string;
private readonly bulkGenerateBtnSelector: string;
private readonly bulkValidateBtnSelector: string;
private readonly bulkFixBtnSelector: string;
private readonly inlineBtnSelector: string;
private readonly specSection: Locator;
private readonly specEditorSection: Locator;
private readonly specTabLocator: Locator;
private readonly specEditorHelper: SpecEditorPage;
constructor(page: Page, testInfo: TestInfo, eyes: any, specName: string) {
super(page, testInfo, eyes, specName);
this.specTree = page.locator("#spec-tree");
this.specSection = page.locator(
`xpath=//div[contains(@id,"${specName}") and @data-mode="example"]`,
);
this.specEditorSection = page.locator(
`xpath=//div[contains(@id,"${specName}") and @data-mode="spec"]`,
);
this.specTabLocator = page.locator('li.tab[data-type="spec"]').first();
this.generateExamplesBtn = this.specSection.locator(
`xpath=.//p[contains(text(),"Generate valid examples")]`,
);
this.exampleDiv = this.specSection.locator(`div.example`);
this.examplesIframe = this.exampleDiv.locator(
"iframe[data-examples-server-base]",
);
this.validExamplesTable = this.specSection.locator("#valid-examples-table");
this.invalidExamplesTable = this.specSection.locator(
"#invalid-examples-table",
);
this.downloadExamplesBtn = this.specSection.locator(
"button#download-examples",
);
this.openApiTabPage = new OpenAPISpecTabPage(this);
this.selectAllCheckboxSelector = "input#select-all";
this.bulkDeleteBtnSelector = "button#bulk-delete";
this.bulkGenerateBtnSelector = "button#bulk-generate";
this.bulkValidateBtnSelector = "button#bulk-validate";
this.inlineBtnSelector = "button#import";
this.bulkFixBtnSelector = "button#bulk-fix";
this.specEditorHelper = new SpecEditorPage(page);
}
private async openExampleGenerationTab() {
console.log("Opening Example Generation tab");
return this.openApiTabPage.openExampleGenerationTab();
}
private async clickGenerateButton(
endpoint: string,
responseCode: number,
withVisualValidation = true,
) {
// Use XPath inside the iframe to find the visible Generate button for the correct endpoint row
const iframe = await this.waitForExamplesIFrame();
const xpath = `//tr[@data-raw-path="/${endpoint}" and .//td[@class='response-cell']/p[text()="${responseCode}"]]//button[(@aria-label="Generate" or @aria-label="Generate More") and not(contains(@class, 'hidden')) and not(contains(@style, 'display: none'))]`;
const generateBtns = iframe.locator(xpath);
// Wait for at least one button to exist before checking visibility
const count = await generateBtns.count();
if (count === 0) {
await this.printDebugInfoForAvailableEndpoints(
iframe,
endpoint,
responseCode,
);
throw new Error(
`No generate button found for endpoint: ${endpoint}, responseCode: ${responseCode}`,
);
}
const btn = generateBtns.first();
await expect(btn).toBeVisible({ timeout: 4000 });
await btn.scrollIntoViewIfNeeded();
await btn.click();
await iframe.waitForSelector(`text=Example Generated`, {
timeout: 5000,
});
await takeAndAttachScreenshot(
this.page,
`clicked-generate-${endpoint}-${responseCode}`,
withVisualValidation ? this.eyes : undefined,
);
await this.verifyTitleAndCloseDialog("Example Generated");
}
private async printDebugInfoForAvailableEndpoints(
iframe: import("@playwright/test").Frame,
endpoint: string,
responseCode: number,
) {
const allRows = await iframe.locator("//tr[@data-raw-path]").all();
const debugRows = [];
for (const row of allRows) {
const rawPath = await row.getAttribute("data-raw-path");
// Find all response codes in this row
const responseCells = await row.locator("td.response-cell p").all();
const codes = [];
for (const cell of responseCells) {
const text = (await cell.textContent())?.trim();
if (text) codes.push(text);
}
debugRows.push({ rawPath, codes });
}
console.error(
`No generate button found for endpoint: ${endpoint}, responseCode: ${responseCode}`,
);
console.error(
"Available rows (data-raw-path and response codes):",
JSON.stringify(debugRows, null, 2),
);
}
private async verifyGenerateButtonNotVisible(
endpoint: string,
responseCode: number,
) {
const rowLocator = this.page.locator(`tr[data-raw-path="/${endpoint}"]`);
const responseCell = rowLocator
.locator("td.response-cell")
.filter({ has: this.page.getByText(`${responseCode}`) });
const generateBtn = responseCell.locator(
'button[aria-label="Generate More"]',
);
await expect(generateBtn).toBeHidden({ timeout: 4000 });
}
private async verifyExampleFileNameVisible(
endpoint: string,
responseCode: number,
withVisualValidation = true,
) {
const iframe = await this.waitForExamplesIFrame();
const rowXpath = `//tr[@data-raw-path="/${endpoint}" and .//td[@class='response-cell']/p[text()="${responseCode}"]]`;
const endpointPrefix = endpoint.replace(/\/(\([^/]+\))/g, "");
const fileNameSpanXpath = `${rowXpath}//td/span[contains(text(), '${endpointPrefix}') and contains(text(), '${responseCode}')]`;
console.log(
`\t\tLooking for example file name span with XPath: ${fileNameSpanXpath}`,
);
const fileNameSpan = iframe.locator(fileNameSpanXpath);
await expect(fileNameSpan).toBeVisible({ timeout: 4000 });
const fileNameText = (await fileNameSpan.textContent())?.trim();
expect(fileNameText).toContain(endpointPrefix);
expect(fileNameText).toContain(String(responseCode));
await takeAndAttachScreenshot(
this.page,
`example-file-name-visible-${endpoint}-${responseCode}`,
withVisualValidation ? this.eyes : undefined,
);
}
private async verifyValidateButtonVisible(
endpoint: string,
responseCode: number,
withVisualValidation = true,
) {
const iframe = await this.waitForExamplesIFrame();
await takeAndAttachScreenshot(
this.page,
`validate-button-visible-${endpoint}-${responseCode}`,
withVisualValidation ? this.eyes : undefined,
);
const xpath = `//tr[@data-raw-path="/${endpoint}" and .//td[@class='response-cell']/p[text()="${responseCode}"]]//button[@aria-label="Validate"]`;
const validateBtn = iframe.locator(xpath);
await expect(validateBtn).toBeVisible({ timeout: 4000 });
}
private async clickViewDetails(
endpoint: string,
responseCode: number,
withVisualValidation = true,
) {
const iframe = await this.waitForExamplesIFrame();
const xpath = `//tr[@data-raw-path="/${endpoint}" and .//td[@class='response-cell']/p[text()="${responseCode}"]]//span[contains(text(), 'View Details')]`;
const viewDetailsSpan = iframe.locator(xpath);
await expect(viewDetailsSpan).toBeVisible({ timeout: 4000 });
await viewDetailsSpan.click();
await this.page.waitForTimeout(2000);
await takeAndAttachScreenshot(
this.page,
`view-details-${endpoint}-${responseCode}`,
withVisualValidation ? this.eyes : undefined,
);
}
private async clickGoBack(endpoint: string, responseCode: number) {
const iframe = await this.waitForExamplesIFrame();
const goBackBtn = iframe.getByRole("button", { name: /Go Back|← Go Back/ });
await expect(goBackBtn).toBeVisible({ timeout: 4000 });
await expect(goBackBtn).toBeEnabled({ timeout: 4000 });
await goBackBtn.click();
await takeAndAttachScreenshot(
this.page,
`go-back-${endpoint}-${responseCode}`,
);
}
private async clickValidateButton(
endpoint: string,
responseCode: number,
withVisualValidation = true,
) {
const iframe = await this.waitForExamplesIFrame();
const xpath = `//tr[@data-raw-path="/${endpoint}" and .//td[@class='response-cell']/p[text()="${responseCode}"]]//button[@aria-label="Validate"]`;
const validateBtn = iframe.locator(xpath);
await expect(validateBtn).toBeVisible({ timeout: 4000 });
await validateBtn.click();
await takeAndAttachScreenshot(
this.page,
`clicked-validate-${endpoint}-${responseCode}`,
withVisualValidation ? this.eyes : undefined,
);
await this.verifyTitleAndCloseDialog("Valid Example");
}
private async verifyTitleAndCloseDialog(expectedTitle: string) {
console.log(`\tVerifying dialog with expected text: '${expectedTitle}'`);
await takeAndAttachScreenshot(
this.page,
`before-closing-dialog-${expectedTitle.replace(/\s+/g, "-").toLowerCase()}`,
);
const { alert } = await this.getAlertContainerFrameAndLocator();
await expect(alert).toBeAttached({ timeout: 15000 });
const title = await this.getDialogTitle(alert);
const message = await this.getDialogMessage(alert);
expect.soft(title).toContain(expectedTitle);
await alert.locator("button").click();
console.log(
`\t\tClicked close button on dialog with title: '${expectedTitle}' Vs Actual: '${title}'`,
);
await this.page.waitForTimeout(1000);
await takeAndAttachScreenshot(
this.page,
`after-closing-dialog-${expectedTitle.replace(/\s+/g, "-").toLowerCase()}`,
);
await expect(alert).toBeHidden();
}
private async getAlertContainerFrameAndLocator(): Promise<{
frame: import("@playwright/test").Frame;
alert: Locator;
}> {
const iframeHandle = await this.examplesIframe.elementHandle();
const frame = await iframeHandle?.contentFrame();
if (!frame) {
throw new Error(
"Frame is null or undefined in getAlertContainerFrameAndLocator",
);
}
const alert = frame.locator("#alert-container");
return { frame, alert };
}
private async getDialogTitle(alert: Locator): Promise<string> {
// Assumes the first <p> or <pre> is the title
const dialogTitle = await alert.locator("p, pre").first().innerText();
console.log("\t\tActual dialog title:", dialogTitle);
return dialogTitle;
}
private async getDialogMessage(alert: Locator): Promise<string> {
// Assumes the second <p> or <pre> is the message, if present
const elements = await alert.locator("p, pre").all();
let dialogMessage = "";
if (elements.length > 1) {
dialogMessage = await elements[1].innerText();
} else if (elements.length === 1) {
dialogMessage = await elements[0].innerText();
}
console.log("\t\tActual dialog message:", dialogMessage);
return dialogMessage;
}
private async saveAndValidate(withVisualValidation = true) {
await test.step(`Click 'Save & Validate' button`, async () => {
const iframe = await this.waitForExamplesIFrame();
const saveValidateBtn = iframe.locator("button#bulk-validate");
await this.page.waitForTimeout(1000);
await expect(saveValidateBtn).toBeVisible({ timeout: 4000 });
await expect(saveValidateBtn).toBeEnabled({ timeout: 4000 });
await saveValidateBtn.click();
await this.page.waitForTimeout(1000);
await takeAndAttachScreenshot(
this.page,
"clicked-save-and-validate",
withVisualValidation ? this.eyes : undefined,
);
});
}
async deleteGeneratedExamples() {
await test.step(`Delete all generated examples if present`, async () => {
console.log("Attempting to delete generated examples if present");
const iframe = await this.waitForExamplesIFrame();
await this.selectAll(iframe);
const bulkDeleteBtn = iframe.locator(this.bulkDeleteBtnSelector);
let deleteClicked = false;
if (await bulkDeleteBtn.isVisible({ timeout: 1000 }).catch(() => false)) {
await takeAndAttachScreenshot(this.page, `click-bulk-delete`);
await bulkDeleteBtn.click();
deleteClicked = true;
console.log("\tbulk-delete button clicked");
await takeAndAttachScreenshot(this.page, `clicked-bulk-delete`);
}
if (deleteClicked) {
await this.verifyTitleAndCloseDialog("Delete Examples Complete");
} else {
console.log("No examples to delete");
await this.uncheckSelectAll(iframe); // Uncheck select-all if we had checked it but there were no examples to delete
}
await takeAndAttachScreenshot(
this.page,
`examples-deleted-or-none-to-delete`,
);
});
}
private async selectAll(iframe: import("@playwright/test").Frame) {
const selectAll = iframe.locator(this.selectAllCheckboxSelector);
await selectAll.waitFor({ timeout: 3000 });
const checkboxes = await selectAll.all();
console.log(`\tselect-all checkbox found, count: ${checkboxes.length}`);
let allChecked = true;
for (let i = 0; i < checkboxes.length; i++) {
let checked = await checkboxes[i].isChecked();
let attempts = 0;
while (!checked && attempts < 3) {
await checkboxes[i].click({ force: true });
await this.page.waitForTimeout(200 * (attempts + 1)); // Wait a bit longer after each attempt
checked = await checkboxes[i].isChecked();
console.log(
`\tselect-all checkbox[${i}] checked after click attempt ${attempts + 1}: ${checked}`,
);
attempts++;
}
if (!checked) {
allChecked = false;
console.log(
`\tselect-all checkbox[${i}] could not be checked after 3 attempts`,
);
}
}
// Log final checked state for all checkboxes
for (let i = 0; i < checkboxes.length; i++) {
const checkedState = await checkboxes[i].isChecked();
console.log(`\tselect-all checkbox[${i}] final checked: ${checkedState}`);
}
if (!allChecked) {
throw new Error(
"selectAll: One or more checkboxes could not be checked after 3 attempts",
);
}
// Also check that at least one is checked for safety
if (checkboxes.length === 0) {
throw new Error(
"selectAll: No checkboxes found for selector 'input#select-all'",
);
}
await takeAndAttachScreenshot(this.page, `select-all-checked`);
}
private async uncheckSelectAll(iframe: import("@playwright/test").Frame) {
const selectAll = iframe.locator(this.selectAllCheckboxSelector);
await selectAll.waitFor({ timeout: 3000 });
console.log("\tuncheck select-all checkbox found");
if (await selectAll.isChecked()) {
await selectAll.click({ force: true });
await expect(selectAll).not.toBeChecked({ timeout: 2000 });
console.log("\tselect-all checkbox unchecked");
await takeAndAttachScreenshot(this.page, `select-all-unchecked`);
}
}
private async waitForExamplesIFrame() {
await this.examplesIframe.waitFor({ state: "attached", timeout: 10000 });
const iframeElement = await this.examplesIframe.elementHandle();
if (!iframeElement) {
throw new Error("Could not find the iframe element at index 1");
}
const frame = await iframeElement.contentFrame();
if (!frame) {
throw new Error("Could not get contentFrame from iframe element");
}
console.log("\tSuccessfully got the examples iframe");
return frame;
}
async validateAllExamples() {
await test.step(`Validate all generated examples`, async () => {
console.log(`Validating all generated examples`);
const iframe = await this.waitForExamplesIFrame();
await this.selectAll(iframe);
await this.clickBulkValidateButton();
await this.waitForProcessingToComplete(iframe);
await this.verifyTitleAndCloseDialog("Example Validations Complete");
await takeAndAttachScreenshot(
this.page,
`validate-examples-for-all-paths`,
this.eyes,
);
});
}
async generateAllExamples() {
await test.step(`Generate example and validate for all paths`, async () => {
console.log(`Generating and validating example for all paths`);
const iframe = await this.waitForExamplesIFrame();
await this.selectAll(iframe);
await this.clickBulkGenerateButton();
await this.waitForProcessingToComplete(iframe);
await takeAndAttachScreenshot(
this.page,
`generate-examples-for-all-paths`,
this.eyes,
);
});
}
private async waitForProcessingToComplete(
iframe: import("@playwright/test").Frame,
) {
console.log(`\t\tWaiting for processing to complete...`);
const processingBtn = iframe.locator("button#bulk-generate", {
hasText: "Processing",
});
// wait for 5 seconds for the processing button to appear in case it takes some time for the generation to start, but if it doesn't appear within that time, we proceed to check for completion to avoid unnecessary test failure
await processingBtn
.waitFor({ state: "visible", timeout: 5000 })
.catch(() => {
console.log(
"\t\tProcessing button did not appear within 5 seconds, proceeding to check for generation completion",
);
});
await expect(processingBtn).toBeHidden({ timeout: 60000 });
}
async getNumberOfPathMethodsAndResponses(): Promise<number> {
const iframe = await this.waitForExamplesIFrame();
const exampleRows = await iframe.locator("tr[data-raw-path]").all();
console.log(
`\tTotal number of path-method-response combinations: ${exampleRows.length}`,
);
return exampleRows.length;
}
async getNumberOfGenerateButtons(): Promise<number> {
const iframe = await this.waitForExamplesIFrame();
const generateButtons = await iframe
.locator('button[aria-label="Generate"]')
.all();
console.log(
`\tNumber of Generate buttons available: ${generateButtons.length}`,
);
return generateButtons.length;
}
async getNumberOfValidateButtons(): Promise<number> {
const iframe = await this.waitForExamplesIFrame();
const validateButtons = await iframe
.locator('button[aria-label="Validate"]')
.all();
console.log(
`\tNumber of Validate buttons available: ${validateButtons.length}`,
);
return validateButtons.length;
}
async getNumberOfExamplesValidated(): Promise<number> {
const iframe = await this.waitForExamplesIFrame();
const exampleRows = await iframe.locator("tr[data-valid=success]").all();
console.log(
`\tTotal endpoints with generated examples: ${exampleRows.length}`,
);
return exampleRows.length;
}
async getNumberOfExamplesGenerated(): Promise<number> {
const iframe = await this.waitForExamplesIFrame();
const exampleRows = await iframe
.locator("tr[data-example-relative-path]")
.all();
console.log(
`\tTotal endpoints with generated examples: ${exampleRows.length}`,
);
return exampleRows.length;
}
private async clickBulkGenerateButton() {
const iframe = await this.waitForExamplesIFrame();
const bulkGenerateBtn = iframe.locator(this.bulkGenerateBtnSelector);
await bulkGenerateBtn.waitFor({ state: "visible", timeout: 4000 });
await expect(bulkGenerateBtn).toBeVisible({ timeout: 4000 });
await expect(bulkGenerateBtn).toBeEnabled({ timeout: 4000 });
await bulkGenerateBtn.click();
await takeAndAttachScreenshot(this.page, "clicked-generate");
}
private async clickBulkValidateButton() {
const iframe = await this.waitForExamplesIFrame();
const bulkValidateBtn = iframe.locator(this.bulkValidateBtnSelector);
await bulkValidateBtn.waitFor({ state: "visible", timeout: 4000 });
await expect(bulkValidateBtn).toBeVisible({ timeout: 4000 });
await expect(bulkValidateBtn).toBeEnabled({ timeout: 4000 });
await bulkValidateBtn.click();
await takeAndAttachScreenshot(this.page, "clicked-validate");
}
async inlineExamples() {
await test.step(`Inline generated examples into the spec file`, async () => {
console.log(`Inlining examples into the spec file`);
await takeAndAttachScreenshot(this.page, `before-inline`);
const iframe = await this.waitForExamplesIFrame();
const inlineBtn = iframe.locator(this.inlineBtnSelector);
await inlineBtn.waitFor({ state: "visible", timeout: 4000 });
await expect(inlineBtn).toBeVisible({ timeout: 4000 });
await expect(inlineBtn).toBeEnabled({ timeout: 4000 });
await inlineBtn.click();
await takeAndAttachScreenshot(
this.page,
`all-examples-inlined`,
this.eyes,
);
});
}
async getDialogTitleAndMessage(): Promise<[string, string]> {
return await test.step(`Get dialog title and message`, async () => {
console.log(`\tGetting dialog title and message`);
const { alert } = await this.getAlertContainerFrameAndLocator();
await takeAndAttachScreenshot(this.page, `dialog-title-and-message`);
const title = await this.getDialogTitle(alert);
const message = await this.getDialogMessage(alert);
return [title, message];
});
}
async closeInlineSuccessDialog(expectedTitle: string) {
await test.step(`Close inline success dialog with title: '${expectedTitle}'`, async () => {
console.log(
`Closing inline success dialog with expected title: '${expectedTitle}'`,
);
const iframe = await this.waitForExamplesIFrame();
await this.verifyTitleAndCloseDialog(expectedTitle);
});
}
async generateAndValidateForPaths(
endpoints: { path: string; responseCodes: number[] }[],
) {
let isFirstIteration = true;
for (const endpoint of endpoints) {
for (const code of endpoint.responseCodes) {
const withVisualValidation = isFirstIteration;
isFirstIteration = false;
await test.step(`Generate example and validate for path: '/${endpoint.path}' and response code: '${code}'`, async () => {
console.log(
`Generating and validating example for path: '/${endpoint.path}' and response code: '${code}'`,
);
await this.generateExample(endpoint.path, code, withVisualValidation);
await this.verifyGeneratedExample(
endpoint.path,
code,
withVisualValidation,
);
await this.viewExampleDetailsAndReturn(
endpoint.path,
code,
withVisualValidation,
);
await this.validateExample(endpoint.path, code, withVisualValidation);
});
}
}
}
async generateExampleAndViewDetailsForPath(path: string, code: number) {
await test.step(`Generate example and view details for path: '/${path}' and response code: '${code}'`, async () => {
console.log(
`Generating example and viewing details for path: '/${path}' and response code: '${code}'`,
);
await this.generateExample(path, code);
await this.clickViewDetails(path, code);
});
}
async closeInvalidExampleDialog(dialogTitle: string) {
await test.step(`Close invalid example dialog with title: '${dialogTitle}'`, async () => {
console.log(
`Closing invalid example dialog with title: '${dialogTitle}'`,
);
await this.verifyTitleAndCloseDialog(`${dialogTitle}`);
});
}
async closeExamplesGenerationCompletedDialog(dialogTitle: string) {
await test.step(`Close examples generated dialog with title: '${dialogTitle}'`, async () => {
console.log(
`Closing examples generated dialog with title: '${dialogTitle}'`,
);
await this.verifyTitleAndCloseDialog(`${dialogTitle}`);
});
}
async closeFixedExampleDialog(dialogTitle: string) {
await test.step(`Close fixed example dialog with title: '${dialogTitle}'`, async () => {
console.log(`Closing fixed example dialog with title: '${dialogTitle}'`);
await this.verifyTitleAndCloseDialog(`${dialogTitle}`);
});
}
async closeValidExampleDialog(dialogTitle: string) {
await test.step(`Close valid example dialog with title: '${dialogTitle}'`, async () => {
console.log(`Closing valid example dialog with title: '${dialogTitle}'`);
await this.verifyTitleAndCloseDialog(`${dialogTitle}`);
});
}
async fixExampleWithAutoFix() {
await test.step(`Fix example with Auto-Fix`, async () => {
console.log(`Fixing example with Auto-Fix`);
const iframe = await this.waitForExamplesIFrame();
const autoFixBtn = iframe.locator(this.bulkFixBtnSelector);
await autoFixBtn.waitFor({ state: "attached", timeout: 4000 });
const isVisible = await autoFixBtn.isVisible();
const isEnabled = await autoFixBtn.isEnabled();
if (!isVisible || !isEnabled) {
console.warn(
"Auto-Fix button is not enabled/visible, skipping auto-fix step.",
);
return;
}
await autoFixBtn.click();
await takeAndAttachScreenshot(this.page, `clicked-auto-fix`, this.eyes);
await this.verifyTitleAndCloseDialog("Fixed Example");
});
}
async getDetailsOfErrorsInExample(): Promise<[number, string]> {
return await test.step(`Get details of errors in example`, async () => {
console.log(`Getting details of errors in example`);
const iframe = await this.waitForExamplesIFrame();
// Click the details div to expand if not already expanded
const detailsDiv = iframe.locator("div.details");
const classAttr = await detailsDiv.getAttribute("class");
if (!classAttr || !classAttr.includes("expanded")) {
await detailsDiv.click();
await expect(detailsDiv).toHaveClass(/expanded/, { timeout: 3000 });
}
const expandedDiv = iframe.locator("div.details.expanded");
await expect(expandedDiv).toBeVisible({ timeout: 5000 });
// The summary line is in the .dropdown > p
const summaryP = expandedDiv.locator(".dropdown > p");
const summaryText = await summaryP.textContent();
let errorCount = 0;
if (summaryText) {
const match = summaryText.match(/Example has (\d+) Error/);
if (match) {
errorCount = parseInt(match[1], 10);
}
}
// The error message blob is in the <pre> tag
const pre = expandedDiv.locator("pre");
let errorBlob = "";
if ((await pre.count()) > 0) {
errorBlob = (await pre.first().textContent()) || "";
}
return [errorCount, errorBlob];
});
}
async getCollapsedErrorSummaryCount(): Promise<number> {
return await test.step(`Get collapsed error summary count`, async () => {
console.log(`Getting collapsed error summary count`);
const iframe = await this.waitForExamplesIFrame();
const detailsDiv = iframe.locator("div.details");
await expect(detailsDiv).toBeVisible({ timeout: 5000 });
const classAttr = await detailsDiv.getAttribute("class");
if (classAttr?.includes("expanded")) {
console.log(`\tDetails div is already expanded — collapsing it first`);
await detailsDiv.click();
await expect(detailsDiv).not.toHaveClass(/expanded/, { timeout: 3000 });
}
const summaryP = detailsDiv.locator(".dropdown > p");
const summaryText = await summaryP.textContent();
console.log(`\tCollapsed summary text: "${summaryText}"`);
let errorCount = 0;
if (summaryText) {
const match = summaryText.match(/Example has (\d+) Error/);
if (match) {
errorCount = parseInt(match[1], 10);
}
}
await takeAndAttachScreenshot(
this.page,
`collapsed-error-summary-count-${errorCount}`,
);
return errorCount;
});
}
async getVisibleErrorBlockCount(): Promise<number> {
return await test.step(`Get visible error block count after expanding`, async () => {
console.log(`Getting visible error block count in expanded details`);
const iframe = await this.waitForExamplesIFrame();
const detailsDiv = iframe.locator("div.details");
const classAttr = await detailsDiv.getAttribute("class");
if (!classAttr?.includes("expanded")) {
await detailsDiv.click();
await expect(detailsDiv).toHaveClass(/expanded/, { timeout: 3000 });
}
const expandedDiv = iframe.locator("div.details.expanded");
await expect(expandedDiv).toBeVisible({ timeout: 5000 });
const pre = expandedDiv.locator("pre");
let preText = "";
if ((await pre.count()) > 0) {
preText = (await pre.first().textContent()) || "";
}
const errorBlocks = preText
.split("\n")
.filter((line) => line.trim().startsWith(">>"));
const count = errorBlocks.length;
console.log(`\tVisible error block count: ${count}`);
await takeAndAttachScreenshot(
this.page,
`expanded-error-block-count-${count}`,
);
return count;
});
}
async saveEditedExample(expectedDialogTitle: string) {
await test.step(`Save edited example`, async () => {
console.log(`Saving edited example`);
await this.saveAndValidate();
await this.verifyTitleAndCloseDialog(expectedDialogTitle);
});
}
async editExample(edits: Edit[]) {
await test.step(`Edit and save example with edits`, async () => {
console.log(`Editing example`);
const frame = await this.waitForExamplesIFrame();
const lines = frame.locator("#example-pre .cm-line");
await expect(lines.first()).toBeVisible({ timeout: 15000 });
// create a for loop to process each edit one by one
for (const edit of edits) {
let target = lines;
const pattern = edit.current;
console.log(
`\tProcessing edit #${edits.indexOf(edit) + 1}: '${JSON.stringify(edit.current)}' to '${edit.changeTo}' with pattern mode: '${pattern.mode}'`,
);
if (pattern.mode === "exact") {
target = target.filter({ hasText: pattern.value });
} else if (pattern.mode === "keyOnly") {
const re = new RegExp(`"${pattern.key}"`);
target = target.filter({ hasText: re });
} else if (pattern.mode === "keyAndAnyNumber") {
const re = new RegExp(`"${pattern.key}"\\s*:\\s*\\d+`);
target = target.filter({ hasText: re });
}
const line = target.first();
console.log(`\tLocated line for edit #${edits.indexOf(edit) + 1}`);
console.log(`\tOriginal line text: '${await line.innerText()}'`);
await expect(line).toBeVisible({ timeout: 10000 });
await line.scrollIntoViewIfNeeded();
await line.click();
// In CodeMirror, Home lands at first non-whitespace for indented lines.
// Replacing from there keeps existing indentation unchanged.
await this.page.keyboard.press("Home");
await this.page.keyboard.press("Shift+End");
await this.page.keyboard.type(edit.changeTo);
takeAndAttachScreenshot(
this.page,
`edited-example-line-${edits.indexOf(edit) + 1}`,
);
console.log(
`\tEdited example line: '${JSON.stringify(edit.current)}' to '${edit.changeTo}'`,
);
}
console.log(`All edits processed`);
});
}
private async generateExample(
path: string,
code: number,
withVisualValidation = true,
) {
await test.step(`Generate example`, async () => {
console.log(
`\tGenerating example for path: '/${path}' and response code: '${code}'`,
);
await this.clickGenerateButton(path, code, withVisualValidation);
});
}
private async validateExample(
path: string,
code: number,
withVisualValidation = true,
) {
await test.step(`Validate generated example`, async () => {
console.log(
`\tValidating example for path: '/${path}' and response code: '${code}'`,
);
await this.clickValidateButton(path, code, withVisualValidation);
});
}
private async viewExampleDetailsAndReturn(
path: string,
code: number,
withVisualValidation = true,
) {
await test.step(`View details and go back`, async () => {
console.log(
`\tViewing details for example of path: '/${path}' and response code: '${code}'`,
);
await this.clickViewDetails(path, code, withVisualValidation);
await this.saveAndValidate(withVisualValidation);
await this.verifyTitleAndCloseDialog("Valid Example");
await this.clickGoBack(path, code);
});
}
private async verifyGeneratedExample(
path: string,
code: number,
withVisualValidation = true,
) {
await test.step(`Verify example is generated`, async () => {
console.log(
`\tVerifying generated example for path: '/${path}' and response code: '${code}'`,
);
await this.verifyGenerateButtonNotVisible(path, code);
await this.verifyExampleFileNameVisible(path, code, withVisualValidation);
await this.verifyValidateButtonVisible(path, code, withVisualValidation);
});
}
async openExampleGenerationTabForSpec(
testInfo: import("@playwright/test").TestInfo,
eyes: any,
specName: string,
) {
await test.step(`Go to Example Generation page for Service Spec: '${specName}'`, async () => {
console.log(
`Opening Example Generation page for Service Spec: '${specName}'`,
);
await this.gotoHome();
await this.sideBar.selectSpec(specName);
await this.openExampleGenerationTab();
});
}
async clickGenerateMoreButton(path: string, responseCode: number) {
await test.step(`Click Generate More for ${path} - ${responseCode}`, async () => {
const iframe = await this.waitForExamplesIFrame();
const generateMoreBtn = iframe.locator(
`//tr[@data-raw-path="/${path}" and .//td[@class='response-cell']/p[text()="${responseCode}"]]//button[@aria-label="Generate More"]`,
);
await expect(generateMoreBtn).toBeVisible({ timeout: 4000 });
await generateMoreBtn.click();
await this.page.waitForTimeout(1000);
await this.verifyTitleAndCloseDialog("Example Generated");
});
}
async getGeneratedExampleNames(): Promise<string[]> {
return await test.step(`Get generated example names`, async () => {
console.log(`Getting generated example names from Examples tab`);
const iframe = await this.waitForExamplesIFrame();
const exampleRows = await iframe
.locator("tr[data-example-relative-path]")
.all();
const exampleNames: string[] = [];
for (const row of exampleRows) {
const relativePath = await row.getAttribute(
"data-example-relative-path",
);
if (relativePath) {
const match = relativePath.match(/_examples\/(.+)\.json$/);
if (match) {
exampleNames.push(match[1]);
}
}
}
console.log(
`Found ${exampleNames.length} generated examples:`,
exampleNames,
);
await takeAndAttachScreenshot(this.page, `generated-example-names`);
return exampleNames;
});
}
async openSpecTabForCurrentSpec() {
await test.step(`Open Spec tab for current spec`, async () => {
console.log(`Opening Spec tab`);
await this.openApiTabPage.openSpecTab(this.specTabLocator);
await takeAndAttachScreenshot(this.page, `spec-tab-opened`);
});
}
async verifyInlinedExamplesInSpec(
expectedExampleNames: string[],
endpoint: string,
method: string,
responseCode: number,
) {
await test.step(`Verify inlined examples in spec file`, async () => {
if (method.toLowerCase() === "post") {
await this.verifyInlinedPostExamplesInSpec(
expectedExampleNames,
endpoint,
responseCode,
);
return;
}
const specContent = this.readSpecFile();
for (const name of expectedExampleNames) {
await this.validateExamplePresence(specContent, name);
}
await takeAndAttachScreenshot(
this.page,
`verified-inlined-examples-${endpoint}-${responseCode}`,
);
await this.showVisualEvidenceInEditor(
expectedExampleNames[0],
endpoint,
responseCode,
);
});
}