package test_4_1.tools; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Function; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang3.BooleanUtils; import org.apache.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.databind.ObjectMapper; import org.testng.Assert; /** * @author Terry Date : 2016-02-29 23:17 工具类 */ public class Utils { private final static Logger logger = Logger.getLogger(Utils.class); public static final String ACTION_CLICK = "click"; public static final String ACTION_SENDKEYS = "sendKeys"; public static final String ACTION_SWITCH_TO_FRAME = "switchToFrame"; public static final String ACTION_CLEAR = "clear"; public static final String ACTION_NOP = "nop"; // public static Wait wait; /** * 项目设置对象 */ public static JSONObject settings = null; public static WebDriver driver; /** * 全局等待的设置 WebDriverWait不能用全局变量,Terry Kwan,2017-5-1 */ // public static WebDriverWait waitSetting; /** * extJs confirm窗口的等待时间 WebDriverWait不能用全局变量,Terry Kwan,2017-5-1 */ // public static WebDriverWait confirmWaitSetting; // public static Wait waitSetting; /** * 单次装配后产生的条码 */ public static List barcodes; /** * 用于代理灭菌二次发货的条码 */ public static List resendout; /** * 所有装配产生的条码 */ public static List reBarcodes = new ArrayList(); /** * 动态产生的数据 */ private static SeleniumRuntimeData seleniumRuntimeData = new SeleniumRuntimeData(); /** * 单次一次性物品入库后产生的条码 */ public static List disposableGoodsBatchBarcodesAfterEntry = new ArrayList(); public static SeleniumRuntimeData getSeleniumRuntimeData() { return seleniumRuntimeData; } /** * 根据项目名称,初始化项目的配置对象 * * @param projectName * 项目名称的字符串 * @return 项目配置对象 */ public static JSONObject initProjectSettings(String projectName) { settings = getProjectSettings(projectName); return settings; } /** * 打印当前页面的源代码,用于分析调试 * * @param driver */ public static void printCurrentWebpageSourcecode(WebDriver driver) { Object response = ((JavascriptExecutor) driver) .executeScript("return document.documentElement.innerHTML;"); String source = (String) response; System.out.println(source); } /** * 设置等待的对象 * * @param driver * 对应的driver */ public static void setWaitSetting(WebDriver driver) { // 最长等待15秒,每1秒轮询一次 WebDriverWait waitSetting = new WebDriverWait(driver, 8, 350); // 最长等待2秒,每0.3秒轮询一次 WebDriverWait confirmWaitSetting = new WebDriverWait(driver, 2, 300); // waitSetting = new FluentWait<>(driver).withTimeout(5000, // TimeUnit.MILLISECONDS).pollingEvery(250, TimeUnit.MILLISECONDS); } /** * 初始化chrome的driver */ private static void webDriverChromeInit() { DesiredCapabilities chrome = DesiredCapabilities.chrome(); ChromeOptions options = new ChromeOptions(); options.addArguments("test-type"); chrome.setCapability(ChromeOptions.CAPABILITY, options); chrome.setCapability("applicationName", "terry"); chrome.setCapability("version", "11.0"); driver = new ChromeDriver(chrome); driver.get(Utils.settings.get("服务器地址").toString()); } /** 打开浏览器 */ public static void webDriverInit() { // System.setProperty("webdriver.ie.driver", // "C:\\IEDriverServer_Win32_3.3.0\\IEDriverServer.exe"); // 解决ie兼容模式设置导致无法启动问题 DesiredCapabilities ieCapabilities = DesiredCapabilities .internetExplorer(); // 禁用IE的native Events,解决偶尔有时候页面元素的click点击不生效的问题 ieCapabilities.setCapability(InternetExplorerDriver.NATIVE_EVENTS, false); ieCapabilities .setCapability( InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true); ieCapabilities.setCapability("applicationName", "terry"); ieCapabilities.setCapability("version", "11.0"); try { // driver = new RemoteWebDriver(new URL( // "http://192.168.2.18:4444/wd/hub"), ieCapabilities); driver = new InternetExplorerDriver(ieCapabilities); String cap = ((InternetExplorerDriver) driver).getCapabilities() .toString(); System.out.println("my cap = " + cap); } catch (Exception e) { e.printStackTrace(); } driver.get(Utils.settings.get("服务器地址").toString()); } /** * 初始化设置,包括项目配置和webdriver的初始化 * */ public static void init() { // zd5y已经不使用了 initProjectSettings("all"); webDriverInit(); // webDriverChromeInit(); // driver初始化完设置全局等待的对象 setWaitSetting(driver); } /** 定位到弹出对话框的按钮 */ public static void LocaAndWait() { // Wait wait = new FluentWait(Utils.driver) // .withTimeout(5000, TimeUnit.MILLISECONDS) // .pollingEvery(250, TimeUnit.MILLISECONDS) // .ignoring(NoSuchElementException.class); // WebElement yesbutton = wait // .until(new Function() { // public WebElement apply(WebDriver driver) { // return driver.findElement(By.linkText("是")); // } // }); // yesbutton.click(); retryingFindAndClick(By.linkText("是")); } /** 获取当前日期 */ public static void DateTime() { Date now = new Date(); SimpleDateFormat dateFormater = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); System.out.print(dateFormater.format(now) + " "); } /** * 获取装配时创建的器械包的条码,为集合对象 * */ public static List getToussesBarcodes() { JavascriptExecutor js = (JavascriptExecutor) driver; Object toussesStr = js .executeScript("return JSON.stringify(packingToussesArray)"); List barcodes = new ArrayList(); JSONArray array = JSONArray.fromObject(toussesStr); if (array != null) { for (int i = 0; i < array.size(); i++) { JSONObject tousse = array.getJSONObject(i); JSONArray b = tousse.getJSONArray("barcodes"); for (int j = 0; j < b.size(); j++) { barcodes.add((String) b.get(j)); } } seleniumRuntimeData.addPackingTousseInfo(array); } Utils.reBarcodes.addAll(barcodes); return barcodes; } /** * 获取一次性物品入库后的条码集合对象 * */ public static List getDisposableGoodsBatchBarcodesAfterEntry() { int count = 0; List barcodes = new ArrayList(); while (count <= 10) { try { JavascriptExecutor js = (JavascriptExecutor) driver; Object entryItemStr = js .executeScript("return JSON.stringify(entryItemJsonArray)"); JSONArray array = JSONArray.fromObject(entryItemStr); if (array != null) { for (int i = 0; i < array.size(); i++) { JSONObject entryItem = array.optJSONObject(i); barcodes.add(entryItem.optString("barcode")); } break; } } catch (Exception e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } count++; } return barcodes; } /** * 重复查找,当出现引用的element过时后,重新查找该element * * @param by * @return */ public static WebElement retryingFind(By by) { WebElement element = null; int attempts = 0; // TODO:下面的循环重试应该可以去掉,直接用fluentWaitUntilFind即可 while (attempts < 1) { try { element = fluentWaitUntilFind(by); break; } catch (Exception e) { } attempts++; } return element; } /** * 重复查找和click,当出现引用的element过时后,重新查找该element * * @param by * @return */ public static WebElement retryingFindAndDoAction(By by, String actionType, CharSequence... keys) { WebElement element = null; int attempts = 0; int attemptsTime = 5; while (attempts++ < attemptsTime) { try { // element = findByAwait(by); element = fluentWaitUntilFind(by); if (ACTION_CLICK.equalsIgnoreCase(actionType)) { // Actions actions = new Actions(driver); // 将鼠标移动到html元素,然后click,似乎能增强click的成功率 // actions.moveToElement(element).click().build().perform(); // try{ // WebDriverWait wait = new WebDriverWait(driver, 15); // element = // wait.until(ExpectedConditions.elementToBeClickable(by)); // element.click(); // } // catch(Exception e){ // System.out.println("click() 发生异常:"); // e.printStackTrace(); // } // String onclick = element.getAttribute("onclick"); // System.out.println("onclick = " + onclick); JavascriptExecutor executor = (JavascriptExecutor) driver; Object aa = executor .executeScript( "var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", element); System.out.println("click element attributes:\n" + aa); String attribute = element.getAttribute("disabled"); System.out.println("disabled = " + attribute); if (!"true".equalsIgnoreCase(attribute) && element.isEnabled()) { element.click(); logger.info("点击元素[" + by + "]成功"); } else { logger.info("元素[" + by + "]不是Enable状态,不能点击"); continue; } // 用按回车键模拟click,当element在屏幕上不可见时,也能达到click的效果 // element.sendKeys(Keys.ENTER); } else if (ACTION_SENDKEYS.equalsIgnoreCase(actionType)) { element.sendKeys(keys); } else if (ACTION_CLEAR.equalsIgnoreCase(actionType)) { element.clear(); } else if (ACTION_SWITCH_TO_FRAME.equalsIgnoreCase(actionType)) { // 跳出所有的frame。调用后:you are now outside both frames // Utils.driver.switchTo().defaultContent(); // Utils.driver.switchTo().frame(element); switchToFrame(element); logger.info("切换[" + by + "],frame成功"); } break; } catch (Exception e) { if (attempts == attemptsTime) { String message = e.getMessage(); logger.error(String.format("执行%s时尝试%s次仍然发生错误:%s", by, attemptsTime, message)); if ("null".equals(message)) { e.printStackTrace(); } throw new RuntimeException(message); } logger.warn(String.format("执行动作:%s操作节点%s时,发生错误,重试第%s次,异常如下:%s", actionType, by, attempts, e)); e.printStackTrace(); } } return element; } /** * 重复查找获取控件的文本 * * @param by * @return */ public static String retryingFindAndGetText(By by) { String text = ""; int attempts = 0; while (attempts < 3) { try { WebElement element = fluentWaitUntilFind(by); if (element != null) { text = element.getText(); } else { continue; } break; } catch (Exception e) { } attempts++; } return text; } /** * 重复查找和click,当出现引用的element过时后,重新查找该element * * @param by * @return */ public static WebElement retryingFindAndClick(By by) { return retryingFindAndDoAction(by, ACTION_CLICK); } /** * 重复查找和清空内容,当出现引用的element过时后,重新查找该element * * @param by * @return */ public static WebElement retryingFindAndClear(By by) { return retryingFindAndDoAction(by, ACTION_CLEAR); } public static WebElement retryingFindAndSendKeys(By by, java.lang.CharSequence... keys) { return retryingFindAndDoAction(by, ACTION_SENDKEYS, keys); } /** * 查找组合框,输入按键。输入按键后休眠1.5秒,等待下拉框的内容出现,保证可靠的输入值。 * TODO:如果找到更可靠输入组合框内容的方法,可以取消休眠。如果需要更可靠的输入,可以延长休眠时间 * * @param by * @param keys * @return */ public static WebElement retryingFindComboBoxAndSendKeys(By by, java.lang.CharSequence... keys) { WebElement element = null; int attempts = 0; while (attempts < 5) { try { element = fluentWaitUntilFind(by); element.sendKeys(keys); // TODO:下面的sleep代码,要改为判断Ext.store是否加载完成,然后点击下拉框,而不是睡眠方式 Thread.sleep(1500); // 等待页面状态加载完成 waitPageLoaded(); break; } catch (Exception e) { // System.out.println("hkkkkkk"); // e.printStackTrace(); } attempts++; } return element; } /** * 查找并切换到IFrame * * @param by * @return */ public static WebElement retryingFindAndSwitchToFrame(By by) { return retryingFindAndDoAction(by, ACTION_SWITCH_TO_FRAME); } /** * 流畅等待,查找页面元素 * * @param by * @return */ public static WebElement fluentWaitUntilFind(By by) { // Wait wait = new FluentWait(driver) // .withTimeout(5000, TimeUnit.MILLISECONDS) // .pollingEvery(250, TimeUnit.MILLISECONDS) // .ignoring(NoSuchElementException.class) // .ignoring(StaleElementReferenceException.class) // .ignoring(NullPointerException.class); // element = wait // 暂时改成waitSetting,如果有必要,可以每次new一个新的. waitPageLoaded(); WebDriverWait waitSetting = new WebDriverWait(driver, 8, 350); WebElement element = waitSetting .until(new Function() { public WebElement apply(WebDriver driver) { // 等待页面状态加载完成 // waitPageLoaded(); return driver.findElement(by); } }); return element; } /** * 等待对象使用waitSetting * * @see Utils#findByAwait(By, WebDriverWait) */ public static WebElement findByAwait(By by) { WebDriverWait waitSetting = new WebDriverWait(driver, 8, 350); return findByAwait(by, waitSetting); } /** * 查找页面的节点,使用轮询方式,会一直阻塞,如果超过指定的时间仍然找不到则会抛出异常 * * @param wait * 等待的对象 * @return 查找到的节点,如果在指定的时间找不到则不会返回,直接抛出异常 */ public static WebElement findByAwait(By by, WebDriverWait wait) { try { // 这里找不到会抛出异常 return wait.until((ExpectedCondition) driver -> driver .findElement(by)); } catch (Exception e) { throw new NoSuchElementException(String.format( "找不到对应的元素:%s,原因如下:\n%s", by, e)); } } /** * 先用confirmWaitSetting去找ExtJs的confirm框,如果找得到则点击确认,抛出异常则不点击(用于判断是否需要点击确认框) */ public static WebElement findConfirmAndClick(By by) { WebElement webElement = null; try { webElement = tryFind(by); if (isFind(webElement)) { webElement.click(); } // webElement = findByAwait(by, confirmWaitSetting); } catch (Exception ignored) { } return webElement; } /** * 尝试寻找某个节点 * * @return 返回空则表示找不到 */ public static WebElement tryFind(By by) { try { WebDriverWait confirmWaitSetting = new WebDriverWait(driver, 2, 300); return findByAwait(by, confirmWaitSetting); } catch (Exception ignored) { logger.warn(String.format("尝试查找%s失败", by)); } return null; } /** * 判断某个节点是否被找到 * * @param webElement * 对应的节点 * @return */ public static boolean isFind(WebElement webElement) { return webElement != null && webElement.isDisplayed(); } /** * 在对应的文本框输入想要的内容 * * @param keys * 要输入的内容 */ public static WebElement findByAwaitAndSend(By by, java.lang.CharSequence... keys) { // 先清空文本框上面的然后再输入 // WebElement webElement = findByAwaitAndClear(by); // WebElement webElement = findByAwait(by); // webElement.clear(); retryingFindAndClear(by); return retryingFindAndSendKeys(by, keys); // webElement.sendKeys(keys); // return webElement; } /** * 点击页面元素 */ public static WebElement findByAwaitAndClick(By by) { return retryingFindAndClick(by); // WebElement webElement = // waitSetting.until(ExpectedConditions.elementToBeClickable(by)); // String javascript = "var evt = document.createEvent('MouseEvents');" // + // "evt.initMouseEvent('click',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);" // + "arguments[0].dispatchEvent(evt);"; // runJavaScript(javascript, webElement); // WebElement webElement = findByAwait(by); // webElement.click(); // return webElement; } /** * 切换到对应的frame */ public static WebElement findByAwaitAndSwitchToFrame(By by) { return retryingFindAndSwitchToFrame(by); // Utils.driver.switchTo().defaultContent(); // WebElement webElement = findByAwait(by); // Utils.driver.switchTo().frame(webElement); // return webElement; } /** * 运行js脚本 * * @param script * 要运行的js脚本 */ public static Object runJavaScript(String script) { Object response = ((JavascriptExecutor) Utils.driver) .executeScript(script); logger.info("执行脚本:" + script + " 返回值:" + response); return response; } public static Object runJavaScript(String script, Object... args) { return ((JavascriptExecutor) Utils.driver).executeScript(script, args); } /** * 等待页面加载完成 */ public static void waitPageLoaded() { WebDriverWait waitSetting = new WebDriverWait(driver, 8, 350); waitSetting.until((ExpectedCondition) driver -> "complete" .equals(Utils.runJavaScript("return document.readyState"))); } /** * 默认每次轮询间隔的时间为0.5秒,最长等待时间为10秒 * * @see Utils#waitPageLoaded */ public static void waitPageLoaded(String script) { waitPageLoaded(script, 10000, 500); } /** * 等待页面的某些元素或者某些东西加载完成(通过使用脚本来判断这些是否加载完成) * * @param script * 要执行判断的脚本 * @param maxWaitTime * 最长等待时间 * @param interval * 每次轮询间隔的时间 */ public static void waitPageLoaded(String script, long maxWaitTime, Integer interval) { long start = System.currentTimeMillis(); logger.info("执行等待脚本:" + script); do { if (System.currentTimeMillis() - start > maxWaitTime) { logger.warn("超出最长等待时间" + maxWaitTime + ",跳出循环"); throw new RuntimeException("超出最长等待时间:" + maxWaitTime); } doWait(interval); } while (BooleanUtils.isTrue((Boolean) Utils.runJavaScript(script))); } /** * 切换到default的frame */ public static void switchToDefaultContent() { driver.switchTo().defaultContent(); // 由于切换frame有点不太稳定,切换完立刻点击可能会出现永远找不到元素,所以这里暂时用要休眠一下来解决 doWait(null); } /** * 切换到指定的frame * * @param frame */ public static void switchToFrame(WebElement frame) { Utils.driver.switchTo().frame(frame); // 由于切换frame有点不太稳定,切换完立刻点击可能会出现永远找不到元素,所以这里暂时用要休眠一下来解决 doWait(null); } /** * 切换到指定的frame * @param frame frame的名字 */ public static void switchToFrame(String frame) { Utils.driver.switchTo().frame(frame); // 由于切换frame有点不太稳定,切换完立刻点击可能会出现永远找不到元素,所以这里暂时用要休眠一下来解决 doWait(null); } /** * 切换到指定的window * @param window window的名字 */ public static void switchToWindow(String window) { logger.info("准备开始切换window:" + window); Utils.driver.switchTo().window(window); logger.info("切换window:" + window + "成功"); doWait(null); } /** * 休眠等待一下 * * @param time * 要等待的时间 */ public static void doWait(Integer time) { time = time == null ? 300 : time; // 休眠等待一下 try { Thread.sleep(time); } catch (InterruptedException e) { logger.error(e.getMessage()); } } /** * 重复查找和click,html表格的第一个单元格对象 * * @param by * html table的查找条件 * @return 单元格对象 */ public static boolean retryingFindClickFirstCellOfTable(By by) { boolean result = false; int attempts = 0; while (attempts < 3) { try { WebElement table = retryingFind(by); if (table != null) { WebElement cell = getFirstCellOfTable(table); if (cell != null) { cell.click(); } result = true; break; } } catch (Exception e) { // e.printStackTrace(); } attempts++; } return result; } /** * 重复查找,html表格的第四个单元格对象 * * @param by * html table的查找条件 * @return 单元格对象 */ public static WebElement retryingFindForthCellOfTable(By by) { WebElement result = null; int attempts = 0; while (attempts < 3) { try { WebElement table = retryingFind(by); if (table != null) { WebElement cell = getforthCellOfTable(table); if (cell != null) { String text = cell.getText(); if (text != null) { if (text.equals("自定义器械包申请单") || text.equals("消毒物品申请单")) { result = cell; break; } else { result = null; break; } } } else { result = null; break; } } } catch (StaleElementReferenceException e) { System.out.println("发生了异常:StaleElementReferenceException"); e.printStackTrace(); } catch (NoSuchElementException e) { System.out.println("发生了异常:NoSuchElementException"); e.printStackTrace(); } attempts++; } return result; } /** * 获取Html Table的第一个单元格,即第一行第一列的单元格 * * @param table * 表格对象 * @return 单元格对象 */ private static WebElement getFirstCellOfTable(WebElement table) { WebElement cell = null; // Now get all the TR elements from the table List allRows = table.findElements(By.tagName("tr")); System.out.println("rows size = " + allRows.size()); if (allRows != null && allRows.size() > 0) { WebElement row = allRows.get(0); // return row; List cells = row.findElements(By.tagName("td")); if (cells != null && cells.size() > 0) { cell = cells.get(0); } } return cell; } /** * 获取Html Table的第四个单元格,即第一行第四列的单元格 * * @param table * 表格对象 * @return 单元格对象 */ public static WebElement getforthCellOfTable(WebElement table) { WebElement cell = null; // Now get all the TR elements from the table List allRows = table.findElements(By.tagName("tr")); System.out.println("rows size = " + allRows.size()); if (allRows != null && allRows.size() > 0) { WebElement row = allRows.get(0); // return row; List cells = row.findElements(By.tagName("td")); if (cells != null && cells.size() > 0) { cell = cells.get(3); } } return cell; } /** * 等待直到新窗口被打开 * * @param noOfWindows * 期望的窗口数量 * @param timeOut * 超时时间,单位为毫秒 */ public static void waitForWindowToOpen(int noOfWindows, int timeOut) { int initCount = driver.getWindowHandles().size(); if (initCount == noOfWindows) { return; } else { boolean foundWindow = false; long duration; long startTime = System.currentTimeMillis(); duration = (System.currentTimeMillis() - startTime); while (timeOut > duration && !foundWindow) { try { Thread.sleep(500); } catch (InterruptedException e) { } foundWindow = driver.getWindowHandles().size() >= noOfWindows; duration = (System.currentTimeMillis() - startTime); } if (timeOut <= duration && !foundWindow) { // Throw Error } } } /** * 尝试关闭警告对话框,如果弹出了警告对话框,则关闭该对话框 警告框可能有多个,如:器械包过期告警、满意度调查 */ public static void tryToCloseWarningWindow() { try { Wait wait = new FluentWait(Utils.driver) .withTimeout(5000, TimeUnit.MILLISECONDS) .pollingEvery(250, TimeUnit.MILLISECONDS) .ignoring(NoSuchElementException.class); // 等待对话框弹出 // wait.until(ExpectedConditions // .visibilityOfElementLocated(By // .xpath("//div/span[contains(text(),'满意度调查表')]"))); // 获取警告信息对话框的集合 List closeBtns = wait .until(new Function>() { public List apply(WebDriver driver) { waitPageLoaded(); return driver.findElements(By .cssSelector("div[class='x-tool x-tool-close']")); } }); if (closeBtns.size() == 0) { return; } // List closeBtns = Utils.driver.findElements(By // .cssSelector("div[class='x-tool x-tool-close']")); System.out.println("closeBtns.size() = " + closeBtns.size()); // 逐个关闭对话框,先关闭最外层的。如果没关闭最外层的,里面的对话框无法关闭 for (int i = closeBtns.size() - 1; i >= 0; i--) { closeBtns.get(i).click(); } } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } /** * 回收自定义入筐窗口的切换 */ public static void changeCustomWindow() { try { // 回收窗口 String mainWindow = Utils.driver.getWindowHandle(); Utils.retryingFindAndClick(By.cssSelector("div[class='add2']")); Utils.waitForWindowToOpen(2, 8000); // 遍历所有窗口,切换至新窗口(自定义入筐窗口) Set handles = Utils.driver.getWindowHandles(); for (String windowHandle : handles) { if (!windowHandle.equalsIgnoreCase(mainWindow)) { Utils.driver.switchTo().window(windowHandle); System.out.println("切换到新窗口:" + windowHandle); // 确认已经切换至自定义入筐窗口 String currentUrl = Utils.driver.getCurrentUrl(); System.out.println("currentUrl = " + currentUrl); boolean isLoginOk = currentUrl .indexOf("disinfectsystem/touchScreen/recycle/customIntoBasket.jsp?data") > 0; if (isLoginOk) { Assert.assertTrue(isLoginOk); break; } } } } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } /** * 等待一段时间,直到页面的URL地址变为期望值 * * @param newUrl * 期望的url * @param seconds * 等待的超时时间 */ public static void waitUntilUrlChange(final String newUrl, int seconds) { Wait wait = new FluentWait(Utils.driver) .withTimeout(5000, TimeUnit.MILLISECONDS) .pollingEvery(250, TimeUnit.MILLISECONDS) .ignoring(NoSuchElementException.class); wait.until(new Function() { public Boolean apply(WebDriver d) { return d.getCurrentUrl().startsWith(newUrl); } }); } /** * 获取项目的配置信息,该配置信息合并了web项目的config.js与seleniumTest的settings.json配置信息 * * @param projectName * 项目名称 * @return 项目配置的json对象 */ public static JSONObject getProjectSettings(String projectName) { JSONObject jsonObj = null; ObjectMapper mapper = new ObjectMapper().configure( Feature.ALLOW_COMMENTS, true); mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true); try { // 获取Selenium自动化测试的配置信息 InputStream instream1 = Utils.class.getClassLoader() .getResourceAsStream( "test_4_1/config/" + projectName + "/config.js"); Scanner scanner1 = new Scanner(instream1); String content = scanner1.useDelimiter("\\Z").next(); content = content.replaceAll("var sstsConfig = ", ""); jsonObj = mapper.readValue(content, JSONObject.class); // String testConfigFilename = seleniumTestConfigPath + "/" // + projectName + "/settings.json"; InputStream instream2 = Utils.class .getClassLoader() .getResourceAsStream( "test_4_1/config/" + projectName + "/settings.json"); Scanner scanner2 = new Scanner(instream2); String testConfigFileContent = scanner2.useDelimiter("\\Z").next(); JSONObject jsonObjTestSettings = mapper.readValue( testConfigFileContent, JSONObject.class); // 合并到jsonObj jsonObj.putAll(jsonObjTestSettings); instream1.close(); scanner1.close(); instream2.close(); scanner2.close(); } catch (IOException e) { e.printStackTrace(); } return jsonObj; } /** * 为ExtJS4的组合框输入文字 * * @param comboBoxName * ExtJS4的组合框名字 * @param text * 要输入的文字 */ public static void extJS4comboBoxInput(String comboBoxName, String text) { String script = "return Ext4.getCmp('" + comboBoxName + "').getStore().isLoading();"; // 输入前先等待,看看是否已经加载完,因为处理科室改变物品会重新加载 Utils.waitPageLoaded(script); Utils.findByAwaitAndSend( By.cssSelector("input[name='" + comboBoxName + "']"), text); // 输入完等待加载完毕,加载完毕后才能点 Utils.waitPageLoaded(script); Utils.findByAwaitAndClick(By.xpath("//div/ul/li[contains(text(), '" + text + "')]")); } }