public static IWebElement GetElement(OpenQA.Selenium.IWebDriver webDriver, By selector, int maxRetry = 4, int interval = 2) { if (selector == null) { return(null); } int currentRetry = 0; IWebElement element = null; do { try { element = webDriver.FindElement(selector); } catch (System.Exception) { webDriver.Manage().Timeouts().ImplicitlyWait(System.TimeSpan.FromSeconds(interval)); System.Threading.Thread.Sleep(interval * 1000); } //if (element == null) //{ // webDriver.Manage().Timeouts().ImplicitlyWait(System.TimeSpan.FromSeconds(interval)); // System.Threading.Thread.Sleep(interval * 1000); //} } while (element == null && currentRetry++ < maxRetry); return(element); }
public static void CreateScreenshot(OpenQA.Selenium.IWebDriver webDriver, Environment.IEnvironment environment, string fileName) { string filePath = Path.Combine(environment.OutputFolder, fileName); Screenshot screenshotInstance = ((ITakesScreenshot)webDriver).GetScreenshot(); screenshotInstance.SaveAsFile(filePath, System.Drawing.Imaging.ImageFormat.Png); }
public SeleniumHelper(Browsers theBrowser, bool IsLoadPicture, bool IsLoadJS) { this.browser = theBrowser; _IsLoadPicture = IsLoadPicture; _IsLoadJS = IsLoadJS; wd = InitWebDriver(); }
public static byte[] GetScreamShot(OpenQA.Selenium.IWebDriver driver, string nome) { Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot(); //ICapabilities capabilities = ((RemoteWebDriver)driver).Capabilities; //var uri = ""; //FileInfo info = null; //int i = 0; //do //{ // nome = nome.Replace("/", "-").Trim(); // uri = @"C:\" + nome + i + ".png"; // info = new FileInfo(uri); // i++; //} while (info.Exists); //var file = info.Create(); //file.Close(); //ss.SaveAsFile(uri, ScreenshotImageFormat.Png); return(ss.AsByteArray); }
/// <summary> /// 清空执行环境状态数据 /// </summary> public void cleanUp() { string message = string.Empty; if (_WebDriver == null) { return; } clearAllCookies(); try { _WebDriver.Quit(); } catch (Exception ex) { message = string.Format("Exit webdriver faild,error message<{0}>.", ex.Message); _SystemLog.writeLog2Console(LOG_LEVEL.ERR, message); } try { _WebDriver.Dispose(); } catch (Exception ex) { message = string.Format("Dispose webdriver faild,error message<{0}>.", ex.Message); _SystemLog.writeLog2Console(LOG_LEVEL.ERR, message); } _WebDriver = null; CPublic.killProcess(PhantomjsDriverProcessId); }
/// <summary> /// Finds an element using the element name. /// </summary> /// <param name="driver">The <see cref="IWebDriver"/> to use in finding the element.</param> /// <param name="use">The locator string to use.</param> /// <returns>An <see cref="IWebElement"/> that matches the locator string.</returns> public IWebElement Find(OpenQA.Selenium.IWebDriver driver, string use) { string[] parts = use.Split(new char[] { ' ' }); ReadOnlyCollection <IWebElement> allElements = driver.FindElements(By.Name(parts[0])); IList <IWebElement> filteredElements = new List <IWebElement>(allElements); for (int i = 1; i < parts.Length; i++) { IFilterFunction filterBy = this.GetFilterFunction(parts[i]); if (filterBy == null) { throw new SeleniumException(use + " not found. Cannot find filter for: " + parts[i]); } string filterValue = this.GetFilterValue(parts[i]); filteredElements = filterBy.FilterElements(allElements, filterValue); } if (filteredElements != null && filteredElements.Count > 0) { return(filteredElements[0]); } throw new SeleniumException(use + " not found"); }
public void Browser() { driver = new ChromeDriver(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl("https://www.mailinator.com/"); }
public static bool Assert(UI.UIAssertAction action, OpenQA.Selenium.IWebDriver webDriver) { By locator = SeleniumUIHelper.GetBy(action.Element); OpenQA.Selenium.IWebElement element = SeleniumUIHelper.GetElement(webDriver, locator); switch (action.AssertType) { case UIActionSeertType.Text: return(CheckTextAssert(element, action)); case UIActionSeertType.CssClass: return(CheckCssClassAssert(element, action)); case UIActionSeertType.Count: System.Collections.ObjectModel.ReadOnlyCollection <IWebElement> elements = SeleniumUIHelper.GetElements(webDriver, locator); return(CheckCountElementAssert(elements, action)); case UIActionSeertType.Browser: return(CheckBrowserAssert(webDriver, action)); case UIActionSeertType.Exist: default: return(CheckExistAssert(element, action)); } }
public CommandExecutionResult Execute(OpenQA.Selenium.IWebDriver driver) { try { if (driver.Url.ToLower() != Target.ToLower()) { return(new CommandExecutionResult { CommandResult = CommandResult.Failed, Message = "Url not the same - expecting " + Target.ToLower() + " but was " + driver.Url.ToLower() }); } return(new CommandExecutionResult { CommandResult = CommandResult.Success, Message = string.Empty }); } catch (TimeoutException ex) { return(new CommandExecutionResult { CommandResult = CommandResult.TimedOut, Message = ex.Message }); } catch (Exception ex) { return(new CommandExecutionResult { CommandResult = CommandResult.Failed, Message = ex.Message }); } }
public CommandExecutionResult Execute(OpenQA.Selenium.IWebDriver driver) { try { IWebElement[] elements; try { elements = new Utility().GetTargetElements(driver, Target); } catch (StaleElementReferenceException ex) { //retrying elements = new Utility().GetTargetElements(driver, Target); } IWebElement[] elements2; try { elements2 = new Utility().GetTargetElements(driver, Target); } catch (StaleElementReferenceException ex) { //retrying elements2 = new Utility().GetTargetElements(driver, Target); } if (elements.Length == 0 || elements2.Length == 0) { return new CommandExecutionResult { CommandResult = CommandResult.CannotFindElement, Message = string.Format("Error Command: {1} Cannot find targets.", "DragAndDrop") } } ; if (elements.Length > 1 || elements2.Length > 1) { return new CommandExecutionResult { CommandResult = CommandResult.ResultYieldedMoreThanOne, Message = string.Format("More than one element found for targets") } } ; (new Actions(driver)).DragAndDrop(elements.First(), elements2.First()).Perform(); return(new CommandExecutionResult { CommandResult = CommandResult.Success, Message = string.Empty }); } catch (TimeoutException ex) { return(new CommandExecutionResult { CommandResult = CommandResult.TimedOut, Message = ex.Message + "\n" + ex.StackTrace }); } catch (Exception ex) { return(new CommandExecutionResult { CommandResult = CommandResult.Failed, Message = ex.Message + "\n" + ex.StackTrace }); } }
public CommandExecutionResult Execute(OpenQA.Selenium.IWebDriver driver) { try { IWebElement[] elements; try { elements = new Utility().GetTargetElements(driver, Target); } catch (StaleElementReferenceException ex) { //retrying elements = new Utility().GetTargetElements(driver, Target); } if (elements.Length > 1) { return new CommandExecutionResult { CommandResult = CommandResult.ResultYieldedMoreThanOne, Message = string.Format("More than one element found for target:{0} value:{1}", Target, Value) } } ; if (elements.Length == 0) { return new CommandExecutionResult { CommandResult = CommandResult.CannotFindElement, Message = string.Format("Cannot find target:{0} value:{1}", Target, Value) } } ; string text = elements.First().GetAttribute("value"); if (RuntimeValues.ContainsKey(Value)) { RuntimeValues[Value] = text; } else { RuntimeValues.Add(Value, text); } return(new CommandExecutionResult { CommandResult = CommandResult.Success, Message = string.Empty }); } catch (TimeoutException ex) { return(new CommandExecutionResult { CommandResult = CommandResult.TimedOut, Message = ex.Message }); } catch (Exception ex) { return(new CommandExecutionResult { CommandResult = CommandResult.Failed, Message = ex.Message }); } }
public CommandExecutionResult Execute(OpenQA.Selenium.IWebDriver driver) { try { string v = Value.Contains("$randomNumber") ? Value.Replace("$randomNumber", r.Next(100000, 999999).ToString()) : Value; IWebElement[] elements; try { elements = new Utility().GetTargetElements(driver, Target); } catch (StaleElementReferenceException ex) { //retrying elements = new Utility().GetTargetElements(driver, Target); } if (elements.Length == 0) { return new CommandExecutionResult { CommandResult = CommandResult.CannotFindElement, Message = string.Format("Cannot find target:{0} value:{1}", Target, Value) } } ; if (elements.Length > 1) { return new CommandExecutionResult { CommandResult = CommandResult.ResultYieldedMoreThanOne, Message = string.Format("More than one element found for target:{0} value:{1}", Target, Value) } } ; elements.First().Clear(); elements.First().SendKeys(v.Remove(v.Length - 2)); //minimum of two letters for (int i = v.Length - 2; i < v.Length; i++) { elements.First().SendKeys(v[i].ToString()); Thread.Sleep(1000); } return(new CommandExecutionResult { CommandResult = CommandResult.Success, Message = string.Empty }); } catch (TimeoutException ex) { return(new CommandExecutionResult { CommandResult = CommandResult.TimedOut, Message = ex.Message }); } catch (Exception ex) { return(new CommandExecutionResult { CommandResult = CommandResult.Failed, Message = ex.Message }); } }
public static bool TryNavigate(this OpenQA.Selenium.IWebDriver webDriver, string destinationUrl) { webDriver.Navigate().GoToUrl(destinationUrl); System.Threading.Thread.Sleep(1000); if (webDriver.Url != destinationUrl) { throw new Exception("Url is not " + destinationUrl); } return(true); }
public static bool TryClick(this OpenQA.Selenium.IWebElement webElement, OpenQA.Selenium.IWebDriver webDriver, string url) { webElement.Click(); System.Threading.Thread.Sleep(1000); if (webDriver.Url == url) { throw new Exception("Url is not " + url); } return(true); }
public CommandExecutionResult Execute(OpenQA.Selenium.IWebDriver driver) { try { if (!string.IsNullOrEmpty(Value)) { Target = Target + "|text=" + Value; } IWebElement[] elements; try { elements = new Utility(1).GetTargetElements(driver, Target); } catch (StaleElementReferenceException ex) { //retrying elements = new Utility(1).GetTargetElements(driver, Target); } catch (InvalidOperationException ex) { //retrying elements = new Utility(1).GetTargetElements(driver, Target); } if (elements.Length > 1) { return new CommandExecutionResult { CommandResult = CommandResult.ResultYieldedMoreThanOne, Message = string.Format("More than one element found for target:{0} value:{1}", Target, Value) } } ; if (elements.Length == 0) { return new CommandExecutionResult { CommandResult = CommandResult.CannotFindElement, Message = string.Format("Cannot find target:{0} value:{1}", Target, Value) } } ; return(new CommandExecutionResult { CommandResult = CommandResult.Success, Message = string.Empty }); } catch (TimeoutException ex) { return(new CommandExecutionResult { CommandResult = CommandResult.TimedOut, Message = ex.Message }); } catch (Exception ex) { return(new CommandExecutionResult { CommandResult = CommandResult.Failed, Message = ex.Message }); } }
public static void AutomateLogin(this OpenQA.Selenium.IWebDriver driver, string username, string password) { driver.WaitForHttpResponse(By.LinkText("Log On")); driver.FindElement(By.LinkText("Log On")).Click(); driver.WaitForHttpResponse(By.Id("UserName")); driver.FindElement(By.Id("UserName")).Clear(); driver.FindElement(By.Id("UserName")).SendKeys(username); driver.FindElement(By.Id("Password")).Clear(); driver.FindElement(By.Id("Password")).SendKeys(password); driver.FindElement(By.CssSelector("input.t-button")).Click(); }
// Metodo para esperar por un elemento en la pagina web // Retorna true si se encuentra el elemento en un maximo de 3 segundos, sino retorna false public static bool ElementIsPresent(OpenQA.Selenium.IWebDriver driver, By locator) { try { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3)); wait.Until(drv => drv.FindElement(locator)); return(true); } catch { } return(false); }
/// <summary> /// Finds an element using the ID and name. /// </summary> /// <param name="driver">The <see cref="IWebDriver"/> to use in finding the element.</param> /// <param name="use">The locator string to use.</param> /// <returns>An <see cref="IWebElement"/> that matches the locator string.</returns> /// <remarks>This method looks up elements first by ID, then by name.</remarks> public IWebElement Find(OpenQA.Selenium.IWebDriver driver, string use) { try { return(new IdLookupStrategy().Find(driver, use)); } catch (NoSuchElementException) { return(new NameLookupStrategy().Find(driver, use)); } }
private static bool IsElementPresent(OpenQA.Selenium.IWebDriver driver, By by) { try { driver.FindElement(by); return(true); } catch (NoSuchElementException) { return(false); } }
public void TestMethod1() { /* SETTINGS */ driver = new ChromeDriver(Environment.CurrentDirectory); IJavaScriptExecutor jse = (IJavaScriptExecutor)driver; SelectElement oSelect = new SelectElement(); driver.Navigate().GoToUrl("https://apspi2.uatweb.mbdom.rbbh/"); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); Thread.Sleep(2000); /* END OF SETTINGS */ /* LOGIN */ driver.FindElement(By.Id("txtUserName")).SendKeys("ivicasa"); driver.FindElement(By.Id("txtPassword")).SendKeys("obukaobuka"); driver.FindElement(By.Id("cmdOK")).Click(); /* END OF LOGIN */ /* PRETRAGA KLIJENATA */ driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.FindElement(By.Id("Label2")).Click(); Thread.Sleep(2000); driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.SwitchTo().Window(driver.WindowHandles.Last()); Thread.Sleep(2000); driver.FindElement(By.XPath("//input[@id='txtFilter']")).SendKeys("1230520"); driver.FindElement(By.Id("btnTrazi")).Click(); Thread.Sleep(1000); driver.FindElement(By.Name("dg1$ctl02$ctl00")).Click(); Thread.Sleep(2000); driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.SwitchTo().Window(driver.WindowHandles.Last()); Thread.Sleep(2000); /* END OF PRETRAGA KLIJENATA */ /* LAD */ driver.FindElement(By.XPath("//a[contains(text(),'LAD')]")).Click(); driver.FindElement(By.XPath("//a[contains(text(),'KONTROLA ZAHTJEVA')]")).Click(); Thread.Sleep(5000); ; }
public void PassedTest() { driver = new ChromeDriver(); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl("https://twitter.com/"); string screenshotpath = Capture(driver, "screenshot"); var test = extent.CreateTest("PassedTestMethod", "<h3>This test method gets passed<h3>"); test.Log(Status.Info, "First step of PassedTestMethod"); test.Pass("PassedTestMethod gets completed"); test.AddScreenCaptureFromPath(screenshotpath); driver.Quit(); }
/// <summary> /// looks for dom objects to comment on twitter /// </summary> /// <param name="startSearch">Dom</param> /// <param name="uName">name</param> /// <param name="uPass">pass</param> /// <param name="derValue">bbot utility value/login value</param> internal static void Run(OpenQA.Selenium.IWebDriver startSearch, string uName, string uPass, int derValue) { IWebDriver startDerSeach = BBotUtility.LogMeIn(startSearch, uName, uPass, derValue); IWebElement findDerEle; startDerSeach.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10.0)); findDerEle = startDerSeach.FindElement(By.XPath("//div[@id='tweet-box-mini-home-profile']")); findDerEle.Click(); findDerEle.SendKeys(TwitSpecial); System.Threading.Thread.Sleep(1000); findDerEle = startDerSeach.FindElement(By.XPath("//button[@class='btn primary-btn tweet-action js-tweet-btn']")); findDerEle.Click(); }
public void TestIntialise() { #region Code Injection ClearBrowser(); string ieServerFilePath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, "UnifiedTools", "IEWebDriver"); driver = UnifiedWebControlConfig.IWebDriverConfig(ieServerFilePath); driver.Manage().Window.Maximize(); driver.Manage().Cookies.DeleteAllCookies(); wait = UnifiedWebControlConfig.ExplicitWaitConfig(driver, 60); unifiedReport = Instance; unifiedLogCollection = new List <UnifiedTest>(); WiniumDriver.WiniumInitiate(); #endregion }
/// <summary> /// input type="text"への入力・削除 /// </summary> /// <param name="driver"></param> /// <param name="elementId"></param> /// <param name="value"></param> private static void EditTextField(OpenQA.Selenium.IWebDriver driver) { var element = driver.FindElement(OpenQA.Selenium.By.Id("id_input_text")); // <input type="text">へデータを設定 // なお、既にデータがあったり複数回の入力の場合、 // データは追記されていく element.SendKeys("テキスト"); element.SendKeys("txt"); // <input type="text">のデータ削除 element.Clear(); }
public void GivenIVerifyPage(string text) { //Wait for the page to load Libary.WaitForPageLoad(10); //get page text OpenQA.Selenium.IWebDriver browser = TestRunnerInterface.Map.loginPage.browser; var pageText = browser.FindElement(By.TagName("body")).Text; if (!pageText.Contains(text)) { error = true; errorString = ("Page Test(" + text + ") not found"); } }
// public ScenarioContext sc; // public FeatureContext fc; // public ContextInjection c; public Browser(WebDriver webdriver, ScenarioContext scenarioContext, FeatureContext featureContext) { System.Diagnostics.Debugger.Break(); //_browserDriver = browserDriver; // driver = browserDriver._driver; // wait = browserDriver._wait; driver = webdriver.Current; wait = webdriver.Wait; //_featureContext = featureContext; // System.Diagnostics.Debugger.Break(); // _featureContext.Add("driver", driver); // _featureContext.Add("testString", "test"); _scenarioContext = scenarioContext; // _scenarioContext.Add("driver", driver); }
public void LaunchSuite() { wd = new ChromeDriver(@"..\..\..\..\MONKEY_PAGE\packages\Selenium.Chrome.WebDriver.76.0.0\driver\"); wd.Navigate().GoToUrl(TestContext.DataRow["Link"].ToString()); Thread.Sleep(1000); int code = 0; code = Convert.ToInt32(TestContext.DataRow["Action"].ToString()); switch (code) { case 0: randomComic(); break; case 1: latestComic(); break; case 2: prevStrip(); break; case 3: history(); break; case 4: openDec4(); break; case 5: openJun19(); break; case 6: openMay30(); break; case 7: verify(); break; default: break; } }
public CommandExecutionResult Execute(OpenQA.Selenium.IWebDriver driver) { try { int timeout = 10; bool notFound = false; if (!string.IsNullOrEmpty(Value)) { Target = Target + "|text=" + Value; } IWebElement[] elements; try { notFound = new Utility(1).WaitingForElementNotPresent(driver, Target, timeout); } catch (StaleElementReferenceException ex) { //retrying notFound = new Utility(1).WaitingForElementNotPresent(driver, Target, timeout); } if (!notFound) { return new CommandExecutionResult { CommandResult = CommandResult.CannotFindElement, Message = string.Format("Target exist:{0} value:{1}", Target, Value) } } ; return(new CommandExecutionResult { CommandResult = CommandResult.Success, Message = string.Empty }); } catch (TimeoutException ex) { return(new CommandExecutionResult { CommandResult = CommandResult.TimedOut, Message = ex.Message }); } catch (Exception ex) { return(new CommandExecutionResult { CommandResult = CommandResult.Failed, Message = ex.Message }); } }
public bool CopyStaticDriver(string baseUrl = null) { if (_webDriverCoreStatic == null) { return(false); } _webDriver = _webDriverCoreStatic._webDriver; _webDriverBacked = _webDriverCoreStatic._webDriverBacked; _timeout = _webDriverCoreStatic._timeout; _canceled = false; _baseUrl = string.IsNullOrEmpty(baseUrl) ? _webDriverCoreStatic._baseUrl : baseUrl; _capabilities = _webDriverCoreStatic._capabilities; _preferences = _webDriverCoreStatic._preferences; _extensions = _webDriverCoreStatic._extensions; _arguments = _webDriverCoreStatic._arguments; _profile = _webDriverCoreStatic._profile; _proxy = _webDriverCoreStatic._proxy; _isStartedRemotely = _webDriverCoreStatic._isStartedRemotely; return(true); }
private QA.IWebDriver InitWebDriver() { QA.IWebDriver theDriver = null; switch (this.browser) { case Browsers.IE: { QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions(); _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true; theDriver = new QA.IE.InternetExplorerDriver(_ieOptions); }; break; case Browsers.Chrome: { theDriver = new QA.Chrome.ChromeDriver(); }; break; case Browsers.Firefox: { theDriver = new QA.Firefox.FirefoxDriver(); }; break; case Browsers.Safari: { theDriver = new QA.Safari.SafariDriver(); }; break; case Browsers.PhantomJS: { theDriver = new QA.PhantomJS.PhantomJSDriver(); }; break; default: { QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions(); _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true; theDriver = new QA.IE.InternetExplorerDriver(_ieOptions); }; break; } return(theDriver); }
internal WebElement(WebDriver webDriver, OpenQA.Selenium.IWebElement webElement) { this._wd = webDriver; _webDriver = _wd.WebDriver; _webElement = webElement; }