Skip to content

Commit

Permalink
#593: refactor ScreenShot class to simplify it
Browse files Browse the repository at this point in the history
  • Loading branch information
bhecquet committed Sep 12, 2023
1 parent 32e87ca commit 1b51a66
Show file tree
Hide file tree
Showing 24 changed files with 497 additions and 607 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -308,8 +308,8 @@ protected void formatDescription(String testName, List<TestStep> failedSteps, Te
.map(Snapshot::getScreenshot)
.collect(Collectors.toList());
for (ScreenShot screenshot: screenshots) {
if (screenshot.getFullImagePath() != null && new File(screenshot.getFullImagePath()).exists()) {
fullDescription.append(String.format("!%s|thumbnail!\n", new File(screenshot.getFullImagePath()).getName()));
if (screenshot.getImage() != null && screenshot.getImage().getFile().exists()) {
fullDescription.append(String.format("!%s|thumbnail!\n", screenshot.getImage().getName()));
}
}
}
Expand Down Expand Up @@ -415,8 +415,9 @@ private void addAttachments(JiraBean jiraBean, IssueRestClient issueClient, Issu
if (!jiraBean.getScreenShots().isEmpty()) {
File[] files = jiraBean.getScreenShots()
.stream()
.peek(s -> logger.info("file -> " + s.getFullImagePath()))
.map(s -> new File(s.getFullImagePath()))
.filter(s -> s.getImage() != null)
.peek(s -> logger.info("file -> " + s.getImageName()))
.map(s -> s.getImage().getFile())
.filter(File::exists)
.collect(Collectors.toList())
.toArray(new File[] {});
Expand Down Expand Up @@ -613,7 +614,7 @@ private StringBuilder formatUpdateDescription(String messageUpdate, List<ScreenS

// add snapshots to comment
for (ScreenShot screenshot: screenShots) {
fullDescription.append(String.format("!%s|thumbnail!\n", new File(screenshot.getFullImagePath()).getName()));
fullDescription.append(String.format("!%s|thumbnail!\n", screenshot.getImage().getName()));
}

return fullDescription;
Expand Down Expand Up @@ -648,8 +649,9 @@ public void updateIssue(String issueId, String messageUpdate, List<ScreenShot> s
if (!screenShots.isEmpty()) {
issueClient.addAttachments(issue.getAttachmentsUri(), screenShots
.stream()
.peek(s -> logger.info("file ->" + s.getFullImagePath()))
.map(s -> new File(s.getFullImagePath()))
.filter(s -> s.getImage() != null)
.peek(s -> logger.info("file ->" + s.getImagePath()))
.map(s -> s.getImage().getFile())
.collect(Collectors.toList())
.toArray(new File[] {})
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ public Integer createTestStep(String testStep, Integer testCaseInSessionId) {
}

/**
* Get reference snapshot from server
* Get reference snapshot from server, copy it to a temp file
* This is useful when a step fails and we want to get the reference to allow comparison
*/
public File getReferenceSnapshot(Integer stepResultId) {
Expand Down Expand Up @@ -278,12 +278,12 @@ public void createStepReferenceSnapshot(Snapshot snapshot, Integer stepResultId)
}

checkStepResult(stepResultId);
if (snapshot == null || snapshot.getScreenshot() == null || snapshot.getScreenshot().getFullImagePath() == null) {
if (snapshot == null || snapshot.getScreenshot() == null || snapshot.getScreenshot().getImage() == null) {
throw new SeleniumRobotServerException(NAPSHOT_DOES_NOT_EXIST_ERROR);
}

try {
File pictureFile = new File(snapshot.getScreenshot().getFullImagePath());
File pictureFile = snapshot.getScreenshot().getImage().getFile();

getJSonResponse(buildPostRequest(url + STEP_REFERENCE_API_URL)
.field("stepResult", stepResultId)
Expand Down Expand Up @@ -316,14 +316,14 @@ public SnapshotComparisonResult checkSnapshotHasNoDifferences(Snapshot snapshot,
if (stepName == null) {
throw new ConfigurationException("stepName must not be null");
}
if (snapshot == null || snapshot.getScreenshot() == null || snapshot.getScreenshot().getFullImagePath() == null) {
if (snapshot == null || snapshot.getScreenshot() == null || snapshot.getScreenshot().getImage() == null) {
throw new SeleniumRobotServerException(NAPSHOT_DOES_NOT_EXIST_ERROR);
}

String snapshotName = snapshot.getName().length() > MAX_SNAPSHOT_NAME_LENGHT ? snapshot.getName().substring(0, MAX_SNAPSHOT_NAME_LENGHT): snapshot.getName();

try {
File pictureFile = new File(snapshot.getScreenshot().getFullImagePath());
File pictureFile = snapshot.getScreenshot().getImage().getFile();
BrowserType browser = SeleniumTestsContextManager.getGlobalContext().getBrowser();
browser = browser == null ? BrowserType.NONE : browser;
String strippedTestName = getTestName(testName);
Expand Down Expand Up @@ -394,14 +394,14 @@ public Integer createSnapshot(Snapshot snapshot, Integer sessionId, Integer test
throw new ConfigurationException("TestCaseInSession must be previously recorded");
}
checkStepResult(stepResultId);
if (snapshot == null || snapshot.getScreenshot() == null || snapshot.getScreenshot().getFullImagePath() == null) {
if (snapshot == null || snapshot.getScreenshot() == null || snapshot.getScreenshot().getImage() == null) {
throw new SeleniumRobotServerException(NAPSHOT_DOES_NOT_EXIST_ERROR);
}

String snapshotName = snapshot.getName().length() > MAX_SNAPSHOT_NAME_LENGHT ? snapshot.getName().substring(0, MAX_SNAPSHOT_NAME_LENGHT): snapshot.getName();

try {
File pictureFile = new File(snapshot.getScreenshot().getFullImagePath());
File pictureFile = snapshot.getScreenshot().getImage().getFile();

MultipartBody request = buildPostRequest(url + SNAPSHOT_API_URL)
.field("stepResult", stepResultId)
Expand Down Expand Up @@ -705,12 +705,12 @@ private JSONObject detectInPicture(ScreenShot screenShot, String task) {
return null;
}

if (screenShot == null || screenShot.getFullImagePath() == null) {
if (screenShot == null || screenShot.getImage() == null) {
throw new SeleniumRobotServerException("Provided screenshot does not exist");
}

try {
File pictureFile = new File(screenShot.getFullImagePath());
File pictureFile = screenShot.getImage().getFile();

return getJSonResponse(buildPostRequest(url + DETECT_API_URL)
.field("task", task)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,20 @@
*/
package com.seleniumtests.driver.screenshots;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import com.seleniumtests.customexception.ScenarioException;
import com.seleniumtests.reporter.logger.FileContent;
import com.seleniumtests.util.FileUtility;
import com.seleniumtests.util.HashCodeGenerator;
import org.apache.commons.io.FileExistsException;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.Logger;
Expand All @@ -32,6 +39,10 @@
import com.seleniumtests.core.SeleniumTestsContextManager;
import com.seleniumtests.util.logging.SeleniumRobotLogger;

/**
* Represents a screenshot (image + HTML source code when applicable)
* Files are stored in the output directory of the test
*/
public class ScreenShot {

private static final Logger logger = SeleniumRobotLogger.getLogger(ScreenShot.class);
Expand All @@ -40,57 +51,103 @@ public class ScreenShot {
private FileContent image;
private FileContent html;
private String title;
private String suiteName;
private long duration;
private boolean isException;
private String outputDirectory;

public ScreenShot() {
this(null);
}

public ScreenShot(String imagePath) {
if (SeleniumTestsContextManager.getGlobalContext().getTestNGContext() != null) {
suiteName = SeleniumTestsContextManager.getGlobalContext().getTestNGContext().getSuite().getName();
outputDirectory = SeleniumTestsContextManager.getThreadContext().getOutputDirectory();
/**
* File will be copied in <output_directory>/screenshots/<file_name>
* @param imageBuffer
*/
public ScreenShot(BufferedImage imageBuffer, String pageSource) {

initializeOutputDirectory();

String filename = HashCodeGenerator.getRandomHashCode("web");
if (imageBuffer != null) {
Path filePath = Paths.get(outputDirectory, ScreenshotUtil.SCREENSHOT_DIR, filename + ".png");
FileUtility.writeImage(filePath.toString(), imageBuffer);
this.image = new FileContent(filePath.toFile());
}

if (imagePath != null) {
this.image = new FileContent(Paths.get(outputDirectory, imagePath).toFile());

if (pageSource != null) {
try {
File htmlFile = Paths.get(outputDirectory, ScreenshotUtil.HTML_DIR, filename + ".html").toFile();
FileUtils.writeStringToFile(htmlFile, pageSource, StandardCharsets.UTF_8);
html = new FileContent(htmlFile);
} catch (IOException e) {
logger.warn("Ex", e);
}
}

this.duration = 0;
}

public boolean isException() {
return isException;

/**
* File will be copied in <output_directory>/screenshots/<file_name>
* @param imageFile
*/
public ScreenShot(File imageFile) {
this(imageFile, null, ScreenshotUtil.SCREENSHOT_DIR);
}

public void setException(final boolean isException) {
this.isException = isException;
public ScreenShot(File imageFile, File htmlFile) {
this(imageFile, htmlFile, ScreenshotUtil.SCREENSHOT_DIR);
}

/**
* @deprecated not used anymore
* @return
* File will be copied in <output_directory>/<relative_path>/<file_name>
* @param imageFile
*/
@Deprecated
public String getSuiteName() {
return suiteName;
public ScreenShot(File imageFile, File htmlFile, String relativePath) {



initializeOutputDirectory();

// copy the input image file to <output_directory>/screenshots/<file_name>
if (imageFile != null && imageFile.exists()) {
Path filePath = Paths.get(outputDirectory, relativePath, imageFile.getName());
filePath.getParent().toFile().mkdirs();
try {
Files.move(imageFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING);
this.image = new FileContent(filePath.toFile());
} catch (Exception e) {
throw new ScenarioException(String.format("Failed to move image file %s to %s: %s", imageFile.getAbsolutePath(), filePath.toFile().getAbsolutePath(), e.getMessage()));
}
}

// copy the input HTML file to <output_directory>/htmls/<file_name>
if (htmlFile != null && htmlFile.exists()) {
Path htmlFilePath = Paths.get(outputDirectory, ScreenshotUtil.HTML_DIR, htmlFile.getName());
htmlFilePath.getParent().toFile().mkdirs();
try {
Files.move(htmlFile.toPath(), htmlFilePath, StandardCopyOption.REPLACE_EXISTING);
this.html = new FileContent(htmlFilePath.toFile());
} catch (Exception e) {
throw new ScenarioException(String.format("Failed to move html file %s to %s: %s", htmlFile.getAbsolutePath(), htmlFilePath.toFile().getAbsolutePath(), e.getMessage()));
}
}

this.duration = 0;
}

private void initializeOutputDirectory() {
if (SeleniumTestsContextManager.getGlobalContext().getTestNGContext() != null) {
outputDirectory = SeleniumTestsContextManager.getThreadContext().getOutputDirectory();
} else {
throw new ScenarioException("Cannot create a screenshot outside of a test");
}
}

public String getOutputDirectory() {
return outputDirectory;
}

public void setOutputDirectory(final String outputDirectory) {

/**
* For test
* @param outputDirectory
*/
public void setOutputDirectory(String outputDirectory) {
this.outputDirectory = outputDirectory;
}

public void setSuiteName(final String suiteName) {
this.suiteName = suiteName;
}

/**
* URL of the page for which this screenshot has been taken
* @return
Expand All @@ -110,14 +167,6 @@ public String getImageName() {
public void setLocation(String location) {
this.location = location;
}

public void setHtmlSourcePath(String htmlSourcePath) {
this.html = new FileContent(Paths.get(outputDirectory, htmlSourcePath).toFile());
}

public void setImagePath(String imagePath) {
this.image = new FileContent(Paths.get(outputDirectory, imagePath).toFile());
}

/**
* Returns the relative path of HTML file (relative to outputDirectory)
Expand All @@ -131,19 +180,6 @@ public String getHtmlSourcePath() {
}

}

public String getHtmlSource() {
if (html != null) {
try {
return FileUtils.readFileToString(html.getFile(), StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("cannot read source file", e);
return "";
}
} else {
return "";
}
}

/**
* Get the image path relative to outputDirectory (directory where info for a specific test are recorded)
Expand All @@ -169,26 +205,10 @@ public void setTitle(final String title) {
this.title = title;
}

public String getFullImagePath() {
if (image != null) {
return image.getFile().getAbsolutePath().replace("\\", "/");
} else {
return null;
}
}

public String getFullHtmlPath() {
if (html != null) {
return html.getFile().getAbsolutePath().replace("\\", "/");
} else {
return null;
}
}

@Override
public String toString() {
return "!!!EXCEPTION:" + this.isException + "|APPLICATION URL:" + this.location + "|PAGE TITLE:" + this.title
+ "|PAGE HTML SOURCE:" + this.getFullHtmlPath() + "|PAGE IMAGE:" + this.getFullImagePath();
return "|APPLICATION URL:" + this.location + "|PAGE TITLE:" + this.title
+ "|PAGE HTML SOURCE:" + this.getHtmlSourcePath() + "|PAGE IMAGE:" + this.getImagePath();
}

public long getDuration() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -701,29 +701,13 @@ private File exportToFile(BufferedImage image) {
* @return
*/
private ScreenShot exportToScreenshot(NamedBufferedImage namedImage, long duration) {
ScreenShot screenShot = new ScreenShot();


File screenshotFile = exportToFile(namedImage.image);

ScreenShot screenShot = new ScreenShot(namedImage.image, namedImage.pageSource);

screenShot.setLocation(namedImage.url);
screenShot.setTitle(namedImage.title);

try {
FileUtils.writeStringToFile(Paths.get(outputDirectory, HTML_DIR, filename + ".html").toFile(), namedImage.pageSource, StandardCharsets.UTF_8);
screenShot.setHtmlSourcePath(String.format("%s/%s.html", HTML_DIR, filename));
} catch (IOException e) {
logger.warn("Ex", e);
}

// record duration of screenshot
screenShot.setDuration(duration);
if (screenshotFile.exists()) {
Path pathAbsolute = Paths.get(screenshotFile.getAbsolutePath());
Path pathBase = Paths.get(outputDirectory);

screenShot.setImagePath(pathBase.relativize(pathAbsolute).toString());
}
return screenShot;
}

Expand Down
Loading

0 comments on commit 1b51a66

Please sign in to comment.