Wednesday, March 23, 2016

Webdriver Parser to retrieve information from an HTML report - direct access was not available to use listeners

import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.support.ui.*;  
 import java.util.*;  
 import java.util.concurrent.TimeUnit;  
 /**  
  * Created by Mridul on 1/14/2016.  
  */  
 public class ReportParser {  
   private WebDriver driver;  
   private WebDriverWait wait;  
   ReportParser(){  
     System.setProperty("webdriver.chrome.driver", "C:\\chromedriver\\chromedriver.exe");  
     this.driver = new ChromeDriver();  
     driver.manage().window().maximize();  
     wait=new WebDriverWait(driver,10);  
   }  
   public WebDriver getDriver(){  
     return driver;  
   }  
   public WebDriverWait getWaitDriver(){  
     return wait;  
   }  
   private void printMap(Map<String,List<String>> testMap){  
     System.out.println("Printing values in map!");  
     for(Map.Entry entry: testMap.entrySet()){  
       System.out.println("The Defect is :" + entry.getKey());  
       System.out.println("The associated tests are :");  
       for(String value : (List<String>)entry.getValue()){  
         System.out.println(value);  
       }  
       System.out.println("\n");  
     }  
     System.out.println("The no of tests are : " + testMap.size());  
   }  
   private Map<String,List<String>> storeTestsToMap(List<WebElement> elements, Map<String, List<String>> testMap){  
     for(WebElement element: elements){  
       //WebElement anchor=element.findElement(By.tagName("a"));  
       WebElement anchor=wait.until(ExpectedConditions.presenceOfElementLocated(By.tagName("a")));  
       //retrieve key  
       String fullKey=anchor.getAttribute("title");  
       String key=(fullKey.contains("Exception"))? fullKey.substring(0,fullKey.indexOf("Exception")) : fullKey;  
       //System.out.println(key);  
       //retrieve value  
       String fullValue=anchor.getText();  
       String value=fullValue.substring(fullValue.indexOf("Shopping"), fullValue.length());  
       //System.out.println(value+"\n");  
       //store key value into map based on unique key  
       List<String> values;  
       if(testMap.containsKey(key)){  
         values=testMap.get(key);  
       }else {  
         values=new ArrayList<String>();  
       }  
       values.add(value);  
       testMap.put(key, values);  
     }  
     return testMap;  
   }  
   public static void main(String... args){  
     try {  
       int displaySize, totalCount, currentCount;  
       Map<String, List<String>> failureTestsMap=new WeakHashMap<String, List<String>>();  
       Map<String, List<String>> errorTestsMap=new WeakHashMap<String, List<String>>();  
       ReportParser reportParser;  
       WebDriver driver;  
       WebDriverWait wait;  
       reportParser = new ReportParser();  
       driver = reportParser.getDriver();  
       wait=reportParser.getWaitDriver();  
       driver.get("http://localhost:63342/ais-parent/ais-dotcom/target/site/thucydides/index.html");  
       driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);  
       do {  
         //WebElement testTable = driver.findElement(By.id("test-results-table"));  
         //List<WebElement> elems_failureTest = testTable.findElements(By.className("FAILURE-text"));  
         WebElement testTable = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("test-results-table")));  
         //List<WebElement> elems_failureTest = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("FAILURE-text")));  
         List<WebElement> elems_failureTest = testTable.findElements(By.className("FAILURE-text"));  
         //System.out.println("Failure tests size : " + elems_failureTest.size());  
         failureTestsMap = reportParser.storeTestsToMap(elems_failureTest,failureTestsMap);  
         //reportParser.printMap(failureTestsMap);  
         List<WebElement> elems_errorTest = testTable.findElements(By.className("ERROR-text"));  
         //System.out.println("Error tests size : " + elems_errorTest.size());  
         errorTestsMap = reportParser.storeTestsToMap(elems_errorTest, errorTestsMap);  
         //reportParser.printMap(errorTestsMap);  
         //navigate to the drop down element  
         //Select sel_ResultSize = new Select(driver.findElement(By.name("test-results-table_length")));  
         Select sel_ResultSize = new Select(wait.until(ExpectedConditions.presenceOfElementLocated(By.name("test-results-table_length"))));  
         displaySize = Integer.parseInt(sel_ResultSize.getFirstSelectedOption().getText());  
         //System.out.println("Size : " + displaySize);  
         //retrieve the total tests  
         //String totalTests = driver.findElement(By.id("test-results-table_info")).getText();  
         String totalTests = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("test-results-table_info"))).getText();  
         String count = totalTests.substring(totalTests.indexOf("to"), totalTests.indexOf("of"));  
         currentCount = Integer.parseInt(count.substring(count.length() - 3, count.length() - 1));  
         //System.out.println("currentCount : " + currentCount);  
         String finalCount = totalTests.substring(totalTests.indexOf("of"), totalTests.indexOf("entries"));  
         totalCount = Integer.parseInt(finalCount.substring(finalCount.length() - 3, finalCount.length() - 1));  
         //System.out.println("totalCount : " + totalCount);  
         //click on the next button  
         //WebElement elem_NextButton=driver.findElement(By.id("test-results-table_next"));  
         WebElement elem_NextButton=wait.until(ExpectedConditions.presenceOfElementLocated(By.id("test-results-table_next")));  
         elem_NextButton.click();  
       } while (currentCount < totalCount);  
       reportParser.printMap(failureTestsMap);  
       System.out.println("The no of failure tests are : " + failureTestsMap.size());  
       reportParser.printMap(errorTestsMap);  
       System.out.println("The no of error tests are : "+errorTestsMap.size());  
     }finally {  
       //driver.quit();  
     }  
   }  
 }  

Friday, March 4, 2016

Xml value - absolute xpath mapper. Maps multiple paths if present for each unique value as key

 package com.mridul.mapper;  
 import org.w3c.dom.Document;  
 import org.w3c.dom.Element;  
 import org.w3c.dom.NodeList;  
 import org.w3c.dom.Node;  
 import javax.xml.parsers.DocumentBuilder;  
 import javax.xml.parsers.DocumentBuilderFactory;  
 import java.io.ByteArrayInputStream;  
 import java.io.File;  
 import java.io.IOException;  
 import java.util.*;  
 /**  
  * Created by Mridul on 2/25/2016.  
  */  
 public class Mapper {  
   private List<StringBuilder> paths = new ArrayList<>();  
   private Node rootNode;  
   private static String FORWARD_SLASH = "/";  
   private static int ROOT_COUNTER = 0;  
   private boolean textFlag = false;  
   private static Map<String, List<String>> valuePathMap=new WeakHashMap<>();  
   public boolean isTextFlag() {  
     return textFlag;  
   }  
   public void setTextFlag(boolean textFlag) {  
     this.textFlag = textFlag;  
   }  
   public Node getRootNode() {  
     return rootNode;  
   }  
   public void setRootNode(Node rootNode) {  
     this.rootNode = rootNode;  
   }  
   public static void main(String... args) {  
     try {  
       //The order of these sequential steps matter  
       Mapper mapper = new Mapper();  
       StringBuilder xmlAsString = mapper.getFileAsStringBuilder("xml/catalog.xml");  
       //StringBuilder xmlAsString = mapper.getFileAsStringBuilder("xml/auction.xml");  
       //StringBuilder xmlAsString = mapper.getFileAsStringBuilder("xml/uwm.xml");  
       mapper.retrieveAndSetRootNode(xmlAsString);  
       mapper.recursivelyPrintAllNodes(FORWARD_SLASH);  
       mapper.printValuesInMap();  
     } catch (Exception e) {  
       e.printStackTrace();  
     }  
   }  
   private StringBuilder getFileAsStringBuilder(String fileName) {  
     StringBuilder result = new StringBuilder();  
     ClassLoader classLoader = getClass().getClassLoader();  
     File file = new File(classLoader.getResource(fileName).getFile());  
     try (Scanner scanner = new Scanner(file)) {  
       while (scanner.hasNextLine()) {  
         String line = scanner.nextLine();  
         result.append(line).append("\n");  
       }  
       scanner.close();  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
     //System.out.println(result.toString());  
     return result;  
   }  
   private void retrieveAndSetRootNode(StringBuilder xml) throws Exception {  
     DocumentBuilderFactory factory =  
         DocumentBuilderFactory.newInstance();  
     DocumentBuilder builder = factory.newDocumentBuilder();  
     ByteArrayInputStream input = new ByteArrayInputStream(xml.toString().getBytes("UTF-8"));  
     Document document = builder.parse(input);  
     Element rootNode = document.getDocumentElement();  
     setRootNode(rootNode);  
   }  
   private void recursivelyPrintAllNodes(String path) {  
     Node rootNode = getRootNode();  
     String rootNodeName = rootNode.getNodeName();  
     if (ROOT_COUNTER == 0) {  
       path = path + rootNode.getNodeName();  
     }  
     ++ROOT_COUNTER;  
     String parentPath = path;  
     NodeList childNodes;  
     if (rootNode.hasChildNodes()) {  
       childNodes = rootNode.getChildNodes();  
       for (int index = 0; index < childNodes.getLength(); index++) {  
         Node currentNode = childNodes.item(index);  
         short nodeType = currentNode.getNodeType();  
         if (nodeType == Node.TEXT_NODE) {  
           String value = currentNode.getNodeValue().trim();  
           if (value.equals("")) {  
             continue;  
           } else {  
 /*            System.out.println("The current path is : " + path);  
             System.out.println("The text node value is : " + value);*/  
             storeValuePathIntoMap(value, path);  
             this.setTextFlag(true);  
           }  
         }  
         if (isTextFlag()) {  
           setTextFlag(false);  
           break;  
         }  
         if (nodeType == Node.ELEMENT_NODE) {  
           String currentNodeName = currentNode.getNodeName();  
           if (!(rootNodeName.equals(currentNodeName))) { //add path only in case of mismatch  
             path = parentPath + FORWARD_SLASH + currentNodeName;  
           }  
           setRootNode(currentNode); //setting root node to current node  
           recursivelyPrintAllNodes(path);//recursive call to iterate  
         }  
       }  
     }  
   }  
   private void storeValuePathIntoMap(String key, String value){  
     if(valuePathMap.containsKey(key)){  
       List<String> values=valuePathMap.get(key);  
       values.add(value);  
     }else{  
       valuePathMap.put(key,new ArrayList<>(Arrays.asList(value)));  
     }  
   }  
   private void printValuesInMap(){  
     for(Map.Entry<String, List<String>> entry: valuePathMap.entrySet()){  
       System.out.println("Key: " + entry.getKey());  
       System.out.println("Value: " + entry.getValue()+"\n");  
     }  
   }  
 }