How to loop through dynamic values using a snippet

Prerequisite: Make sure to read How to run my custom Java code

Scenario: You have dropdowns in different parts of your application and each drop-down has a different set of values that you want to verify. Drop-down are country values. Depending on where they are in the application, they could have values related to Europ, South America, North America, and Asia. You want to select "Asia" at the beginning of your test using data templates and you want the test case to loop through all the values of Asia in the drop-down. Or you want to run it for European countries and so forth. In this article, we will show you how to do this. 

 

Solution: High level speaking this is what we will be doing: 

  1. Upload each continent countries list to a storage, Subject, Dropbox, Google Drive, S3, Etc. 
  2. Create a data template with a field called continent with fields name, excel_file_url, select_box_xpath. Add datasets with the continents name and as value enter the public link to the corresponding storage file.  
  3. Create a snippet that loops the values of an Excel file. 
  4. On the platform, create the snippet artifact and make sure as data_template you sepcify the dependency. 
  5. On Subject7 platform, create a test that opens the page and then invoke the snippet. 

 

1. To get started the list of countries are uploaded as Excel sheets on Amazon and here are the links: 

North America

South America

Europe

Asia

 

2. Here are the data_template and all 4 continents data_sets

mceclip0.png

 

3. As for the snippet, here are the Maven dependencies: 

<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>6.1.0</version>
</dependency>
</dependencies>

 

The code is separated into 2 classes CountryDropdownSample.java and a helper model class Continent.java. The idea is to read the Excel files from the web and populate the model object. Then read the values from the select boxes found in https://countries.subject-7.com

 Here is CountryDropdownSample.java: 

package com.subject7.proof.snippets.samples.countries;

/**
* Created by shahryarfeizi on 11/6/18.
*/

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.*;

import io.appium.java_client.AppiumDriver;
import org.apache.poi.ss.usermodel.*;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;

public class CountryDropdownSample {

private WebDriver driver;
private Map<String, String> parametersMap = new HashMap<String, String>();
private AppiumDriver appiumDriver;
private static String EXCEL_FILE_URL = "https://s3.amazonaws.com/subject7-public/snippets/countries/north_america.xlsx";
private static String SELECT_BOX_XPATH = "//select[@name='northAmericanSelect']";
private static String CONTINENT_NAME="North America";

//This method is created to be able to run the sample from your IDE so you can debug. This will not be called from Subject7
public static void main(String[] args) {


//These values will be passed from Subject7. We initilaize here for testing purposes
HashMap<String, String> parametersMap = new HashMap<String, String>();
parametersMap.put("${continent.excel_file_url}",EXCEL_FILE_URL);
parametersMap.put("${continent.select_box_xpath}",SELECT_BOX_XPATH);
parametersMap.put("${continent.name}", CONTINENT_NAME);

//For windows users, just point to your chromedriver on your local drive.
System.setProperty("webdriver.chrome.driver", "/Users/shahryarfeizi/.proof/drivers/chrome-driver-mac");
ChromeDriver driver = null;
DesiredCapabilities capabilities = null;
capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));

//DO NOT CLOSE the driver in your main code. driver is used throughout the test case and Subject7 handles it.
driver = new ChromeDriver((Capabilities)capabilities);
CountryDropdownSample csd = new CountryDropdownSample();
csd.setWebDriver((WebDriver)driver);
csd.setParametersMap(parametersMap);

driver.navigate().to("https://countries.subject-7.com");

try {
String result = csd.checkDropdownValues();
System.out.println(result); //Subject7 parses the result 'Pass|Fail|Fail_Stop, message for command'
} catch (Exception e) {
e.printStackTrace();

} finally {
driver.close();
}
}

public void setWebDriver(WebDriver driver) {
this.driver = driver;
}

public void setParametersMap(Map<String, String> map) {
this.parametersMap = map;
}

public void setAppiumDriver(AppiumDriver appiumDriver) {
this.appiumDriver = appiumDriver;
}


public String checkDropdownValues() {

String continentName = parametersMap.get("${continent.name}");
String result = "PASS, Select box '" + continentName + "' has correct values.";
boolean hasMismatch = false;
String misMatchValues = "";

Continent continent = null;
try {
continent = parseExcelAndCreateContinentObject();
String dropDownXPath = parametersMap.get("${continent.select_box_xpath}");

/*driver.navigate().to("https://beta.subject-7.com/");
try {Thread.sleep(3000);} catch (InterruptedException e) {}*/
WebElement elem = driver.findElement(By.xpath(dropDownXPath));
Select selectElement = new Select(elem);

List<WebElement> webOptions = selectElement.getOptions();
Iterator<String> excelOptionsIt = continent.getCountries().iterator();

for (WebElement option : webOptions) {
String valueFromWeb = option.getAttribute("text");
String valueFromExcel = excelOptionsIt.next();
if (!valueFromExcel.equals(valueFromWeb)) {
hasMismatch = true;
misMatchValues = misMatchValues + "Web:" + valueFromWeb + "<> Excel:" + valueFromExcel + "\n";
}
}
if ( hasMismatch)
result = "FAIL_STOP, " + misMatchValues;

} catch (Exception e) {
e.printStackTrace();
result = "ERROR," + e.getMessage();
return result;
}
return result;
}


private Continent parseExcelAndCreateContinentObject() throws Exception {


InputStream is = null;
Workbook workbook = null;
Continent continent = new Continent();
String continentName = parametersMap.get("${continent.name}");
String excelFileUrl = parametersMap.get("${continent.excel_file_url}");
System.out.println("${continent.name}=" + continentName);
System.out.println("${continent.excel_file_url}=" + excelFileUrl);

try {
String urlString = parametersMap.get("${continent.name}");
URL url = new URL(excelFileUrl);
is = url.openStream();
workbook = WorkbookFactory.create(is);

//Excel Sheet default

Sheet sheet = workbook.getSheetAt(0);
if ( sheet == null)
throw new Exception("Cannot find sheet='" + continentName + "'");

Iterator<Row> rowIterator = sheet.rowIterator();
rowIterator.next(); //Skip headers
while (rowIterator.hasNext()) {
Row row = rowIterator.next();

Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
continent.addCountry(cell.getStringCellValue());
cellIterator.next();
}
}

} catch (ConnectException connectionException) {
throw new Exception("Error reading Excel file");
} catch (Exception e) {
throw e;
}
finally {

try {
if ( workbook != null) {
workbook.close();
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}

}
return continent;
}
}

 

And here is the Continent.java class: 

package com.subject7.proof.snippets.samples.countries;

import java.util.Collection;
import java.util.LinkedList;

/**
* Created by shahryarfeizi on 11/12/18.
*/
public class Continent {

private String name;
private Collection<String> countries;

public Continent() {
this.name = "";
this.countries = new LinkedList<String>();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Collection<String> getCountries() {
return countries;
}

public void setCountries(Collection<String> countries) {
this.countries = countries;
}


public void addCountry(String name) {
countries.add(name);
}
public void printNames() {
for (String country: countries)
System.out.println("Country=" + country);

}
}

 

Also here is jar file incase you want to try it out. Countries.jar

 

4. Upload the jar file and create the Snippet artifact. Make sure you select the data template continent so when running the Snippet, you can pass different Excel files to it. 

mceclip2.png

 5. Last step, create the test case with the following commands: 

GOTO_URL HALT https://countries.subject-7.com/
EXECUTE_JAVA HALT verify_dropdown_countries com.subject7.proof.snippets.samples.countries.CountryDropdownSample checkDropdownValues

When running select your desired set and enjoy!

mceclip3.png

 

 

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

Comments

Please sign in to leave a comment.