Skip to content

Commit

Permalink
Optimize code and upgrade playwright
Browse files Browse the repository at this point in the history
  • Loading branch information
vothaian committed Oct 29, 2024
1 parent 12d2fcb commit f5ac40d
Show file tree
Hide file tree
Showing 18 changed files with 175 additions and 80 deletions.
23 changes: 13 additions & 10 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,23 @@

<groupId>com.anhtester</groupId>
<artifactId>PlaywrightJava</artifactId>
<version>1.45.0</version>
<version>1.48.0</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<log4j.version>2.24.1</log4j.version>
<slf4j.version>2.0.16</slf4j.version>
</properties>

<dependencies>
<!-- https://mvnrepository.com/artifact/com.microsoft.playwright/playwright -->
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.45.0</version>
<version>1.48.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.testng/testng -->
Expand All @@ -33,14 +36,14 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.13</version>
<version>${slf4j.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.13</version>
<version>${slf4j.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
Expand All @@ -61,7 +64,7 @@
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.16.1</version>
<version>2.17.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.github.stephenc.monte/monte-screen-recorder -->
Expand All @@ -75,14 +78,14 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.23.1</version>
<version>${log4j.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.23.1</version>
<version>${log4j.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.aventstack/extentreports -->
Expand All @@ -96,14 +99,14 @@
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-testng</artifactId>
<version>2.28.0</version>
<version>2.29.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.qameta.allure/allure-attachments -->
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-attachments</artifactId>
<version>2.28.0</version>
<version>2.29.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
Expand All @@ -125,7 +128,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.2.1-jre</version>
<version>33.3.1-jre</version>
</dependency>

</dependencies>
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/anhtester/constants/AppConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ public class AppConfig {
public static boolean SCREENSHOT_FAIL = Boolean.parseBoolean(PropertiesHelper.getValue("SCREENSHOT_FAIL"));
public static boolean SCREENSHOT_PASS = Boolean.parseBoolean(PropertiesHelper.getValue("SCREENSHOT_PASS"));
public static int TIMEOUT_STEP = Integer.parseInt(PropertiesHelper.getValue("TIMEOUT_STEP"));
public static boolean TRACE_VIEWER = Boolean.parseBoolean(PropertiesHelper.getValue("TRACE_VIEWER"));

}
66 changes: 66 additions & 0 deletions src/main/java/com/anhtester/helpers/SystemHelper.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package com.anhtester.helpers;

import java.io.File;
import java.text.Normalizer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

public class SystemHelper {
public static String getCurrentDir() {
Expand All @@ -13,4 +19,64 @@ public static String getOperatingSystem() {
// System.out.println("OS name: " + os);
return os;
}

public static String getDateTimeNow() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
return dateFormat.format(new Date());
}

public static String getDateTimeNowAndMakeSlug() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
return makeSlug(dateFormat.format(new Date()));
}

public static String makeSlug(String input) {
final Pattern NONLATIN = Pattern.compile("[^\\w-]");
final Pattern WHITESPACE = Pattern.compile("[\\s]");

if (input == null)
throw new IllegalArgumentException();

String noWhiteSpace = WHITESPACE.matcher(input).replaceAll("_");
String normalized = Normalizer.normalize(noWhiteSpace, Normalizer.Form.NFD);
String slug = NONLATIN.matcher(normalized).replaceAll("");
return slug.toLowerCase(Locale.ENGLISH);
}

/**
* Create folder empty
*
* @param path is the path to create the folder
*/
public static void createFolder(String path) {
// File is a class inside java.io package
File file = new File(path);

String result = null;

int lengthSum = path.length();
int lengthSub = path.substring(0, path.lastIndexOf('/')).length();

result = path.substring(lengthSub, lengthSum);

if (!file.exists()) {
file.mkdir(); // mkdir is used to create folder
System.out.println("Folder " + file.getName() + " created: " + path);
} else {
System.out.println("Folder already created");
}
}

/**
* @param str is value as type is String to be split based on condition
* @param valueSplit the character to split the string into an array of values
* @return array of string values after splitting
*/
public static ArrayList<String> splitString(String str, String valueSplit) {
ArrayList<String> arrayListString = new ArrayList<>();
for (String s : str.split(valueSplit, 0)) {
arrayListString.add(s);
}
return arrayListString;
}
}
16 changes: 14 additions & 2 deletions src/main/java/com/anhtester/managers/BrowserFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.microsoft.playwright.*;

import java.awt.*;
import java.nio.file.Paths;

public class BrowserFactory {
protected static Playwright playwright;
Expand Down Expand Up @@ -49,12 +50,23 @@ public static void createBrowser(String browserName) {
// System.out.println("Screen Browser Width (customize): " + AppConfig.VIEWPORT_WIDTH);
// System.out.println("Screen Browser Height (customize): " + AppConfig.VIEWPORT_HEIGHT);

browserContext = PageManager.getBrowser().newContext(new Browser.NewContextOptions().setViewportSize(AppConfig.VIEWPORT_WIDTH, AppConfig.VIEWPORT_HEIGHT).setDeviceScaleFactor(1));
browserContext = PageManager.getBrowser().newContext(new Browser.NewContextOptions()
.setRecordVideoDir(Paths.get("exports/videos/"))
.setViewportSize(AppConfig.VIEWPORT_WIDTH, AppConfig.VIEWPORT_HEIGHT)
.setDeviceScaleFactor(1));

// Start tracing before creating / navigating a page.
if (AppConfig.TRACE_VIEWER == true) {
browserContext.tracing().start(new Tracing.StartOptions()
.setScreenshots(true)
.setSnapshots(true)
.setSources(true));
}

PageManager.setBrowserContext(browserContext);
page = PageManager.getBrowserContext().newPage();

PageManager.setPage(page);
WebKeyword.maximizeBrowserOnWindow();
//WebKeyword.maximizeBrowserOnWindow();
}
}
22 changes: 13 additions & 9 deletions src/main/java/com/anhtester/managers/PageManager.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.anhtester.managers;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.anhtester.utils.LogUtils;
import com.microsoft.playwright.*;

import java.nio.file.Paths;

public class PageManager {

Expand Down Expand Up @@ -48,18 +48,22 @@ public static void closePage() {
if (pageThreadLocal.get() != null) {
pageThreadLocal.get().close();
pageThreadLocal.remove();
LogUtils.info("Closed page.");
}
}

public static void closeTracing(String path) {
// Stop tracing and export it into a zip archive.
browserContextThreadLocal.get().tracing().stop(new Tracing.StopOptions()
.setPath(Paths.get(path)));
LogUtils.info("Closed Tracing.");
}

public static void closeBrowser() {
if (browserThreadLocal.get() != null) {
browserThreadLocal.get().close();
browserThreadLocal.remove();
System.out.println("Closed browser.");
}
if (playwrightThreadLocal.get() != null) {
playwrightThreadLocal.get().close();
playwrightThreadLocal.remove();
LogUtils.info("Closed browser.");
}
}

Expand Down
7 changes: 3 additions & 4 deletions src/main/java/com/anhtester/reports/ExtentTestManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.io.File;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -34,8 +35,7 @@ public static void addScreenShot(String message) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
ScreenshotOptions screenshotOptions = new ScreenshotOptions();

String base64Image = "data:image/png;base64,"
+ PageManager.getPage().screenshot(screenshotOptions.setPath(Paths.get(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH") + File.separator + "ExtentReport_" + dateFormat.format(new Date()) + ".png"))).toString();
String base64Image = Base64.getEncoder().encodeToString(PageManager.getPage().screenshot(screenshotOptions.setPath(Paths.get(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH") + File.separator + "ExtentReport_" + dateFormat.format(new Date()) + ".png"))));

getTest().log(Status.FAIL, message,
MediaEntityBuilder.createScreenCaptureFromBase64String(base64Image).build());
Expand All @@ -45,8 +45,7 @@ public static void addScreenShot(Status status, String message) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
ScreenshotOptions screenshotOptions = new ScreenshotOptions();

String base64Image = "data:image/png;base64,"
+ PageManager.getPage().screenshot(screenshotOptions.setPath(Paths.get(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH") + File.separator + dateFormat.format(new Date()) + ".png")));
String base64Image = Base64.getEncoder().encodeToString(PageManager.getPage().screenshot(screenshotOptions.setPath(Paths.get(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH") + File.separator + "ExtentReport_" + dateFormat.format(new Date()) + ".png"))));

getTest().log(status, message,
MediaEntityBuilder.createScreenCaptureFromBase64String(base64Image).build());
Expand Down
7 changes: 3 additions & 4 deletions src/test/java/com/anhtester/common/BaseTest.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
package com.anhtester.common;

import com.anhtester.constants.AppConfig;
import com.anhtester.helpers.PropertiesHelper;
import com.anhtester.keywords.WebKeyword;
import com.anhtester.listeners.TestListener;
import com.anhtester.managers.BrowserFactory;
import com.anhtester.managers.PageManager;
import com.anhtester.pom.pages.CommonPage;
import com.anhtester.pom.pages.BasePage;
import org.testng.annotations.*;

@Listeners(TestListener.class)
public class BaseTest extends CommonPage {
public class BaseTest extends BasePage {

@BeforeMethod
@Parameters({"BROWSER"})
public void createBrowser(@Optional("chrome") String browserName) {
if (AppConfig.BROWSER != null && !AppConfig.BROWSER.isEmpty()) {
BrowserFactory.createBrowser(AppConfig.BROWSER);
}else {
} else {
BrowserFactory.createBrowser(browserName);
}
}
Expand Down
18 changes: 10 additions & 8 deletions src/test/java/com/anhtester/listeners/AllureListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.anhtester.helpers.PropertiesHelper;
import com.anhtester.helpers.SystemHelper;
import com.anhtester.keywords.WebKeyword;
import com.anhtester.managers.PageManager;
import com.anhtester.reports.AllureManager;
import com.microsoft.playwright.Page.ScreenshotOptions;
Expand Down Expand Up @@ -44,14 +45,15 @@ public void afterTestStart(TestResult result) {

@Override
public void beforeTestStop(TestResult result) {
// SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
//
// ScreenshotOptions screenshotOptions = new ScreenshotOptions();
// if (result.getStatus() == Status.FAILED || result.getStatus() == Status.SKIPPED || result.getStatus() == Status.BROKEN) {
// if (PageManager.getPage() != null) {
// Allure.addAttachment(result.getName() + "_Failed_Screenshot", new ByteArrayInputStream(PageManager.getPage().screenshot(screenshotOptions.setPath(Paths.get(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH") + File.separator + dateFormat.format(new Date()) + ".png")))));
// }
// }
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");

ScreenshotOptions screenshotOptions = new ScreenshotOptions();
if (result.getStatus() == Status.FAILED) {
if (PageManager.getPage() != null) {
WebKeyword.sleep(1);
Allure.addAttachment(result.getName() + "_Failed_Screenshot", new ByteArrayInputStream(PageManager.getPage().screenshot(screenshotOptions.setPath(Paths.get(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH") + File.separator + dateFormat.format(new Date()) + ".png")))));
}
}
}

@Override
Expand Down
Loading

0 comments on commit f5ac40d

Please sign in to comment.