0
点赞
收藏
分享

微信扫一扫

Selenium+Java+Appium+TestNg环境搭建——Web自动化测试与HTML5测试(4)

洲行 2022-11-15 阅读 61

Web端启动源码
package com.zenni.utils;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.Writer;

import java.net.URL;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Date;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Set;

import java.util.concurrent.TimeUnit;

import java.util.regex.Matcher;

import java.util.regex.Pattern;


import jxl.Workbook;

import jxl.write.Label;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;


import org.apache.commons.io.FileUtils;

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.Keys;

import org.openqa.selenium.NoSuchElementException;

import org.openqa.selenium.NoSuchFrameException;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.TimeoutException;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.firefox.FirefoxProfile;

import org.openqa.selenium.firefox.internal.ProfilesIni;

import org.openqa.selenium.ie.InternetExplorerDriver;

import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.support.ui.ExpectedCondition;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.Select;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.Reporter;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.DataProvider;


import com.zenni.consts.Consts;

import com.zenni.consts.ZenniConsts;

import com.zenni.pageobject.HomePage;

import com.zenni.pageobject.Order;

import com.zenni.pageobject.ShoppingCart;


import com.thoughtworks.selenium.SeleniumException;

import com.thoughtworks.selenium.Wait;


/**

* <b>Name:</b> StartingSelenium</br> <b>Description: </b>This class is used to

* start/stop webdriver</br>

* @author <i>Ron Zhang</i>

*/

public class StartingSelenium {


protected static WebDriver driver;

private static WebDriverWait wait;

// ***This parameter comes from Consts and set up the browser

private static String browser = Consts.startBrowser;

private static final String TASKLIST = "tasklist";

private static final String TASKKILL = "taskkill /F /IM ";


// ***Time out for WebDriverWait in second

private final static int WEBDRIVER_WAIT_TIMEOUT = 10;

// ***Time out for implicitlyWait in millisecond

private final static int IMPLICIT_WAIT_TIMEOUT = 500;

private static Set<String> availableWindows;



// ***This parameters for @DataProvider

public String className;

public String dataFileName;

private Class<?> fullClassName;


/**

* <b>Name: StartingSelenium</b></br> <b>Description:</b> This is

* constructor of this class to instantiate the class name for data

* provider.

*/

public StartingSelenium() {

fullClassName = this.getClass();

className = getClassName(fullClassName);

dataFileName = Consts.TEST_DATA_FILE;

}


/**

* <b>Name:</b> getClassName</br> <b>Description:</b> Get class name string

* of a specific class object

*

* @param className

* - class object

* @return class name string

*/

public static String getClassName(Class<?> className) {

String fqClassName = className.getName();

int charIndex;

charIndex = fqClassName.lastIndexOf('.') + 1;

if (charIndex > 0) {

fqClassName = fqClassName.substring(charIndex);

}

return fqClassName;

}


/**

* <b>Name:</b> getTestData</br> <b>Description:</b> Read and store input

* test data in HashMap.

*

* @return data for data provider

* @throws Exception

*/

@DataProvider(name = "getTestData")

public Object[][] getTestData() throws Exception {

return getDataProvider(dataFileName,className);

}


/**

* <b>Name:</b> getDataProvider</br> <b>Description:</b> Gets data from the

* excel sheet in form of hash map and converts it into 2 dimensional array.

*

* @param className

* @return two dimension array of data

*/

public static Object[][] getDataProvider(String dataFileName,String className) throws Exception {

ArrayList<HashMap<String, String>> testDataSheet = null;

String dataFilePath = null;

File f = new File("");

dataFilePath = f.getAbsolutePath().replace("\\", "/");

dataFilePath = dataFilePath + "/TestData/" + dataFileName + ".xlsx";

System.out.println(dataFilePath);



Reporter.log("Entering Test data from file: " + dataFileName, true);

ExcelParser ep = new ExcelParser(dataFilePath,className);

testDataSheet = ep.getTestData();

Object[][] result = null;

int numberTestCases = testDataSheet.size();

result = new Object[numberTestCases][];

for (int i = 0; i < numberTestCases; i++) {

result[i] = new Object[] { testDataSheet.get(i) };

}

Reporter.log("Exiting Test data", true);

return result;

}


/**

* <b>Name: launchBrowser</b>

* <p>

* <b>Description:</b> This is method to instantiate the driver.

*

* @return driver

*/

@BeforeMethod(alwaysRun = true)

public static WebDriver launchBrowser() {


if (driver == null) {

stopSelenium();

if (browser.contentEquals(Consts.FF)) {



ProfilesIni firefoxini = new ProfilesIni();

// firefoxProfile.setAcceptUntrustedCertificates(false);

FirefoxProfile firefoxProfile = firefoxini.getProfile("default");

firefoxProfile.setAssumeUntrustedCertificateIssuer(false);

driver = new FirefoxDriver(firefoxProfile);

}

if (browser.contentEquals(Consts.IE)) {

System.setProperty("webdriver.ie.driver", Consts.LIB_PATH

+ "/IEDriverServer.exe");

DesiredCapabilities caps = DesiredCapabilities

.internetExplorer();

// *** Set this flag to prevent the error about zoom set to 0%

caps.setCapability("ignoreZoomSetting", true);

caps.setCapability(

InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,

true);

driver = new InternetExplorerDriver(caps);

}

if (browser.contentEquals("*googlechrome")) {

System.setProperty("webdriver.chrome.driver", Consts.LIB_PATH

+ "/chromedriver.exe");

DesiredCapabilities capabilities = DesiredCapabilities.chrome();

// *** Enable plugin like java required by some app like

// ssltools

capabilities.setCapability("chrome.switches",

Arrays.asList("--always-authorize-plugins"));

driver = new ChromeDriver(capabilities);

}

driver.manage()

.timeouts()

.implicitlyWait(IMPLICIT_WAIT_TIMEOUT,

TimeUnit.MILLISECONDS);

driver.manage().window().maximize();

wait = new WebDriverWait(driver, WEBDRIVER_WAIT_TIMEOUT);

}

return driver;

}


/**

* <b>Name:</b> stopSelenium

* <p>

* <b>Description:</b> Stop selenium after each test case

*

* @throws Exception

*/

@AfterMethod(alwaysRun = true)

public static void stopSelenium() {

try {

stopSeleniumBrowser();

} catch (Exception e) {

org.testng.Assert.fail("Failed to stop selenium");

throw e;

}

// driver.close();

// driver.quit();

// driver = null;

}


/**

* <b>Name:</b> isProcessRunging

* <p>

* <b>Description:</b> this method check the process is running.

*

* @param processName

* @return none

* @throws Exception

*/

public static boolean isProcessRunging(String processName) throws Exception {

boolean result = false;

Process p = Runtime.getRuntime().exec(TASKLIST);

BufferedReader reader = new BufferedReader(new InputStreamReader(

p.getInputStream()));

String line;

while ((line = reader.readLine()) != null) {

if (line.contains(processName)) {

result = true;

break;

}

}

return result;

}


/**

* <b>Name:</b> killProcess

* <p>

* <b>Description:</b> this method kill the process.

*

* @return none

*/

public static void killProcess(String processName) throws Exception {

for (int i = 0; i < 5; i++) {

if (isProcessRunging(processName)) {

Runtime.getRuntime().exec(TASKKILL + processName);

Thread.sleep(2000);

} else

break;

}

}


/**

* <b>Name:</b> stopSelenium

* <p>

* <b>Description:</b> close all browser and stop driver.

*

* @return none

*/

public static void stopSeleniumBrowser() {

try {

closeBrowser(browser);

} catch (Exception e) {

e.printStackTrace();

}


if (driver != null) {

driver = null;

}

}


/**

* <b>Name:</b> closeBrowser

* <p>

* <b>Description:</b> will close all opened browser.

*

* @param browser

* @throws Exception

*/

public static void closeBrowser(String browser) throws Exception {

if (browser.equals(Consts.FF)) {

killProcess(Consts.FFPROCESS);

} else if (browser.equals(Consts.IE)) {

killProcess(Consts.IEPROCESS);

killProcess(Consts.IEDRIVERP);

} else if (browser.equals(Consts.CR)) {

killProcess(Consts.CRPROCESS);

killProcess(Consts.CRDRIVERP);

}

}


/**

* <b>Name:</b> explicitWait</br> <b>Description: </b>Method waiting till an

* element is found and displays duration of waiting.

*

* <h4>Example using this method:</h4>

* explicitWait(By.cssSelector(EDMConsts.EDM_PRINT_DOC_LAYER_TXT),20);<br>

*

* @param locator

* @param timeout

* @author <i>Ron Zhang</i>

*/

public static void explicitWait(final By locator, long timeout) {

Reporter.log("********Explicit Wait started**********", true);

long startTime = 0;

long endTime = 0;


try {

startTime = System.currentTimeMillis();

WebElement welement = (new WebDriverWait(driver, timeout))

.until(new ExpectedCondition<WebElement>() {

@Override

public WebElement apply(WebDriver wd) {

return wd.findElement(locator);

}

});

try {

wait.until(ExpectedConditions.visibilityOf(welement));

Actions act = new Actions(driver);

act.moveToElement(welement).perform();

} catch (TimeoutException te) {

Reporter.log("Time out exeption for wait visibility: " + te,

true);

}

endTime = System.currentTimeMillis();

Reporter.log("Passed to explicit wait for element( " + locator

+ " )within - " + countPerformTime(startTime, endTime),

true);


} catch (Exception e) {

e.printStackTrace();

endTime = System.currentTimeMillis();

Reporter.log("Fail to explicit wait for element {" + locator + " }"

+ " within - " + countPerformTime(startTime, endTime), true);

}

}


/**

* <b>Name:</b> countPerformTime</br> <b>Description: </b>Method calculates

* the time difference and transforms it into a second.</br>

*

* @param startTime

* @param endTime

* @return resultTime

*/

public static String countPerformTime(long startTime, long endTime) {

String resultTime = "";


float seconds = (endTime - startTime) / 1000F;

resultTime = Float.toString(seconds) + " seconds.";


return resultTime;

}


/**

* <b>Name:</b> waitForPageToLoad<br>

* <b>Description:</b> wait for page to load after clicking a button.

*

* @param timeout

*/

public static void waitForPageToLoad(String timeout) throws Exception {

// *** Wait until things look like they've been stable for a second

if (!(driver instanceof JavascriptExecutor)) {

return;

}

new Wait() {

private long started = System.currentTimeMillis();


public boolean until() {

Object result = ((JavascriptExecutor) driver)

.executeScript("return document['readyState'] ? 'complete' == document.readyState : true");

if (result != null && result instanceof Boolean

&& (Boolean) result) {

long now = System.currentTimeMillis();

if (now - started > 1000) {

Reporter.log(

"Page loaded for: "

+ countPerformTime(started, now), true);

return true;

}

} else {

started = System.currentTimeMillis();

}

return false;

}

}.wait(timeout);

windowFocus();

}


/**

* <b>Name:</b> windowFocus<br>

* <b>Description:</b> focus the current window

*/

public static void windowFocus() {

executeScript("window.focus()");

}


/**

* <b>Name:</b> executeScript<br>

* <b>Description:</b> Use to execute Javascript script

*

* @param script

* @param args

* @return none

*/

private static Object executeScript(String script, Object... args) {

if (driver instanceof JavascriptExecutor) {

return ((JavascriptExecutor) driver).executeScript(script, args);

}

throw new UnsupportedOperationException(

"The underlying WebDriver instance does not support executing javascript");

}


/**

* <b>Name: </b>goToThePage<br>

* <b>Description: </b>Using URL go to the desired page.

*

* <h4>Example using this method:</h4> goToThePage(rTestData,)<br>

*

* @param URL

* @throws Exception

*/

public void goToThePage(String URL) {

try {

driver.get(URL);

Reporter.log("Navigate to' " + URL

+ "' page loaded with the title: " + driver.getTitle(),

true);

//clickCertificateLinkForIE();

} catch (Exception e) {

e.printStackTrace();

}

}


/**

* <b>Name: </b>clickCertificateLinkForIE<br>

* <b>Description: </b>Clicks on 'Continue to this website (not

* recommended)' link on IE.

*

* @throws Exception

*/

public void clickCertificateLinkForIE() {

driver.navigate().to(

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

}


/**

* <b>Name:</b> checkBoxSelect<br>

* <b>Description:</b> check a checkBox on the web page according to the

* given value . This function does not call ExpectedCondition in

* selectCheckBox() because it results timeout for certain type of check

* box.

*

* @param element

* @param elementDesc

*/

public void checkBoxSelect(WebElement element, String elementDesc) {

try {

explicitWait(element, 20);

if (!element.isSelected()) {

clickUsingJS(element, elementDesc);

Thread.sleep(1000);

Reporter.log("check a CheckBox for : " + elementDesc, true);

} else {

Reporter.log("check a CheckBox for : " + elementDesc

+ " is already checked.", true);

}

} catch (Exception e) {

e.printStackTrace();

Reporter.log("Failed to select checkbox " + elementDesc, true);

}

}


/**

* <b>Name:</b> click<br>

* <b>Description:</b> Click on a link/button/radio button.

*

* @param element

* @param elementDescription

* @throws Exception

*/

public void click(WebElement element, String elementDescription) {

try {

explicitWait(element, 3000);

if (element == null) {

Reporter.log("No such element"+elementDescription);

} else {

clickUsingJS(element, elementDescription);

//waitForPageToLoad(Consts.PAGETOLOAD_MAX);

}

} catch (Exception e) {

Reporter.log("Fail to click on the element: " + elementDescription,

true);

e.printStackTrace();

}

}


/**

* <b>Name:</b> selectListByVisibleText<br>

* <b>Description:</b> Select a Drop Down/field on the web page according to

* the given value.

*

* @param element

* @param elementValue

* @param elementDescription

*/

public void selectListByVisibleText(WebElement element,

String elementValue, String elementDescription) {

try {

explicitWait(element, 20);

if (element == null) {

Reporter.log("Element for : " + elementDescription

+ " does not exist.", true);

}

driver.switchTo().activeElement();

Select select = new Select(element);

try {

select.selectByVisibleText(elementValue);

} catch (NoSuchElementException notFoundEx) {

Reporter.log("Cannot select by text. Try select by value",

true);

select.selectByValue(elementValue);

}

Reporter.log("Selected : "

+ (elementDescription == null ? element

: elementDescription) + " with text: "

+ elementValue, true);

} catch (Exception e) {

Reporter.log("Fail to select : "

+ (elementDescription == null ? element

: elementDescription) + " with text "

+ elementValue, true);

}

}


/**

* <b>Name:</b> selectListByIndex<br>

* <b>Description:</b> Select a Drop Down/field on the web page according to

* the given index.

*

* @param element

* @param indexValue

* @param elementDescription

*/

public void selectListByIndex(WebElement element, int indexValue,

String elementDescription) {

try {

explicitWait(element, 20);

if (element == null) {

Reporter.log("Element for : " + elementDescription

+ " does not exist.", true);

}

driver.switchTo().activeElement();

Select select = new Select(element);


select.selectByIndex(indexValue);

Reporter.log("Selected : "

+ (elementDescription == null ? element

: elementDescription) + " with index: "

+ indexValue, true);

} catch (Exception e) {

Reporter.log(

"Fail to select : "

+ (elementDescription == null ? element

: elementDescription) + " with index "

+ indexValue, true);

}

}


/**

* <b>Name:</b> getSelectedOptionText<br>

* <b>Description:</b> Return a Drop Down/field selected option text

*

* @param element

* @param indexValue

* @param elementDescription

*/

public String getSelectedOptionText(WebElement element,

String elementDescription) {

String returnText;


explicitWait(element, 20);

if (element == null) {

Reporter.log("Element for : " + elementDescription

+ " does not exist.", true);

}

driver.switchTo().activeElement();

Select select = new Select(element);

returnText = select.getFirstSelectedOption().getText();


Reporter.log("Get the selected option text = " + returnText, true);

return returnText;

}


/**

* <b>Name:</b> type<br>

* <b>Description:</b> Fills a TextBox on the web page according to the

* given value.

*

* @param element

* @param elementValue

* @param elementDescription

*/

public void type(WebElement element, String elementValue,

String elementDescription) {

explicitWait(element, 20);

if (elementValue != null) {

try {

if (element == null) {

Reporter.log("Element: " + elementDescription

+ " does not exist.", true);

}

if (!wait.until(ExpectedConditions.visibilityOf(element))

.isEnabled()) {

throw new Exception(elementDescription + "does not exist.");

}

clearTextField(element);

element.sendKeys(elementValue);

windowFocus();

Reporter.log("Entering Text in Text Box : "

+ elementDescription + " = " + elementValue, true);

} catch (Exception e) {

Reporter.log("Fail to enter Text: " + elementValue + " for "

+ elementDescription, true);

}

}

}


/**

* <b>Name:</b> clearTextField<br>

* <b>Description:</b> Clear text field or text box

*

* @param element

* @return

*/

public void clearTextField(WebElement element) {

element.sendKeys(Keys.HOME, Keys.SHIFT, Keys.END, Keys.BACK_SPACE);

clearTextFieldMulLines(element);

}


/**

* <b>Name:</b> clearTextFieldMulLines<br>

* <b>Description:</b> Clear multiple lines in a text box

*

* @param element

* @return

*/

public void clearTextFieldMulLines(WebElement element) {

element.sendKeys(Keys.CONTROL, Keys.HOME);

element.sendKeys(Keys.CONTROL, Keys.SHIFT, Keys.END);

element.sendKeys(Keys.BACK_SPACE);

}


/**

* <b>Name:</b> selectRadioButton<br>

* <b>Description:</b> check a radio button on the web page according to the

* given value/element description.

*

* @param elementId

* @param elementDescription

*/

public void selectRadioButton(WebElement elementId,

String elementDescription) {

explicitWait(elementId, 20);

if (elementId != null) {

if (!elementId.isSelected()) {

clickUsingJS(elementId, elementDescription);

Reporter.log("Check a Radio Button for : "

+ (elementDescription == null ? elementId

: elementDescription), true);

} else {

Reporter.log("Radio Button for : "

+ (elementDescription == null ? elementId

: elementDescription) + " is already checked.",

true);

}

} else {

Reporter.log("Element : " + elementId + " does not exist.", true);

}

}


/**

* <b>Name:</b> Exists<br>

* <b>Description:</b> check if element exists.

*

* @param element

* @param elementDescription

*/

public boolean Exists(final By locator, String elementDescription) {

boolean present = false;

try {

waitForPageToLoad(Consts.PAGETOLOAD);

} catch (Exception ex) {

ex.printStackTrace();

}

try {

driver.findElement(locator);

Reporter.log("The element: " + elementDescription

+ " exists on the " + driver.getTitle() + " page", true);

present = true;

} catch (NoSuchElementException e) {

Reporter.log("The element: " + elementDescription

+ " is not exist on the " + driver.getTitle() + " page",

true);

present = false;

}

return present;

}


/**

* <b>Name:</b> clickUsingJS</br> <b>Description: </b>Method clicks on a

* specific element using java script.</br>

*

* @param element

* @param elementDescription

*/

public void clickUsingJS(WebElement element, String elementDescription) {


try {

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("arguments[0].click();", element);

Reporter.log("Clicking on the element: " + elementDescription, true);

waitForPageToLoad(Consts.PAGETOLOAD);

} catch (Exception e) {

Reporter.log("Fail to click on the element: " + elementDescription,

true);

e.printStackTrace();

}

}


/**

* <b>Name:</b> getNameFromObjectID</br> <b>Description: </b>Method returns

* By locator part from the WebElement.

*

* @param elementID

* @returnt byLocator

*/

public static String getNameFromObjectID(WebElement elementID) {

return elementID.toString().split("->")[1].trim();

}


/**

* <b>Name:</b> getByFromWebElement</br> <b>Description: </b>Method returns

* By locator part from the WebElement.

*

* @param elementID

* @returnt byLocator

*/

public static By getByFromWebElement(WebElement elementID) {

By byLocator = null;

String allStr = getNameFromObjectID(elementID);

String elementPath = allStr.split(":")[1].trim();

String locatorName = allStr.split(":")[0].trim();

if (elementPath.endsWith("]")) {

elementPath = elementPath.substring(0, elementPath.length() - 1)

.trim();

}

if (locatorName.indexOf(" ") != -1

&& !locatorName.equals("partial link text")) {

String partOne = locatorName.split(" ")[0];

String partTwo = locatorName.split(" ")[1];

partTwo = Character.toUpperCase(partTwo.charAt(0))

+ partTwo.substring(1);

locatorName = partOne + partTwo;

} else if (locatorName.equals("partial link text")) {

locatorName = "partialLinkText";

}

try {

switch (locatorName) {

case "className":

byLocator = By.className(elementPath);

break;

case "cssSelector":

byLocator = By.cssSelector(elementPath);

break;

case "id":

byLocator = By.id(elementPath);

break;

case "linkText":

byLocator = By.linkText(elementPath);

break;

case "name":

byLocator = By.name(elementPath);

break;

case "partialLinkText":

byLocator = By.partialLinkText(elementPath);

break;

case "tagName":

byLocator = By.tagName(elementPath);

break;

case "xpath":

byLocator = By.xpath(elementPath);

break;

default:

break;

}

} catch (NoSuchElementException elEx) {

elEx.printStackTrace();

}

return byLocator;

}


/**

* <b>Name:</b> explicitWait</br> <b>Description: </b>Using WebElement

* method waiting till an element is found and displays duration of

* waiting.</br>

*

* @param elementID

* @param timeout

*/

public void explicitWait(WebElement element, long timeout) {

Reporter.log(

"********Explicit Wait using WebElement started**********",

true);

long startTime = 0;

long endTime = 0;


try {

wait.until(ExpectedConditions.visibilityOf(element));

Actions act = new Actions(driver);

act.moveToElement(element).perform();

endTime = System.currentTimeMillis();

Reporter.log("Passed to explicit wait for element( " + element.getLocation()

+ " )within - " + countPerformTime(startTime, endTime),

true);

} catch (TimeoutException te) {

Reporter.log("Time out exeption for wait visibility: " + te,

true);

}catch (Exception e) {

endTime = System.currentTimeMillis();

Reporter.log("Fail to explicit wait for element {" + element.getLocation() + " }"

+ " within - " + countPerformTime(startTime, endTime), true);

e.printStackTrace();

}



}


/**

* <b>Name:</b> unselectCheckBox<br>

* <b>Description:</b> uncheck a checkBox on the web page according to the

* given value.<br>

*

* @param elementId

* @param elementDescription

*/

public void unselectCheckBox(WebElement elementId, String elementDescription) {

try {

if (elementId != null) {

if (elementId.isSelected()) {

click(elementId, elementDescription);

Reporter.log("uncheck a CheckBox for : "

+ (elementDescription == null ? elementId

: elementDescription), true);

} else {

Reporter.log("uncheck a CheckBox for : "

+ (elementDescription == null ? elementId

: elementDescription)

+ " is already unchecked.", true);

}

}

} catch (Exception e) {

Reporter.log("Element : " + elementId + " does not exist.", true);

e.printStackTrace();

}

}


/**

* <b>Name:</b> waitForNumberOfWindows<br>

* <b>Description:</b> waiting for number of the window.

*

* @param numberOfWindows

*/

public void waitForNumberOfWindows(final int numberOfWindows) {

long startTime = 0;

long endTime = 0;


try {

startTime = System.currentTimeMillis();

new WebDriverWait(driver, 20000) {

}.until(new ExpectedCondition<Boolean>() {

@Override

public Boolean apply(WebDriver driver) {

return (driver.getWindowHandles().size() == numberOfWindows);

}

});

endTime = System.currentTimeMillis();

Reporter.log("Passed to wait for the new window within - "

+ countPerformTime(startTime, endTime), true);

} catch (Exception e) {

endTime = System.currentTimeMillis();

Reporter.log("Fail to wait for the new window within - "

+ countPerformTime(startTime, endTime), true);

e.printStackTrace();

}

}


/**

* <b>Name:</b> switchWindow<br>

* <b>Description:</b> This method is used to switch between two opened

* windows.</br>

*/

public void switchWindow() {

String parentTitle = driver.getTitle();

availableWindows = driver.getWindowHandles();


String winParent = (String) availableWindows.toArray()[0];

String winChild = (String) availableWindows.toArray()[1];


if (parentTitle.equals(driver.switchTo().window(winParent).getTitle())) {

driver.switchTo().window(winChild);

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

}

String childTitle = driver.getTitle();

driver.manage().window().maximize();

Reporter.log("Window switched from: " + "'" + parentTitle + "'"

+ " to window: " + "'" + childTitle + "'.", true);

}


/**

* <b>Name:</b> switchToCurrentWindow <br>

* <b>Description:</b> This method is used Switch focus to currently opened

* windows </br>

*/

public void switchToCurrentWindow() {

for (String winHandle : driver.getWindowHandles()) {

driver.switchTo().window(winHandle);

}

//driver.manage().window().maximize();

Reporter.log("Title of the page switching to newly opened Windows: "

+ driver.getTitle(), true);

}



/**

* <b>Name:</b> switchWindow<br>

* <b>Description:</b> This method is used to switch next window;

* windows.</br>

*/



/**

* <b>Name:</b> switchBetweenTabs<br>

* <b>Description:</b> This method is used to switch between two opened

* tabs.</br>

*/



public void switchBetweenTabs() {

String tabName = "";

waitForNumberOfWindows(2);

ArrayList<String> tabs = new ArrayList<String>(

driver.getWindowHandles());

driver.switchTo().window(tabs.get(0));

tabName = driver.switchTo().window(tabs.get(0)).getTitle();

driver.switchTo().window(tabs.get(1));

Reporter.log("The tab was switched from " + tabName + " to "

+ driver.switchTo().window(tabs.get(1)).getTitle(), true);

}


/**

* <b>Name:</b> selectFrame<br>

* <b>Description:</b> Selects a particular frame on the basis of the

* parameters passed.<br>

*

* @param frameId

*/

public void selectFrame(WebElement frameId) {

try {

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

try {

driver.switchTo().frame(frameId);

Reporter.log("Frame has switched to: " + frameId, true);

} catch (NoSuchFrameException e) {

throw new SeleniumException(e.getMessage(), e);

}

} catch (Exception e) {

Reporter.log("Fail to select Frame : " + frameId, true);

e.printStackTrace();

}

}


/**

* <b>Name:</b> clickLinkUsingText<br>

* <b>Description:</b> This method is used to click link using the link text

*

* @param linkText

*/

public void clickLinkUsingText(String linkText) {

WebElement link = driver.findElement(By.linkText(linkText));

if (!getBrowserType(Consts.IE)) {

click(link,

"link " + linkText + " on the page: " + driver.getTitle());

} else {

clickUsingJS(link,

"link " + linkText + " on the page: " + driver.getTitle());

}

}


/**

* <b>Name:</b> getBrowserType<br>

* <b>Description:</b> This method is used for the definition of browser

* type

*

*/

public boolean getBrowserType(String browserName) {

boolean type = false;

if (Consts.startBrowser == browserName) {

type = true;

Reporter.log("The test is run on " + browserName + " browser", true);

}

return type;

}


/**

* <b>Name:</b> closeParentWindow<br>

* <b>Description:</b> This method is used to close parent window

*/

public void closeOriginalWindow(String handle) {



Set<String> all_handles = driver.getWindowHandles();



// set.remove(base);

// assert set.size() == 1;

// Reporter.log(

// "The window: "

// + driver.switchTo().window((String) set.toArray()[0])

// .getTitle() + " has been closed", true);

// driver.switchTo().window((String) set.toArray()[0]).close();

// driver.switchTo().window(base);

for (String e : all_handles) {



if (handle!=e) {

driver.switchTo().window(e).close();

}

}

System.out.println("瀹歌尙绮¢崗鎶芥4閸樼喐娼甸幍鎾崇磻閻ㄥ嫭绁荤憴鍫濇珤");



}


/**

* <b>Name:</b> convertDateFormat<br>

* <b>Description:</b> This method is used to convert date from one format

* to another<br>

*

* <b>Example:</b>

* <code>convertDateFormat("07302014","MMddyyyy","MM/dd/yyyy")</code>

*

* @param dateToConvert

* - date and time

* @param fromFormat

* - original format

* @param toFormat

* - new format

* @return date and time in new format

*/

public static String convertDateFormat(String dateToConvert,

String fromFormat, String toFormat) {

String dateStr = "";

try {

DateFormat convertFromFormat = new SimpleDateFormat(fromFormat);

DateFormat convertToFormat = new SimpleDateFormat(toFormat);

dateStr = convertToFormat.format(convertFromFormat

.parse(dateToConvert));

Reporter.log("The converted date: " + dateStr, true);

} catch (Exception e) {

e.printStackTrace();

Reporter.log("Failed to convert from " + fromFormat + " to "

+ toFormat, true);

}

return dateStr;

}


/**

* <b>Name:</b> getCurrentYear<br>

* <b>Description:</b> This method is used to return current year<br>

*

* <b>Example:</b> <code>getCurrentYear("yyyy")</code>

*

* @param format

* @return current year in new format

*/

public static String getCurrentYear(String format) {

String year = new SimpleDateFormat(format).format(new Date());

Reporter.log("The year: " + year, true);

return year;

}


/**

* <b>Name:</b> isTextPresent<br>

* <b>Description:</b> Check whether text present or not.<br>

*

* @param text

* @param locator

* @return isTextPresent (true/false)

*/

public boolean isTextPresent(String text, By locator) {

boolean textPresent = false;

try {

Thread.sleep(3000);

String textSearch = driver.findElement(locator).getText();

System.out.println(textSearch);



if (textSearch.contains(text)) {

textPresent = true;

}

Reporter.log("Checking text present: " + text + " - results - "

+ textPresent, true);

} catch (Exception e) {

Reporter.log("Checking text not present: " + text + " - results - "

+ textPresent, true);

e.printStackTrace();

}

return textPresent;

}


/**

* <b>Name:</b> readStringFromFile<br>

* <b>Description:</b> Read first string from file<br>

*

* @param fileName

* @return str

*/

// public static String readStringFromFile(String fileName) {

// List<String> list = null;

// String str = "";

// File f = new File(fileName);

// if (!f.exists()) {

// try {

// throw new Exception(

// "BEFORE RUN SELENIUM TESTS YOU MUST RUN: "

// + fileName.split(Consts.PATH_BWR_NAME_EDM_IO

// + "//")[1].split(".txt")[0]

// + " - QTP TESTS" +

// " ONCE!");

// } catch (Exception e) {

// Reporter.log(e.getMessage(),true);

// }

// createFileWriteLine(fileName, "FAKE 0821-32052 PM");

// }

// try {

// list = Files.readAllLines(new File(fileName).toPath(),

// Charset.defaultCharset());

// str = list.get(0).toString();

// Reporter.log("The line from file: " + fileName + " - " + str,true);

// } catch (Exception ex) {

// ex.printStackTrace();

// }

// return str;

// }


/**

* <b>Name:</b> createFileWriteLine<br>

* <b>Description:</b> Creates a file and writes a line of a text in it<br>

*

* @param filePath

* @param line

*/

public static void createFileWriteLine(String filePath, String line) {

try (Writer writer = new BufferedWriter(new OutputStreamWriter(

new FileOutputStream(filePath), "utf-8"))) {

writer.write(line);

Reporter.log("The file created: " + filePath, true);

} catch (IOException ex) {

ex.printStackTrace();

}

}


/***

* <b>Name:</b> acceptAlert<br>

* <b>Description:</b> Click "OK" in alert<br>

*/

public void acceptAlert() {

Reporter.log("The alert: " + driver.switchTo().alert().getText()

+ " started and accepted", true);

try {

driver.switchTo().alert().accept();

waitForPageToLoad(Consts.PAGETOLOAD);

} catch (Exception e) {

e.printStackTrace();

}

}


/***

* <b>Name:</b> getAlertText<br>

* <b>Description:</b> Get text from alert<br>

*

* @return alertText

*/

public String getAlertText() {

String alertText = driver.switchTo().alert().getText();

Reporter.log("The alert text: " + alertText, true);

return alertText;

}


/**

* <b>Name:</b> getLocalDateTimeAnyFormat<br>

* <b>Description:</b> Returns day and time in any formats<br>

* <b>Example:</b> <code>getLocalDateTimeAnyFormat("MM/dd/yyyy");</code>

*

* @param format

* @return local date in specific format

*/

public static String getLocalDateTimeAnyFormat(String format) {

DateFormat dateFormat = new SimpleDateFormat(format);

Date date = new Date();

String formDayTime = dateFormat.format(date).trim();

Reporter.log("The day/time in format: " + formDayTime, true);

return formDayTime;

}


/**

* <b>Name:</b> checkWinClosed<br>

* <b>Description:</b> This method is used to check if the window is closed

*/

public boolean checkWinClosed(String parentWinTitle) {

boolean winExists = false;

switchToCurrentWindow();

String winName = getWinTitle();

if (getWinHandleSize() == 1 && parentWinTitle.equals(winName)) {

winExists = true;

Reporter.log("All the windows have been closed except: " + winName

+ " window", true);

} else if (!winExists) {

Reporter.log("Window: " + winName + " has not been closed", true);

}

return winExists;

}


/**

* <b>Name:</b> getWinHandleSize<br>

* <b>Description:</b> This method is used to get total number of window

* handle available

*/

public static int getWinHandleSize() {

int winSize = driver.getWindowHandles().size();

Reporter.log("Window handle size: " + winSize, true);

return winSize;

}


/**

* <b>Name:</b> getWinTitle<br>

* <b>Description:</b> This method is used to get title of the window

*/

public static String getWinTitle() {

String winTitle = driver.getTitle();

Reporter.log("Window title: " + winTitle, true);

return winTitle;

}


/**

* <b>Name:</b> refreshWin<br>

* <b>Description:</b> This method is used to refresh a window

*/

public void refreshWin() {

try {

driver.navigate().refresh();

waitForPageToLoad(Consts.PAGETOLOAD);

} catch (Exception e) {

e.printStackTrace();

}

Reporter.log(

"The window: " + driver.getTitle() + " has been refreshed",

true);

}

/**

* By id

* @param element

* @param elementScriptino

*/

public void ClickButton(String element,String elementScriptino)

{

try{

Thread.sleep(20000);

driver.findElement(By.id(element)).click();



Reporter.log("Click Button: " + elementScriptino+"---success", true);

}

catch (Exception e)

{



Reporter.log("Click Button: " + elementScriptino+"--fail", true);

e.printStackTrace();

}





}





/**

* By xpath

*

*/

public void ClickButtonByXpath(String element,String elementScriptino)

{

try{

Thread.sleep(20000);

driver.findElement(By.xpath(element)).click();



Reporter.log("Click Button: " + elementScriptino+"---success", true);

}

catch (Exception e)

{



Reporter.log("Click Button: " + elementScriptino+"--fail", true);

e.printStackTrace();

}





}

/**

* <b>Name:</b> refreshWin<br>

* <b>Description:</b> This method is used to Drag drop box

*/

public void DragDropBox(int height)

{

JavascriptExecutor JS=(JavascriptExecutor) driver;

String high="scroll(0,"+height+")";

JS.executeScript(high);

}

/**

* @category Display now Time

*/

public void DisplayTime()

{

Date now = new Date();

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//閸欘垯浜掗弬閫涚┒閸﹂鎱ㄩ弨瑙勬)閺堢喐鐗稿锟�


String time = dateFormat.format( now );

System.out.println(time);

}

/**

* @deprecated:Close The pop ads

* @throws InterruptedException

*/

public void CloseADS() throws InterruptedException

{ DisplayTime();

Order orderpager;

orderpager=new Order();

explicitWait(By.id(ZenniConsts.ORDER_ADS_ID), 60);

if(Exists(By.id(ZenniConsts.ORDER_ADS_ID), "The Pop Ads"))

{

orderpager.CloseADS();



}



}



private void takeScreenshot(String screenPath) {

try {

File scrFile = ((TakesScreenshot) driver)

.getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(scrFile, new File(screenPath));

} catch (IOException e) {

System.out.println("Screen shot error: " + screenPath);

}

}

/*

* @Function: Take Screen shot

*

*/

public void takeScreenshot() {

SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");

String mDateTime = formatter.format(new Date());

String screenName = String.valueOf(mDateTime) + ".jpg";

File dir = new File("test-output/snapshot");

if (!dir.exists())

dir.mkdirs();

String screenPath = dir.getAbsolutePath() + "/" + className+"____"+screenName;

this.takeScreenshot(screenPath);

}



public String getWebUrl()

{

String url =driver.getCurrentUrl();

return url;





}

/*

* Empty the goods in the shopping cart

*/

public void ClearShopingCart()

{

String Number=driver.findElement(By.xpath(ZenniConsts.HOME_SHOPPING_CART_AMOUNT_XPATH)).getText();

String spNumber=Number.substring(1, Number.length()-1);

System.out.println(spNumber);

int cartAmount=Integer.parseInt(spNumber);

if (cartAmount!=0) {

HomePage homePage=new HomePage();

homePage.ClickShoppingCart();

ShoppingCart shopcar=new ShoppingCart();

while (Exists(By.linkText(ZenniConsts.SHOPPINGCART_REMOVE_FIRST_LINK), "Goods exists,so must clear them")) {

shopcar.ClickRemoveLink();

}





}

else {

Reporter.log("There are no shopping goods");

}





}

/**

* Get Text string from web

* @param locator

* @param elementString

* @return

*/

public String getWebText(By locator,String elementString)

{

String webValueString = null;

try {

Thread.sleep(2000);

webValueString=driver.findElement(locator).getText();

Reporter.log("Get web value sucessful");



} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

Reporter.log("Get web value"+elementString+"fail");

}



return webValueString;

}

/**

* Choose the next window

* @param current_handle

*/

public void switchNextWindow(String current_handle){

try {

Thread.sleep(30000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println("Go on");

Set<String> all_handles=driver.getWindowHandles();

System.out.println("all_handles.size()"+all_handles.size());

for (String e : all_handles) {

System.out.println("Handles:"+e);

if (current_handle!=e) {

driver.switchTo().window(e);



}

}



System.out.println("Go out");

}

/**

* Go to Back

*/

public void back()

{

driver.navigate().back();

}



/*

* Radio button is selected

*/

public boolean isSelectRadioButton(By locator,String elementDescription) {



boolean isChecked=false;

try{

boolean checked = driver.findElement(locator).isSelected();

if(checked){

isChecked=true;

}

Reporter.log("Checking Radio Button is checked: " + elementDescription + " - results - "

+ isChecked, true);



}catch(Exception e){

Reporter.log("Checking Radio Button is not checked: " + elementDescription + " - results - "

+ isChecked, true);





}

return isChecked;



}



/**

* <b>Name:</b> moveScrollToElement<br>

* <b>Description:</b> Move the scroll bar to the location of the specified element

* @param element

*/

public void moveScrollToElement(WebElement element){



JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("arguments[0].scrollIntoView();", element);

}



private void WriteToExcel(WritableWorkbook workbook,WritableSheet sheet,int cols,int rows,String Data,Label[] lb) throws IOException, RowsExceededException, WriteException

{



lb[rows]=new Label(cols,rows,Data);

Label labe1=new Label(1,0,"TagName_Of_A_Information");

sheet.addCell(labe1);



Label labe2=new Label(6,0,"TagName_Of_Span_Information");

sheet.addCell(labe2);

//Label label=new Label(cols,rows,Data);

sheet.addCell(lb[rows]);





}



private String getContent(String urlHTML)

{

String temp;

StringBuffer sb=new StringBuffer();

try {

URL ulr=new URL(urlHTML);

BufferedReader b=new BufferedReader(new InputStreamReader(ulr.openStream(),"utf-8"));

while ((temp=b.readLine())!=null) {

sb.append(temp);

}



} catch (Exception e) {

e.printStackTrace();

}

return sb.toString();





}



private List<String> getTagA_WenZi(String content)

{



String regex = "<a.*?</a>";

Pattern pa = Pattern.compile(regex);

Matcher ma = pa.matcher(content);

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

while (ma.find()) {

list.add(ma.group());

}

return list;



}



private List<String> getTagP_Wenzi(String content)

{

String regex = "<p.*?</p>";

Pattern pa = Pattern.compile(regex);

Matcher ma = pa.matcher(content);

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

while (ma.find()) {

list.add(ma.group());

}

return list;





}

private List<String> getTagSpan_WenZi(String content)

{



String regex = "<span.*?</span>";

Pattern pa = Pattern.compile(regex);

Matcher ma = pa.matcher(content);

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

while (ma.find()) {

list.add(ma.group());

}

return list;



}



private List<String> getTagDiv_WenZi(String content)

{



String regex = "<span.*?</span>";

Pattern pa = Pattern.compile(regex);

Matcher ma = pa.matcher(content);

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

while (ma.find()) {

list.add(ma.group());

}

return list;



}



public void GetInfoAndWrite(String url,File file) throws IOException{

StartingSelenium t=new StartingSelenium();

String content=t.getContent("http://www.zennioptical.com");

List<String> aTagString=t.getTagA_WenZi(content);

List<String> spanTagString=t.getTagSpan_WenZi(content);

List<String> pTagString=t.getTagP_Wenzi(content);

WritableWorkbook workbook=Workbook.createWorkbook(new File("D:\\Data\\TestDemo.xls"));

WritableSheet sheet=workbook.createSheet("Information", 0);

sheet = workbook.getSheet(0);

System.out.println("a标签摘取");

Label[] ji=new Label[aTagString.size()+spanTagString.size()+pTagString.size()];

for (int i = 0; i < aTagString.size(); i++) {



String aString=aTagString.get(i).replaceAll("<[^>]*>| |\t|\n|&[\\s\\S]*;{1}","").trim();



if (aString!="") {

try {

t.WriteToExcel(workbook,sheet,1,i+1,aString,ji);

} catch (RowsExceededException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (WriteException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}









}

System.out.println("Span标签摘取");

for (int i = 0; i < spanTagString.size(); i++) {



String aString=spanTagString.get(i).replaceAll("<[^>]*>| |\t|\n|&[\\s\\S]*;{1}","").trim();

if (aString!=null) {

//System.out.println(aString);

try {

t.WriteToExcel(workbook,sheet,6,i+1,aString,ji);

} catch (RowsExceededException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (WriteException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}



}

}



System.out.println("P标签摘取");

for (int i = 0; i < pTagString.size(); i++) {



String aString=pTagString.get(i).replaceAll("<[^>]*>| |\t|\n|&[\\s\\S]*;{1}","").trim();

if (aString!=null) {

//System.out.println(aString);

try {

t.WriteToExcel(workbook,sheet,10,i+1,aString,ji);

} catch (RowsExceededException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (WriteException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}



}

}





}



/**

* value字符抓取

*

*

*/

public List<String> getTagValue_Wenzi(String content)

{

String regex ="value="+'"'+"[^=]+"+'"';

Pattern pa = Pattern.compile(regex);

Matcher ma = pa.matcher(content);

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

while (ma.find()) {

list.add(ma.group());

}

return list;





}

/**

* title字符抓取

*

*

*/

public List<String> getTagTitile_Wenzi(String content)

{

String regex ="title="+'"'+"[^=]+"+'"';

Pattern pa = Pattern.compile(regex);

Matcher ma = pa.matcher(content);

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

while (ma.find()) {

list.add(ma.group());

}

return list;





}

/**

* 字符抓取

*

*

*/

public List<String> getPlaceholder_Wenzi(String content)

{

String regex ="placeholder="+'"'+"[^=]+"+'"';

Pattern pa = Pattern.compile(regex);

Matcher ma = pa.matcher(content);

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

while (ma.find()) {

list.add(ma.group());

}

return list;





}









}

举报

相关推荐

0 条评论