4
4
import com .microsoft .playwright .Page ;
5
5
import io .swaglabs .portal .qa .constants .WebPortalConstants ;
6
6
import io .swaglabs .portal .qa .exceptions .WebPageException ;
7
+ import io .swaglabs .portal .qa .listeners .WebTestListeners ;
7
8
import io .swaglabs .portal .qa .locators .Locators ;
8
9
import io .swaglabs .portal .qa .screenshotsmanager .ElementScreenshotStrategy ;
9
10
import io .swaglabs .portal .qa .screenshotsmanager .ScreenshotContext ;
11
+ import org .testng .ITestResult ;
12
+ import org .testng .Reporter ;
10
13
11
14
import java .util .Objects ;
15
+ import java .util .function .Consumer ;
12
16
13
17
public abstract class WebBasePage {
14
18
@@ -58,4 +62,36 @@ protected void takeElementScreenshot(Locator locator, String fileName) {
58
62
ScreenshotContext screenshotContext = new ScreenshotContext (new ElementScreenshotStrategy (locator ));
59
63
screenshotContext .captureScreenshot (basePage , ELEMENT_SCREENSHOT_FILE_LOCATION + fileName + WebPortalConstants .IMAGE_FORMAT );
60
64
}
65
+
66
+ protected void switchToNewTabAndRun (Page newTabPage , Consumer <WebBasePage > actionsInNewTab ) {
67
+ Page originalPage = this .basePage ;
68
+ Locators originalLocators = this .locators ;
69
+ try {
70
+ // Update to new tab context
71
+ this .basePage = newTabPage ;
72
+ this .locators = new Locators (newTabPage );
73
+ WebTestListeners .setPage (newTabPage );
74
+ actionsInNewTab .accept (this ); // Perform operations in new tab
75
+ } catch (Exception testException ) {
76
+ // Capture screenshot of the new tab before any cleanup
77
+ if (newTabPage != null && !newTabPage .isClosed ()) {
78
+ ITestResult currentTestResult = Reporter .getCurrentTestResult ();
79
+ if (currentTestResult != null ) {
80
+ currentTestResult .setStatus (ITestResult .FAILURE );
81
+ currentTestResult .setThrowable (testException );
82
+ WebTestListeners listeners = new WebTestListeners ();
83
+ listeners .onTestFailure (currentTestResult );
84
+ }
85
+ }
86
+ throw testException ; // Re-throw to maintain original behavior
87
+ } finally {
88
+ if (newTabPage != null && !newTabPage .isClosed ()) {
89
+ newTabPage .close (); // Always close the new tab
90
+ }
91
+ WebTestListeners .setPage (originalPage );
92
+ // Revert to the original page and locator
93
+ this .basePage = originalPage ;
94
+ this .locators = originalLocators ;
95
+ }
96
+ }
61
97
}
0 commit comments