Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CR-1729] Addon to compare 2 xml files and Ignore specific regions based on Xpath. #68

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions xml_verification_/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.testsigma.addons</groupId>
<artifactId>xml_verification_</artifactId>
<version>1.0.3</version>
<packaging>jar</packaging>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<testsigma.sdk.version>1.2.13_cloud</testsigma.sdk.version>
<junit.jupiter.version>5.8.0-M1</junit.jupiter.version>
<testsigma.addon.maven.plugin>1.0.0</testsigma.addon.maven.plugin>
<maven.source.plugin.version>3.2.1</maven.source.plugin.version>
<lombok.version>1.18.20</lombok.version>

</properties>

<dependencies>
<dependency>
<groupId>com.testsigma</groupId>
<artifactId>testsigma-java-sdk</artifactId>
<version>${testsigma.sdk.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.14.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.appium/java-client -->
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>9.0.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
</dependencies>
<build>
<finalName>xml_verification_</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>${maven.source.plugin.version}</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.testsigma.addons.utilities;

import com.testsigma.sdk.Logger;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.WebDriver;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class XMLUtility {

WebDriver driver;
Logger logger;

public XMLUtility(WebDriver driver, Logger logger) {
this.driver = driver;
this.logger = logger;
}
public Document parseXML(String xmlContent) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(xmlContent.getBytes()));
}

public Document parseXML(File file) throws Exception {
if (file == null || !file.exists() || file.length() == 0) {
logger.warn("Invalid file: " + (file == null ? "null" : file.getAbsolutePath()));
throw new Exception("Invalid file: " + (file == null ? "null" : file.getAbsolutePath()));
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // Enable namespace awareness
DocumentBuilder builder = factory.newDocumentBuilder();

logger.info("Parsing XML file: " + file.getAbsolutePath());
Document document = builder.parse(file);

document.getDocumentElement().normalize(); // Normalize the document
logger.info("Root element: " + document.getDocumentElement().getNodeName());
return document;
}


public void removeNodesByXPath(Document doc, String xpathExpression) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression xPathExpr = xpath.compile(xpathExpression);
NodeList nodes = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node != null && node.getParentNode() != null) {
node.getParentNode().removeChild(node);
}
}
}


public File urlToFileConverter(String fileName, String url) throws IOException {
if (url.startsWith("https://")) {
logger.info("Given is s3 url ...File name:" + fileName);
URL urlObject = new URL(url);
File tempFile = File.createTempFile(fileName.split("\\.")[0], "." + fileName.split("\\.")[1]);
FileUtils.copyURLToFile(urlObject,tempFile);
logger.info("Temp file created with name for s3 file" + tempFile.getName() + " at path " + tempFile.getAbsolutePath());
return tempFile;
} else {
logger.info("Given is local file path..");
return new File(url);
}
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.testsigma.addons.web;

import com.testsigma.addons.utilities.XMLUtility;
import com.testsigma.sdk.ApplicationType;
import com.testsigma.sdk.Result;
import com.testsigma.sdk.WebAction;
import com.testsigma.sdk.annotation.Action;
import com.testsigma.sdk.annotation.TestData;
import lombok.Data;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.NoSuchElementException;
import org.w3c.dom.Document;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

@Data
@Action(actionText = "Xml: Verify if local files with filepath filepath1 and filepath filepath2 are equal while ignoring specific XPaths X-Paths",
description = "Verifies if files with given filepath are equal while ignoring given xPaths " +
"(separate xPaths by comma) e.g: xpath1, xpath2",
applicationType = ApplicationType.WEB)
public class CompareLocalXMLFiles extends WebAction {

@TestData(reference = "filepath1")
private com.testsigma.sdk.TestData testData1;

@TestData(reference = "filepath2")
private com.testsigma.sdk.TestData testData2;

@TestData(reference = "X-Paths")
private com.testsigma.sdk.TestData testData3;

@Override
protected Result execute() throws NoSuchElementException {
Result result ;
try {
XMLUtility xmlUtility = new XMLUtility(driver, logger);

// Get the file paths
String xPathsToIgnore = testData3.getValue().toString();
logger.info("xPaths to be ignored: " + xPathsToIgnore);

File baseFile = File.createTempFile("tempFile1_", ".xml");
File actualFile = File.createTempFile("tempFile2_", ".xml");

logger.info("created temp files");
baseFile = xmlUtility.urlToFileConverter(baseFile.getName(), testData1.getValue().toString());
actualFile = xmlUtility.urlToFileConverter(actualFile.getName(), testData2.getValue().toString());

logger.info("converted temp files");
// deleting files on completion of execution
baseFile.deleteOnExit();
actualFile.deleteOnExit();

// Parsing XML files
Document doc1 = xmlUtility.parseXML(baseFile);
Document doc2 = xmlUtility.parseXML(actualFile);
logger.info("Parsed the xml files");
// Removing nodes based on XPath expressions
String[] xpathArray = xPathsToIgnore.split(",");
for (String xpathExpression : xpathArray) {
xmlUtility.removeNodesByXPath(doc1, xpathExpression.trim());
xmlUtility.removeNodesByXPath(doc2, xpathExpression.trim());
}

logger.info("successfully Ignored xPaths of the given xml files");

// Compare the modified documents
boolean isEqual = doc1.isEqualNode(doc2);
if (isEqual) {
setSuccessMessage("The XML files are equal.");
result = Result.SUCCESS;
} else {
setErrorMessage("The base XML file is not same as the actual XML file.");
result = Result.FAILED;
}
return result;

} catch (Exception e) {
setErrorMessage("An error occurred, please check if the Xml file is not damaged " + ExceptionUtils.getMessage(e));
logger.info(ExceptionUtils.getStackTrace(e));
return Result.FAILED;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.testsigma.addons.web;

import com.testsigma.addons.utilities.XMLUtility;
import com.testsigma.sdk.ApplicationType;
import com.testsigma.sdk.Result;
import com.testsigma.sdk.WebAction;
import com.testsigma.sdk.annotation.Action;
import com.testsigma.sdk.annotation.TestData;
import lombok.Data;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.w3c.dom.Document;

import java.util.NoSuchElementException;

@Data
@Action(actionText = "Xml: Verify if xmlText text1 is equal to xmlText text2 while ignoring specific XPaths X-paths",
description = "Verifies if texts with given xml content are equal while ignoring given xPaths" +
" (separate xPaths by comma) e.g: xpath1, xpath2",
applicationType = ApplicationType.WEB)
public class CompareXMLTextsIgnoringXPaths extends WebAction {

@TestData(reference = "text1")
private com.testsigma.sdk.TestData testData1;

@TestData(reference = "text2")
private com.testsigma.sdk.TestData testData2;

@TestData(reference = "X-paths")
private com.testsigma.sdk.TestData testData3;

@Override
protected Result execute() throws NoSuchElementException {
Result result = Result.SUCCESS;
try {
String filePath1 = testData1.getValue().toString();
String filePath2 = testData2.getValue().toString();
String xPathsToIgnore = testData3.getValue().toString();
logger.info("xPathsToIgnore: " + xPathsToIgnore);
XMLUtility xmlUtility = new XMLUtility(driver, logger);
Document doc1 = xmlUtility.parseXML(filePath1);
Document doc2 = xmlUtility.parseXML(filePath2);
logger.info("Text1 after parsing into xml " + doc1);

// Remove nodes based on XPath expressions
String[] xpathArray = xPathsToIgnore.split(",");
for (String xpathExpression : xpathArray) {
xmlUtility.removeNodesByXPath(doc1, xpathExpression.trim());
xmlUtility.removeNodesByXPath(doc2, xpathExpression.trim());
}

logger.info("Text1 after ignoring xPaths " + doc1);
logger.info("Text2 after parsing xPaths " + doc2);
// Compare the modified documents
boolean isEqual = doc1.isEqualNode(doc2);
if (isEqual) {
setSuccessMessage("the given texts are equal");
result = Result.SUCCESS;
} else {
setErrorMessage("the given texts are not equal");
result = Result.FAILED;
}
return result;

} catch (Exception e) {
setErrorMessage("Error occurred while comparing: " + ExceptionUtils.getStackTrace(e));
logger.info(ExceptionUtils.getStackTrace(e));
return Result.FAILED;
}
}

}
Loading
Loading