Skip to content

Commit

Permalink
Bài 30 - Take Screenshot and Record video
Browse files Browse the repository at this point in the history
  • Loading branch information
anhtester committed Dec 6, 2023
1 parent 3bb6a76 commit c81372e
Show file tree
Hide file tree
Showing 6 changed files with 206 additions and 10 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,6 @@ build/
.classpath
.idea/
out/
*.iml
*.iml
reports/
report/
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@
<version>2.15.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.github.stephenc.monte/monte-screen-recorder -->
<dependency>
<groupId>com.github.stephenc.monte</groupId>
<artifactId>monte-screen-recorder</artifactId>
<version>0.7.7.0</version>
</dependency>

</dependencies>

</project>
120 changes: 120 additions & 0 deletions src/main/java/com/anhtester/helpers/CaptureHelper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package com.anhtester.helpers;

import com.anhtester.drivers.DriverManager;
import org.monte.media.Format;
import org.monte.media.Registry;
import org.monte.media.math.Rational;
import org.monte.screenrecorder.ScreenRecorder;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.io.FileHandler;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static org.monte.media.FormatKeys.*;
import static org.monte.media.VideoFormatKeys.*;

public class CaptureHelper extends ScreenRecorder {

// Record with Monte Media library
public static ScreenRecorder screenRecorder;
public String name;

//Hàm xây dựng
public CaptureHelper(GraphicsConfiguration cfg, Rectangle captureArea, Format fileFormat, Format screenFormat, Format mouseFormat, Format audioFormat, File movieFolder, String name) throws IOException, AWTException {
super(cfg, captureArea, fileFormat, screenFormat, mouseFormat, audioFormat, movieFolder);
this.name = name;
}

//Hàm này bắt buộc để ghi đè custom lại hàm trong thư viên viết sẵn
@Override
protected File createMovieFile(Format fileFormat) throws IOException {

if (!movieFolder.exists()) {
movieFolder.mkdirs();
} else if (!movieFolder.isDirectory()) {
throw new IOException("\"" + movieFolder + "\" is not a directory.");
}
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
return new File(movieFolder, name + "-" + dateFormat.format(new Date()) + "." + Registry.getInstance().getExtension(fileFormat));
}

// Start record video
public static void startRecord(String methodName) {
//Tạo thư mục để lưu file video vào
File file = new File(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("VIDEO_RECORD_PATH"));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width;
int height = screenSize.height;

Rectangle captureSize = new Rectangle(0, 0, width, height);

GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
try {
screenRecorder = new CaptureHelper(gc, captureSize, new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI), new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE, CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE, DepthKey, 24, FrameRateKey, Rational.valueOf(15), QualityKey, 1.0f, KeyFrameIntervalKey, 15 * 60), new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black", FrameRateKey, Rational.valueOf(30)), null, file, methodName);
screenRecorder.start();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (AWTException e) {
throw new RuntimeException(e);
}
}

// Stop record video
public static void stopRecord() {
try {
screenRecorder.stop();
} catch (IOException e) {
throw new RuntimeException(e);
}
}


//Tạo format ngày giờ để xíu gắn dô cái name của screenshot hoặc record video không bị trùng tên (không bị ghi đè file)
private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");

public static void captureScreenshot(String screenshotName) {
try {
// Tạo tham chiếu đối tượng của TakesScreenshot với dirver hiện tại
TakesScreenshot ts = (TakesScreenshot) DriverManager.getDriver();
// Gọi hàm getScreenshotAs để chuyển hóa hình ảnh về dạng FILE
File source = ts.getScreenshotAs(OutputType.FILE);
//Kiểm tra folder nếu không tồn tại thì tạo folder
File theDir = new File(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH"));
if (!theDir.exists()) {
theDir.mkdirs();
}
// Chổ này đặt tên thì truyền biến "screenName" gán cho tên File chụp màn hình
FileHandler.copy(source, new File(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH") + File.separator + screenshotName + "_" + dateFormat.format(new Date()) + ".png"));
System.out.println("Screenshot taken: " + screenshotName);
System.out.println("Screenshot taken current URL: " + DriverManager.getDriver().getCurrentUrl());
} catch (Exception e) {
System.out.println("Exception while taking screenshot: " + e.getMessage());
}
}

public static void takeScreenshot(String screenshotName) {
// Tạo tham chiếu của TakesScreenshot
TakesScreenshot ts = (TakesScreenshot) DriverManager.getDriver();
// Gọi hàm để chụp ảnh màn hình - getScreenshotAs
File source = ts.getScreenshotAs(OutputType.FILE);
// Kiểm tra folder tồn tại. Nếu không thì tạo mới folder theo đường dẫn
File theDir = new File(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH"));
if (!theDir.exists()) {
theDir.mkdirs(); //Tạo mới thư mục
}
// Lưu file ảnh với tên cụ thể vào đường dẫn
try {
FileHandler.copy(source, new File(SystemHelper.getCurrentDir() + PropertiesHelper.getValue("SCREENSHOT_PATH") + screenshotName + ".png"));
System.out.println("Take screenshot " + screenshotName + " successfully.");
} catch (IOException e) {
System.out.println("ERROR. Can not Take screenshot " + screenshotName + ".");
e.printStackTrace();
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.anhtester.Bai30_TakeScreenshot_RecordVideo;

import com.anhtester.Bai26_CustomDriverParallelExecution.pages.LoginPage;
import com.anhtester.common.BaseTest;
import com.anhtester.helpers.CaptureHelper;
import com.anhtester.helpers.ExcelHelper;
import org.testng.annotations.Test;

public class DemoTakeScreenshot extends BaseTest {

LoginPage loginPage;

@Test
public void testLoginCRM_Success() {
System.out.println("=====testLoginCRM_Success=====");
CaptureHelper.startRecord("testLoginCRM_Success");

loginPage = new LoginPage();

ExcelHelper excelHelper = new ExcelHelper();
excelHelper.setExcelFile("src/test/resources/testdata/LoginData.xlsx", "Sheet1");

loginPage.loginCRM(
excelHelper.getCellData("EMAIL", 1),
excelHelper.getCellData("PASSWORD", 1)
);

//CaptureHelper.takeScreenshot("testLoginCRM_Success");

//CaptureHelper.stopRecord();

loginPage.verifyLoginSuccess();

}

@Test
public void testLoginCRM_Fail() {
System.out.println("=====testLoginCRM_Success=====");
CaptureHelper.startRecord("testLoginCRM_Fail");

loginPage = new LoginPage();

ExcelHelper excelHelper = new ExcelHelper();
excelHelper.setExcelFile("src/test/resources/testdata/LoginData.xlsx", "Sheet1");

loginPage.loginCRM(
excelHelper.getCellData("EMAIL", 2),
excelHelper.getCellData("PASSWORD", 2)
);

//CaptureHelper.takeScreenshot("testLoginCRM_Fail");

//CaptureHelper.stopRecord();

loginPage.verifyLoginSuccess();

}

}
24 changes: 15 additions & 9 deletions src/test/java/com/anhtester/common/BaseTest.java
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
package com.anhtester.common;

import com.anhtester.drivers.DriverManager;
import com.anhtester.helpers.CaptureHelper;
import com.anhtester.helpers.PropertiesHelper;
import com.anhtester.keywords.WebUI;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.annotations.*;

public class BaseTest {

@BeforeSuite
public void beforeSuite(){
//Chỉ cần load 1 lần là đã lưu giá trị vào bộ nhớ tạm, áp dụng cho toàn phiên chạy
public void beforeSuite() {
PropertiesHelper.loadAllFiles();
}

@BeforeMethod
@Parameters({"browser"})
public void createDriver(@Optional("chrome") String browserName) {
WebDriver driver = setupBrowser(browserName); //Khởi tạo loại browser và gán vào driver
//new WebUI(driver);
DriverManager.setDriver(driver); //Mang giá trị driver đã khởi tạo vào trong ThreadLocal
WebDriver driver = setupBrowser(browserName);
DriverManager.setDriver(driver);
}

//Viết hàm trung gian để lựa chọn Browser cần chạy với giá trị tham số "browser" bên trên truyền vào
public WebDriver setupBrowser(String browserName){
public WebDriver setupBrowser(String browserName) {
WebDriver driver;
switch (browserName.trim().toLowerCase()) {
case "chrome":
Expand All @@ -44,7 +44,6 @@ public WebDriver setupBrowser(String browserName){
return driver;
}

// Viết các hàm khởi chạy cho từng Browser đó
private WebDriver initChromeDriver() {
WebDriver driver;
System.out.println("Launching Chrome browser...");
Expand All @@ -70,7 +69,14 @@ private WebDriver initFirefoxDriver() {
}

@AfterMethod
public void closeDriver() {
public void closeDriver(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
CaptureHelper.takeScreenshot(result.getName());
}

WebUI.sleep(1);
CaptureHelper.stopRecord();

DriverManager.quit();
}
}
2 changes: 2 additions & 0 deletions src/test/resources/configs/configs.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ email=admin@example.com
message=Add customer successfully
password=123456
url=https\://crm.anhtester.com/admin/authentication
SCREENSHOT_PATH = reports/screenshots/
VIDEO_RECORD_PATH = reports/videorecords/

0 comments on commit c81372e

Please sign in to comment.