Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

We will now return to our facts server from prior assignments. This time, you wi

ID: 3913224 • Letter: W

Question

We will now return to our facts server from prior assignments. This time, you will test the original version using input space partitioning.

Analyze the inputs and create an input domain model (IDM). Use the base choice criterion (BBC) to design tests. Automated your tests using Selenium, the JUnit-based test framework for web applications. Run your tests.

Submission Submit four items in class, on paper:

1. Your input domain model

2. Your test designs, including the values and expected results, at the design abstraction level

3. Your automated tests

4. A screen shot and printout of the results of running your tests Grading We will grade on several factors.

• (25 pts) The quality of your input domain model

• (20 pts) Proper use of BCC

• (25 pts) Correct implementation of your automated tests

• (20 pts) Results of running your tests

• (10 pts) Other factors to be determined while grading such as peer evaluation

Explanation / Answer

Java->Checkfilehashfile.java

package main.java.actions;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.IOException;
public class CheckFileHash {
private static final Logger LOG = Logger.getLogger(CheckFileHash.class);
private HashType typeOfHash = null;
private String expectedFileHash = null;
private File fileToCheck = null;

public void fileToCheck(File fileToCheck) throws FileNotFoundException {
if (!fileToCheck.exists())
throw new FileNotFoundException(fileToCheck + " does not exist!");
this.fileToCheck = fileToCheck;
}
public void hashDetails(String hash, HashType hashType) {
this.expectedFileHash = hash;
this.typeOfHash = hashType;
}
public boolean hasAValidHash() throws IOException {
if (this.fileToCheck == null)
throw new FileNotFoundException("File to check has not been set!");
if (this.expectedFileHash == null || this.typeOfHash == null)
throw new NullPointerException("Hash details have not been set!");
String actualFileHash = "";
boolean isHashValid = false;
switch (this.typeOfHash) {
case MD5:
actualFileHash = DigestUtils.md5Hex(new FileInputStream(
this.fileToCheck));
if (this.expectedFileHash.equals(actualFileHash))
isHashValid = true;
break;
case SHA1:
actualFileHash = DigestUtils.shaHex(new FileInputStream(
this.fileToCheck));
if (this.expectedFileHash.equals(actualFileHash))
isHashValid = true;
break;
}
return isHashValid;
}}
FileDownloader.java
package main.java.actions;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class FileDownloader {
private static final Logger LOG = Logger.getLogger(FileDownloader.class);
private WebDriver driver;
private String localDownloadPath = System.getProperty("java.io.tmpdir");
private boolean followRedirects = true;
private boolean mimicWebDriverCookieState = true;
private int httpStatusOfLastDownloadAttempt = 0;
public FileDownloader(WebDriver driverObject) {
this.driver = driverObject;
LOG.setLevel(Level.INFO);
}
public void followRedirectsWhenDownloading(boolean value) {
this.followRedirects = value;
}
public String localDownloadPath() {
return this.localDownloadPath;
}
public void localDownloadPath(String filePath) {
this.localDownloadPath = filePath;
}
public String downloadFile(WebElement element) throws Exception {
return downloader(element, "href");
}
public String downloadImage(WebElement element) throws Exception {
return downloader(element, "src");
}
public int getHTTPStatusOfLastDownloadAttempt() {
return this.httpStatusOfLastDownloadAttempt;
}
public void mimicWebDriverCookieState(boolean value) {
this.mimicWebDriverCookieState = value;
}
private BasicCookieStore mimicCookieState(Set<Cookie> seleniumCookieSet) {
BasicCookieStore mimicWebDriverCookieStore = new BasicCookieStore();
for (Cookie seleniumCookie : seleniumCookieSet) {
BasicClientCookie duplicateCookie = new BasicClientCookie(
seleniumCookie.getName(), seleniumCookie.getValue());
duplicateCookie.setDomain(seleniumCookie.getDomain());
duplicateCookie.setSecure(seleniumCookie.isSecure());
duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
duplicateCookie.setPath(seleniumCookie.getPath());
mimicWebDriverCookieStore.addCookie(duplicateCookie);
}
return mimicWebDriverCookieStore;
}
private String downloader(WebElement element, String attribute)

throws IOException, NullPointerException, URISyntaxException {

String fileToDownloadLocation = element.getAttribute(attribute);

if (fileToDownloadLocation.trim().equals(""))

throw new NullPointerException(
"The element you have specified does not link to anything!");
URL fileToDownload = new URL(fileToDownloadLocation);
File downloadedFile = new File(this.localDownloadPath
+ fileToDownload.getFile().replaceFirst("/|\\", ""));
if (downloadedFile.canWrite() == false) {
downloadedFile.setWritable(true);
}
HttpClient client = new DefaultHttpClient();
BasicHttpContext localContext = new BasicHttpContext();
if (this.mimicWebDriverCookieState) {
localContext.setAttribute(ClientContext.COOKIE_STORE,
mimicCookieState(this.driver.manage().getCookies()));
}
HttpGet httpget = new HttpGet(fileToDownload.toURI());
HttpParams httpRequestParameters = httpget.getParams();
httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS,
this.followRedirects);
httpget.setParams(httpRequestParameters);
HttpResponse response = client.execute(httpget, localContext);
this.httpStatusOfLastDownloadAttempt = response.getStatusLine()
.getStatusCode();
FileUtils.copyInputStreamToFile(response.getEntity().getContent(),
downloadedFile);
response.getEntity().getContent().close();
return downloadedFile.getAbsolutePath();
}}
FileDownloadTest.Java
package main.java.actions;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class FileDownloadTest {
@Test
public void downloadAFile() throws Exception {
System.setProperty(
"webdriver.ie.driver",
"D:\Softwares\Selenium_Materials\Selenium_Materials\IEDriverServer_Win32_2.33.0\IEDriverServer.exe");
WebDriver driver;
driver = new InternetExplorerDriver();
driver.get("http://iscls1apps/INFYDIR/");
driver.findElement(By.id("_ctl0_ContentPlaceHolder1_txtSearch"))
.sendKeys("demo_v_v");
driver.findElement(By.id("_ctl0_ContentPlaceHolder1_lnkSearch"))
.click();
Thread.sleep(20000);
WebElement downloadLink = null;
int count = 0;
while (downloadLink == null) {
downloadLink = driver.findElement(By
.id("_ctl0_ContentPlaceHolder1_lnkDownload"));
count++;
if (count == 50) {
break;
}
}
// WebElement downloadLink = driver.findElement(By
// .id("_ctl0_ContentPlaceHolder1_lnkDownload"));
FileDownloader downloadTestFile = new FileDownloader(driver);
String downloadedFileAbsoluteLocation = downloadTestFile
.downloadFile(downloadLink);
System.out.println("downloadTestFile.downloadFile(downloadLink);"
+ downloadTestFile.downloadFile(downloadLink));
Assert.assertTrue(new File(downloadedFileAbsoluteLocation).exists());
// assertThat(downloadTestFile.getHTTPStatusOfLastDownloadAttempt(),
// is(equalTo(200)));
}
@Test
public void checkValidMD5Hash() throws Exception {
CheckFileHash fileToCheck = new CheckFileHash();
fileToCheck.fileToCheck(new File(System.getProperty("java.io.tmpdir")));
fileToCheck.hashDetails("617bfc4b78b03a0f61c98188376d2a6d",
HashType.MD5);
Assert.assertTrue(fileToCheck.hasAValidHash());
}}
Hastype.java
package main.java.actions;
public enum HashType {
MD5, SHA1;
}
methodtype.java
package main.java.actions;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import main.java.model.MethodParameters;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import main.java.util.MainTestNG;
import main.java.util.ReadElementLocators;
import main.java.util.WebDriverClass;
public class MethodType {
List<WebElement> listOfElements = new ArrayList<WebElement>();
WebElement element;
ReadElementLocators read = new ReadElementLocators();
String alertText = null;
String titleOfPage = null;
public void methodExecutor(String methodType, String objectLocators,
String actionType, String data) {
MethodParameters mModel = new MethodParameters();
mModel.setMethodType(methodType);
mModel.setObjectLocators(objectLocators);
mModel.setActionType(actionType);
mModel.setData(data);
MainTestNG.LOGGER
.info("methodType= " + methodType + "objectLocators="
+ objectLocators + "actionType=" + actionType
+ "data= " + data);
switch (methodType) {
case "ID":
findElementById(objectLocators);
mModel.setElement(listOfElements);
findMethod(methodType, objectLocators, actionType, data, mModel);
break;
case "NAME":
findElementByName(objectLocators);
mModel.setElement(listOfElements);
findMethod(methodType, objectLocators, actionType, data, mModel);
break;
case "XPATH":
findElementByXpath(objectLocators);
mModel.setElement(listOfElements);
findMethod(methodType, objectLocators, actionType, data, mModel);
break;
case "CSS":
findElementByCssSelector(objectLocators);
mModel.setElement(listOfElements);
findMethod(methodType, objectLocators, actionType, data, mModel);
break;
default:
if (actionType.contains(":")) {
String[] actsplit = actionType.split(":");
mModel.setActionType(actsplit[1]);
actionType = actsplit[0];
System.out.println(actsplit[1]);
System.out.println(actsplit[0]);
}
findMethod(methodType, objectLocators, actionType, data, mModel);
break;
}
}
public void findMethod(String methodType, String objectLocators,
String actionType, String data, MethodParameters model) {
Class cl = null;
try {
cl = (Class) Class.forName("main.java.actions.MethodType");
main.java.actions.MethodType clName = (MethodType) cl.newInstance();
Method[] methods = cl.getMethods();
Method methodName = findMethods(actionType, methods);
methodName.invoke(clName, (Object) model)
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
MainTestNG.LOGGER
.info("exception occured in finding methods, method name is incorrect"
+ e);
} catch (Exception e) {MainTestNG.LOGGER
.info("exception occured in finding methods, method name is incorrect"
+ e);
}
}

private void findElementByCssSelector(String objectLocators) {
WebDriverWait wait = new WebDriverWait(WebDriverClass.getDriver(), 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By
.cssSelector(objectLocators)));
List<WebElement> list1 = WebDriverClass.getInstance().findElements(
By.cssSelector(objectLocators));
listOfElements = list1;
}

public void findElementById(String objectLocators) {
WebDriverWait wait = new WebDriverWait(WebDriverClass.getDriver(), 30);
List<WebElement> list1 = wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By.id(objectLocators)));
listOfElements = list1;}
public void findElementByXpath(String objectLocators) {
WebDriverWait wait = WebDriverWait(WebDriverClass.getDriver(), 30);
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By
.xpath(objectLocators)));
List<WebElement> list1 = wait
until(ExpectedConditions.visibilityOfAllElements(WebDriverClass
.getDriver().findElements(By.xpath(objectLocators))));
istOfElements = list1;
public void findElementByName(String objectLocators) {
MainTestNG.LOGGER.info("findElementByName==" + objectLocators);
WebDriverWait wait = new WebDriverWait(WebDriverClass.getDriver(), 30);
wait.until(ExpectedConditions.visibilityOfAllElements(WebDriverClass
.getDriver().findElements(By.name(objectLocators))));
MainTestNG.LOGGER.info("element found==" + objectLocators);
List<WebElement> list1 = WebDriverClass.getInstance().findElements(
By.name(objectLocators));
MainTestNG.LOGGER.info("list size" + list1.size());
listOfElements = list1;
}
public static Method findMethods(String methodName, Method[] methods) {
for (int i = 0; i < methods.length; i++) {
if (methodName.equalsIgnoreCase(methods[i].getName().toString())) {
return methods[i];
}
}
return null;
}


public void click(MethodParameters model) {
WebDriverWait wait = new WebDriverWait(WebDriverClass.getDriver(), 30);

wait.until(
ExpectedConditions.elementToBeClickable(model.getElement().get(

0))).click();
MainTestNG.LOGGER.info("click method started"

+ model.getObjectLocators());

MainTestNG.LOGGER.info("click method completed");

}
public void submit(MethodParameters model) {

MainTestNG.LOGGER.info("submit method started"

+ model.getObjectLocators());

model.getElement().get(0).submit();

MainTestNG.LOGGER.info("submit method end");

}
public void enterText(MethodParameters model) {
MainTestNG.LOGGER
.info(" inside enterText(), data to entered into the text=="

+ model.getData());

System.out.println("model.getElement().get(0)=="

+ model.getElement().get(0));

model.getElement().get(0).sendKeys(model.getData());

MainTestNG.LOGGER.info("enterText() exit");

}
public void readTextFieldValue(MethodParameters model) {
MainTestNG.LOGGER.info("inside readTextFieldValue()"
+ model.getObjectLocators());
model.getElement().get(0).getAttribute("value");

MainTestNG.LOGGER.info("end of readTextFieldValue");
}
public void alertAccept(MethodParameters model) {
WebDriverWait wait = new WebDriverWait(WebDriverClass.getDriver(), 30);wait.until(ExpectedConditions.alertIsPresent());
MainTestNG.LOGGER.info("inside alertAccept()");
wait1(2000);
Alert alert = WebDriverClass.getInstance().switchTo().alert();wait1(2000);

alert.accept();
MainTestNG.LOGGER.info("completed alertAccept()");}
public void alertDismiss(MethodParameters model) {
WebDriverWait wait = new WebDriverWait(WebDriverClass.getDriver(), 30);
wait.until(ExpectedConditions.alertIsPresent());
MainTestNG.LOGGER.info("inside alertDismiss()");

wait1(2000);
model.getElement().get(0).click();
Alert alert = WebDriverClass.getInstance().switchTo().alert();

wait1(2000);
alert.dismiss();

}

/**

*Get the title of the page and verify the title

*/

public void verifyTitleOfPage(MethodParameters model) {

MainTestNG.LOGGER.info("inside verifyTitleOfPage()" + "title=="

+ WebDriverClass.getInstance().getTitle() + "data from excel="

+ model.getData());

wait1(2000);

String actual = WebDriverClass.getInstance().getTitle().toString();

String expected = model.getData().toString();

Assert.assertEquals(actual, expected);

MainTestNG.LOGGER

.info("assert verification successful verifyTitleOfPage()");

}

/**

*Make the driver to wait for specified amount of time

*/

public void wait1(long i) {

try {

Thread.sleep(i);

} catch (InterruptedException e) {

MainTestNG.LOGGER.severe("InvalidFormatException" + e);

}

}

/**

*Select from the drop down list,if the drop down element tag is "SELECT" then use this method

*/

public void selectDropDownByVisibleText(MethodParameters model) {

wait1(2000);

MainTestNG.LOGGER.info("inside selectDropDownByVisibleText");

WebDriverWait wait = new WebDriverWait(WebDriverClass.getDriver(), 30);

wait.pollingEvery(2, TimeUnit.SECONDS).until(

ExpectedConditions.elementToBeClickable(model.getElement().get(

0)));

Select sel = new Select(model.getElement().get(0));

sel.selectByVisibleText(model.getData());

wait1(2000);

}

/**

*Select the value from a dropdown list by its index

*/

public void selectDropDownByIndex(MethodParameters model) {

MainTestNG.LOGGER.info("inside selectDropDownByIndex");

Select sel = new Select(model.getElement().get(0));

sel.selectByIndex(Integer.parseInt(model.getData()));

}

/**

*Select the value from a dropdown list by its value

*/

public void selectDropDownByValue(MethodParameters model) {

MainTestNG.LOGGER.info("inside selectDropDownByValue");

Select sel = new Select(model.getElement().get(0));

sel.selectByValue(model.getData());

}

/**

*Switch To frame( html inside another html)

*/

public void switchToFrame(MethodParameters model) {

MainTestNG.LOGGER.info("inside switchToFrame");

WebDriverClass.getInstance().switchTo()

.frame(model.getElement().get(0));

}

/**

*Switch back to previous frame or html

*/

public void switchOutOfFrame(MethodParameters model) {

MainTestNG.LOGGER.info("inside switchOutOfFrame");

WebDriverClass.getInstance().switchTo().defaultContent();

}

/**

*Select the multiple value from a dropdown list

*/

public void selectFromListDropDown(MethodParameters model) {

MainTestNG.LOGGER.info("inside selectFromListDropDown");

wait1(2000);

for (WebElement element1 : model.getElement()) {

if (element1.getText().equals(model.getData())) {

element1.click();

break;

}

}

wait1(2000);

}

/**

*Navigate to next page

*/

public void moveToNextPage(MethodParameters model) {

WebDriverClass.getInstance().navigate().forward();

}

/**

*Navigate to previous page

*/

public void moveToPreviousPage(MethodParameters model) {

WebDriverClass.getInstance().navigate().back();

}

/**

*Maximize the window

*/

public void maximizeWindow(MethodParameters model) {

WebDriverClass.getInstance().manage().window().maximize();

}

/**

*Reads the text present in the web element

*/

public void readText(MethodParameters model) {

MainTestNG.LOGGER

.info("getText() method called and value of getText==*************"

+ model.getElement().get(0).getText());

model.getElement().get(0).getText();

MainTestNG.LOGGER.info("readText completed");

}

/**

*Quit the application

*/

public void quit(MethodParameters model) {

WebDriverClass.getInstance().quit();

}

/**

*Closes the driver

*/

public void close(MethodParameters model) {

WebDriverClass.getInstance().close();

}

/**

*Checks that the element is displayed in the current web page

*/

public void isDisplayed(MethodParameters model) {

model.getElement().get(0).isDisplayed();

}

/**

*Checks that the element is enabled in the current web page

*/

public void isEnabled(MethodParameters model) {

model.getElement().get(0).isEnabled();

}

/**

*Selects a radio button

*/

public void selectRadioButton(MethodParameters model) {

model.getElement().get(0).click();

}

/**

*Refresh the current web page

*/

public void refreshPage(MethodParameters model) {

WebDriverClass.getInstance().navigate().refresh();

}

/**

*Switch back to the parent window

*/

public void switchToParentWindow(MethodParameters model) {

String parentWindow = WebDriverClass.getInstance().getWindowHandle();

WebDriverClass.getInstance().switchTo().window(parentWindow);

}

/**

*Switche to the child window

*/

public void switchToChildWindow(MethodParameters model) {

model.getElement().get(0).click();

String parent = WebDriverClass.getInstance().getWindowHandle();

Set<String> windows = WebDriverClass.getInstance().getWindowHandles();

try {

if (windows.size() > 1) {

for (String child : windows) {

if (!child.equals(parent)) {

if (WebDriverClass.getInstance().switchTo()

.window(child).getTitle()

.equals(model.getData())) {

WebDriverClass.getInstance().switchTo()

.window(child);

}

}

}

}

} catch (Exception e) {

throw new RuntimeException("Exception", e);

}

}

/**

*Scrolls down the page till the element is visible

*/

public void scrollElementIntoView(MethodParameters model) {

wait1(1000);

MainTestNG.LOGGER.info("scrollElementIntoView started");

((JavascriptExecutor) WebDriverClass.getDriver())

.executeScript("arguments[0].scrollIntoView(true);", model

.getElement().get(0));

wait1(1000);

}

/**

*Scrolls down the page till the element is visible and clicks on the

*element

*/

public void scrollElementIntoViewClick(MethodParameters model) {

Actions action = new Actions(WebDriverClass.getDriver());

action.moveToElement(model.getElement().get(0)).click().perform();

}

/**

*Reads the url of current web page

*/

public void readUrlOfPage(MethodParameters model) {

WebDriverClass.getInstance().getCurrentUrl();

}

/**

*Navigates to the specified url

*/

public void navigateToURL(MethodParameters model) {

WebDriverClass.getInstance().navigate().to(model.getData());

}

public static WebElement waitForElement(By by) {

int count = 0;

WebDriverWait wait = null;

while (!(wait.until(ExpectedConditions.presenceOfElementLocated(by))

.isDisplayed())) {

wait = new WebDriverWait(WebDriverClass.getInstance(), 60);

wait.pollingEvery(5, TimeUnit.MILLISECONDS);

wait.until(ExpectedConditions.visibilityOfElementLocated(by))

.isDisplayed();

wait.until(ExpectedConditions.presenceOfElementLocated(by))

.isDisplayed();

count++;

if (count == 100) {

break;

}

return wait.until(ExpectedConditions.presenceOfElementLocated(by));

}

return wait.until(ExpectedConditions.presenceOfElementLocated(by));

}

/**

*Provide Login name for window authentication

*/

public static void windowAuthenticationLoginName(MethodParameters model) {

Alert alert = WebDriverClass.getDriver().switchTo().alert();

alert.sendKeys(model.getData());

}

/**

*Provide password for window authentication

*/

public static void windowAuthenticationPassword(MethodParameters model) {

Robot robot;

try {

robot = new Robot();

robot.keyPress(KeyEvent.VK_TAB);

String letter = model.getData();

for (int i = 0; i < letter.length(); i++) {

boolean upperCase = Character.isUpperCase(letter.charAt(i));

String KeyVal = Character.toString(letter.charAt(i));

String variableName = "VK_" + KeyVal.toUpperCase();

Class clazz = KeyEvent.class;

Field field = clazz.getField(variableName);

int keyCode = field.getInt(null);

if (upperCase){

robot.keyPress(KeyEvent.VK_SHIFT);

}

robot.keyPress(keyCode);

robot.keyRelease(keyCode);

if (upperCase){

robot.keyRelease(KeyEvent.VK_SHIFT);

}

}

robot.keyPress(KeyEvent.VK_ENTER);

} catch (AWTException e) {

MainTestNG.LOGGER.severe(e.getMessage());

} catch (NoSuchFieldException e) {

MainTestNG.LOGGER.severe(e.getMessage());

} catch (SecurityException e) {

MainTestNG.LOGGER.severe(e.getMessage());

} catch (IllegalArgumentException e) {

MainTestNG.LOGGER.severe(e.getMessage());

} catch (IllegalAccessException e) {

MainTestNG.LOGGER.severe(e.getMessage());

}

}

/**

* @param model

* Lets say there is header menu bar, on hovering the mouse, drop down should be displayed

*/

public void dropDownByMouseHover(MethodParameters model) {

Actions action = new Actions(WebDriverClass.getInstance());

action.moveToElement(model.getElement().get(0)).perform();

WebElement subElement = WebDriverClass.getInstance().findElement(

By.xpath(model.getData()));

action.moveToElement(subElement);

action.click().build().perform();

}

/**

*verifies the data present in the text field

*/

public void verifyTextFieldData(MethodParameters model) {

Assert.assertEquals(model.getElement().get(0).getAttribute("value"),

model.getData());

}

/**

* @param model

* Read title of the page and verify it

*/

public void readTitleOfPage(MethodParameters model) {

if (!(titleOfPage == null)) {

titleOfPage = null;

}

titleOfPage = WebDriverClass.getInstance().getTitle();

}

/**

* @param model

* File upload in IE browser.

*/

public void fileUploadinIE(MethodParameters model) {

model.getElement().get(0).click();

StringSelection ss = new StringSelection(model.getData());

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

Robot r;

try {

r = new Robot();

r.keyPress(KeyEvent.VK_ENTER);

r.keyRelease(KeyEvent.VK_ENTER);

r.keyPress(KeyEvent.VK_CONTROL);

r.keyPress(KeyEvent.VK_V);

r.keyRelease(KeyEvent.VK_V);

r.keyRelease(KeyEvent.VK_CONTROL);

r.keyPress(KeyEvent.VK_ENTER);

r.keyRelease(KeyEvent.VK_ENTER);

} catch (AWTException e) {

MainTestNG.LOGGER.severe(e.getMessage());

}

}

/**

* @param model

* Verify the alert text

*/

public void verifyalertText(MethodParameters model) {

model.getElement().get(0).click();

wait1(1000);

Alert alert = WebDriverClass.getInstance().switchTo().alert();

wait1(1000);

if (!(alertText == null)) {

alertText = null;

}

alertText = alert.getText();

Assert.assertEquals(alertText.toString(), model.getData());

alert.accept();

}

/**

* @param model

* SSL errors that appear on IE browser can be resolved

*/

public void certificateErrorsIE(MethodParameters model) {

WebDriverClass

.getDriver()

.navigate()

.to("javascript:document.getElementById('overridelink').click()");

}

/**

* @param model

* Not tested

*/

public void DragAndDrop(MethodParameters model) {

String[] actType = model.getActionType().split("$");

WebElement sourceElement = WebDriverClass.getDriver().findElement(

By.xpath(actType[0]));

WebElement destinationElement = WebDriverClass.getDriver().findElement(

By.xpath(actType[1]));

Actions action = new Actions(WebDriverClass.getDriver());

action.dragAndDrop(sourceElement, destinationElement).build().perform();

}

/**

* @param model

* clear the content of the text field

*/

public void clear(MethodParameters model) {

wait1(2000);

WebDriverWait wait = new WebDriverWait(WebDriverClass.getDriver(), 60);

wait.until(ExpectedConditions.visibilityOf(model.getElement().get(0)));

model.getElement().get(0).clear();

}

/**

*Makes the driver to sleep for specified time

*/

public void sleep(MethodParameters model) {

try {

Integer i = Integer.parseInt(model.getData());

System.out.println(i);

Thread.sleep(i);

} catch (InterruptedException e) {

MainTestNG.LOGGER.info("InterruptedException" + e.getMessage());

}

}

/**

*Verifies the Text present in the element

*/

public void verifyText(MethodParameters model) {

MainTestNG.LOGGER.info("model.getElement().get(0).getText()**********"

+ model.getElement().get(0).getText());

MainTestNG.LOGGER.info("model.getData()**********" + model.getData());

Assert.assertEquals(model.getData(), model.getElement().get(0)

.getText().toString());

MainTestNG.LOGGER.info("verify text completed");

}

/**

*Verifies that the particular file is exists or not

*/

public void verifyFileExists(MethodParameters model) {

try {

File file = new File(model.getData());

if (file.exists() && !(file.isDirectory() && file.isFile())) {

Assert.assertEquals(file.getAbsoluteFile(), model.getData());

}

} catch (Exception e) {

throw e;

}

}

/**

*Downloads a file from IE browser

*/

public void downloadFileIE(MethodParameters model) {

FileDownloader downloadTestFile = new FileDownloader(

WebDriverClass.getDriver());

String downloadedFileAbsoluteLocation;

try {

downloadedFileAbsoluteLocation = downloadTestFile

.downloadFile(model.getElement().get(0));

Assert.assertTrue(new File(downloadedFileAbsoluteLocation).exists());

} catch (Exception e) {

MainTestNG.LOGGER.info("exception occured");

}

}

/**

* @param model

* Not tested

*/

public void webTableClick(MethodParameters model) {

String[] actType = model.getActionType().split("\$");

WebElement mytable = WebDriverClass.getDriver().findElement(

By.xpath(actType[0]));

List<WebElement> rowstable = mytable.findElements(By.tagName("tr"));

int rows_count = rowstable.size();

for (int row = 0; row < rows_count; row++) {

List<WebElement> Columnsrow = rowstable.get(row).findElements(

By.tagName("td"));

int columnscount = Columnsrow.size();

for (int column = 0; column < columnscount; column++) {

String celtext = Columnsrow.get(column).getText();

celtext.getClass();

}

}

}

/**

* @param model

* Select date from date picker

*/

public void selectDateFromCalendar(MethodParameters model) {

String[] actionType = model.getActionType().split("$$");

String[] data = model.getData().split("/");

List<String> monthList = Arrays.asList("January", "February", "March",

"April", "May", "June", "July", "August", "September",

"October", "November", "December");

int expMonth;

int expYear;

String expDate = null;

// Calendar Month and Year

String calMonth = null;

String calYear = null;

boolean dateNotFound;

// WebDriverClass.getDriver()

// .findElement(By.xpath(".//*[@id='ui-datepicker-div']")).click();

WebDriverClass.getDriver().findElement(By.xpath(actionType[0])).click();

dateNotFound = true;

// Set your expected date, month and year.

expDate = data[0];

expMonth = Integer.parseInt(data[1]);

expYear = Integer.parseInt(data[2]);

// This loop will be executed continuously till dateNotFound Is true.

while (dateNotFound) {

// Retrieve current selected month name from date picker popup.

calMonth = WebDriverClass.getDriver()

.findElement(By.className("ui-datepicker-month")).getText();

// Retrieve current selected year name from date picker popup.

calYear = WebDriverClass.getDriver()

.findElement(By.className("ui-datepicker-year")).getText();

/*

* If current selected month and year are same as expected month and

* year then go Inside this condition.

*/

if (monthList.indexOf(calMonth) + 1 == expMonth

&& (expYear == Integer.parseInt(calYear))) {

/*

* Call selectDate function with date to select and set

* dateNotFound flag to false.

*/

selectDate(expDate);

dateNotFound = false;

}

// If current selected month and year are less than expected month

// and year then go Inside this condition.

else if (monthList.indexOf(calMonth) + 1 < expMonth

&& (expYear == Integer.parseInt(calYear))

|| expYear > Integer.parseInt(calYear)) {

// Click on next button of date picker.

/*

* WebDriverClass .getDriver() .findElement(

* By.xpath(".//*[@id='ui-datepicker-div']/div[2]/div/a/span"))

* .click();

*/

WebDriverClass.getDriver().findElement(By.xpath(actionType[1]))

.click();

}

// If current selected month and year are greater than expected

// month and year then go Inside this condition.

else if (monthList.indexOf(calMonth) + 1 > expMonth

&& (expYear == Integer.parseInt(calYear))

|| expYear < Integer.parseInt(calYear)) {

// Click on previous button of date picker.

/*

* WebDriverClass .getDriver() .findElement(

* By.xpath(".//*[@id='ui-datepicker-div']/div[1]/div/a/span"))

* .click();

*/

WebDriverClass.getDriver().findElement(By.xpath(actionType[2]))

.click();

}

}

wait1(3000);

}

/**

*Selects the Date

*/

public void selectDate(String date) {

WebElement datePicker = WebDriverClass.getDriver().findElement(

By.id("ui-datepicker-div"));

List<WebElement> noOfColumns = datePicker

.findElements(By.tagName("td"));

// Loop will rotate till expected date not found.

for (WebElement cell : noOfColumns) {

// Select the date from date picker when condition match.

if (cell.getText().equals(date)) {

cell.findElement(By.linkText(date)).click();

break;

}

}

}

/**

*Double clicks on the particular element

*/

public void doubleClick(MethodParameters model) {

Actions action = new Actions(WebDriverClass.getDriver());

action.doubleClick((WebElement) model.getElement()).perform();

}

/**

*Mouse hovering on the element is performed

*/

public void singleMouseHover(MethodParameters model) {

Actions action = new Actions(WebDriverClass.getDriver());

action.moveToElement((WebElement) model.getElement()).perform();

}

/**

*Right clicks on the element

*/

public void rightClick(MethodParameters model) {

Actions action = new Actions(WebDriverClass.getDriver());

action.contextClick((WebElement) model.getElement()).perform();

}

/**

*Select the check boxes

*/

public void selectCheckBox(MethodParameters model) {

boolean res = true;

while (!model.getElement().get(0).isSelected()) {

model.getElement().get(0).click();

if (model.getElement().get(0).isSelected()) {

res = false;

break;

}

}

}

/**

*Un-check the check box

*/

public void deselectCheckBox(MethodParameters model) {

boolean res = true;

while (model.getElement().get(0).isSelected()) {

model.getElement().get(0).click();

if (!model.getElement().get(0).isSelected()) {

res = false;

break;

}

}

}

/**

*Un-check the all check boxes

*/

public void deselectAllCheckbox(MethodParameters model) {

List<WebElement> list = model.getElement();

for (WebElement element : list) {

if (element.isSelected()) {

element.click();

}

}

}

/**

*Selects all the check boxes

*/

public void selectAllCheckbox(MethodParameters model) {

List<WebElement> list = model.getElement();

for (WebElement element : list) {

if (!element.isSelected()) {

element.click();

}

}

}

/**

*Verifies that the particular check box is selected

*/

public void verifyCheckBoxSelected(MethodParameters model) {

Assert.assertTrue(model.getElement().get(0).isSelected());

}

/**

*Verifies whether all the check box is selected

*/

public void verifyAllCheckBoxSelected(MethodParameters model) {

for (WebElement element : model.getElement()) {

Assert.assertTrue(element.isSelected(), "check box is selected");

}

}

/**

*Verifies that all the check boxes is not selected

*/

public void verifyAllCheckBoxNotSelected(MethodParameters model) {

for (WebElement element : model.getElement()) {

Assert.assertFalse(element.isSelected(), "check box not selected");

}

}

/**

* @param model

* File download from Auto It

*/

public void filedownloadAUTOIT(MethodParameters model){

try {

Runtime.getRuntime().exec(model.getData());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}}}

CaptureObjectpoperties.java

package main.java.model;

/**

* The CapturedObjectPropModel class is used as a bean class to get the Captured

* objects properties in the excel sheet

*

* @author Shilpashree_V

* @version 1.0

* @since February 2015

*

*/

public class CapturedObjectPropModel {

String page=null;

String name=null;

String property=null;

String value=null;

public void setPage(String page){

this.page=page;

}

public String getPage(){

return page;

}

public void setName(String name){

this.name=name;

}

public String getName(){

return name;

}

public void setProperty(String property){

this.property=property;

}

public String getProperty(){

return property;

}

public void setValue(String value){

this.value=value;

}

public String getValue(){

return value;

}}

Methodparameters.jaa

package main.java.model;

/**

* The MethodParameters class is used as a bean class to get the details for actions

* performed on the element

*

* @author Shilpashree_V

* @version 1.0

* @since February 2015

*

*/

import java.util.ArrayList;

import java.util.List;

import org.openqa.selenium.WebElement;

public class MethodParameters {

List<WebElement> elements = new ArrayList<WebElement>();

String methodType = null;

String actionType = null;

String data = null;

String objectLocators = null;

public List<WebElement> getElement() {

return elements;

}

public void setElement(List<WebElement> element) {

this.elements = element;

}

public String getMethodType() {

return methodType;

}

public void setMethodType(String methodType) {

this.methodType = methodType;

}

public String getActionType() {

return actionType;

}

public void setActionType(String actionType) {

this.actionType = actionType;

}

public String getData() {

return data;

}

public void setData(String data) {

this.data = data;

}

public String getObjectLocators() {

return objectLocators;

}

public void setObjectLocators(String objectLocators) {

this.objectLocators = objectLocators;

}}

testcase.java

package main.java.model;

/**

* The TestCase class is used as a bean class to get the details of each test case

*

* @author Shilpashree_V

* @version 1.0

* @since February 2015

*

*/

import java.util.ArrayList;

import java.util.List;

public class TestCase {

String testCaseName = null;

List<String> testStepId = new ArrayList<String>();

List<String> testSteps = new ArrayList<String>();

List<String> methodType = new ArrayList<String>();

List<String> ojectNameFromPropertiesFile = new ArrayList<String>();

List<String> actionType = new ArrayList<String>();

String>

List testData = new ArrayList();

public String getTestCaseName() {

return testCaseName;

}

public void setTestCaseName(String testCaseName) {

this.testCaseName = testCaseName;

}

public void addTestSteps(String steps) {

testSteps.add(steps);

}

public List<String> getTestSteps() {

return testSteps;

}

public void setMethodType(String methodype) {

methodType.add(methodype);

}

public List<String> getMethodType() {

return methodType;

}

public void setObjectNameFromPropertiesFile(String name) {

ojectNameFromPropertiesFile.add(name);

}

public List<String> getObjectNameFromPropertiesFile() {

return ojectNameFromPropertiesFile;

}

public void setActionType(String actiontype) {

actionType.add(actiontype);

}

public List<String> getActionType() {

return actionType;

}

public void setTestData(String testdata) {

testData.add(testdata);

}

public List<String> getTestData() {

return testData;

}

public List<String> getTestStepId() {

return testStepId;

}

public void setTestStepId(String tststepId) {

testStepId.add(tststepId);

}

public String getOnFail() {

return onFail;

}

public void setOnFail(String onFail) {

this.onFail = onFail;

}}

Excelaction.java:

package main.java.util;

/**

* The ExcelAction class is used to store the data from the excel into map

*

* @author Shilpashree_V

* @version 1.0

* @since February 2015

*

*/

import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import main.java.model.CapturedObjectPropModel;

import main.java.model.TestCase;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import org.openqa.selenium.WebDriver;

import org.testng.Reporter;

import main.java.actions.MethodType;

public class ExcelAction {

WebDriver driver;

static ExcelLibrary excel = new ExcelLibrary();

static ReadConfigProperty config = new ReadConfigProperty();

static Map<String, Object> testCaseSheet = new HashMap<String, Object>();

static Map<String, String> readFromConfigFile = new HashMap<String, String>();

static Map<String, Object> testSuiteSheet = new HashMap<String, Object>();

static Map<String, Object> testDataSheet = new HashMap<String, Object>();

static Map<String, Object> capObjPropSheet = new HashMap<String, Object>();

static List listOfTestCases = new ArrayList();

int numberOfTimeExecution = 0;

MethodType methodtype = new MethodType();

String testcasepth = "TestCasePath";

public static void main(String[] args) {

ExcelAction action = new ExcelAction();

action.readCapturedObjectProperties();

action.readLocators("PAGE", "SEARCH_BOX");

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote