public IElementAssert DoNotExist(By findExpression, string message = null, TimeSpan maxWait = default(TimeSpan)) { return DoNotExist(() => Find.Element(findExpression, maxWait), findExpression.ToString(), message); }
public ReadOnlyCollection<IWebElement> FindElements(By @by) { if (@by.ToString().Contains("value")) return new ReadOnlyCollection<IWebElement>(_childElements); if(@by.ToString().Contains("text")) return new ReadOnlyCollection<IWebElement>(_childElements); return null; }
public static IWebElement GetElement(By locator) { if (IsElemetPresent(locator)) return ObjectRepository.Driver.FindElement(locator); else throw new NoSuchElementException("Element Not Found : " + locator.ToString()); }
public void WaitForElement(By by) { try { WebDriverWait wait = new WebDriverWait(this.driver, waitForElement); wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(by)); } catch { throw new TimeoutException(string.Format("Element with locator: {0} was not found in {1} seconds!", by.ToString(), secondsToWait)); } }
private string BuildStillCheckedExceptionText(By by, BaseTestDriver ext) { StringBuilder sb = new StringBuilder(); string customLoggingMessage = String.Format("#### The element with the location strategy: {0} ####\n ####WAS CHECKED!####", by.ToString()); sb.AppendLine(customLoggingMessage); string cuurentUrlMessage = String.Format("The URL when the test failed was: {0}", ext.Browser.Url); sb.AppendLine(cuurentUrlMessage); return sb.ToString(); }
private string BuildElementStillVisibleExceptionText(By by, BaseWebDriverTest ext) { StringBuilder sb = new StringBuilder(); string customLoggingMessage = String.Format("#### The element with the location strategy: {0} ####\n ####IS STILL VISIBLE!####", by.ToString()); sb.AppendLine(customLoggingMessage); string cuurentUrlMessage = String.Format("The URL when the test failed was: {0}", ext.Browser.Url); sb.AppendLine(cuurentUrlMessage); return sb.ToString(); }
public IWebElement GetElement(By by) { IWebElement foundElement; try { foundElement = this.Wait.Until<IWebElement>((d) => { return d.FindElement(by); }); } catch (TimeoutException ex) { log.Error(ex.Message); throw new ElementNotFoundException(by.ToString(), this.BaseUri); } return foundElement; }
public bool IsElementNotDisplayed(By element) { try { Driver.FindElement(element); return false; } catch (NoSuchElementException e) { return true; } catch (Exception e) { Console.WriteLine("Something is wrong came to exception instead of NoSuchelementException -- IsElementNotDisplayed({0}) -- Exception >> {1}",element.ToString(),e.Message); return false; } }
/** * Will wait for a specified web element to appear. If not found * an assertion will fail. * * @param by The description of the element * @return The matching element if found. */ public static IWebElement WaitForElement(By by) { for (int second = 0; ; second++) { if (second >= timeOut) { Execute.Assertion.FailWith("Timeout occurred while waiting for: " + by.ToString()); } try { return GetWebDriver().FindElement(by); } catch (Exception) { Thread.Sleep(1000); } } }
private WebElementCollection findElements(OpenQA.Selenium.By by, int timeoutms) { try { if (timeoutms < 1) { return(new WebElementCollection(this._wd, _webElement.FindElements(by))); } return(new WebElementCollection(this._wd, this._wd.WaitNotNullOrTrue(() => { var elts = _webElement.FindElements(by); return elts.Count == 0 ? null : elts; }, timeoutms))); } catch (Exception ex) { if (ex is NoSuchElementException || ex is TimeoutException) { throw new Exception("Elements not found. " + "Method=" + by.ToString().ToLower().Substring(3).Replace(": ", ", value=")); } throw; } }
public static IWebElement WaitForElement(this IWebDriver driver, By by, TimeSpan timeout) { var wait = new WebDriverWait(driver, timeout); return wait.Until((d) => { var value = default(IWebElement); try { value = d.FindElement(by); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Error detected while locating element {0}: ", by.ToString(), e.Message); } return value; }); }
public IWebElement GetElementWithText(By by, string text) { IWebElement foundElement = null; try { this.Wait.Until<bool>((d) => { foundElement = this.GetElement(by); return foundElement.Text.Contains(text); }); } catch (TimeoutException ex) { log.Error(ex.Message); throw new ElementNotFoundException(by.ToString(), this.BaseUri); } return foundElement; }
private WebElement findElement(OpenQA.Selenium.By by, int timeoutms, bool raise) { try { if (timeoutms < 1) { return(new WebElement(this._wd, _webElement.FindElement(by))); } return(new WebElement(this._wd, this._wd.WaitNoException(() => _webElement.FindElement(by), timeoutms))); } catch (Exception ex) { if (ex is NoSuchElementException || ex is TimeoutException) { if (raise) { throw new Exception("Element not found. " + "Method=" + by.ToString().ToLower().Substring(3).Replace(": ", ", value=")); } return(null); } throw; } }
public static Zu.AsyncWebDriver.By By(OpenQA.Selenium.By by) { var description = by.ToString(); if (description.StartsWith("By.Id: ")) { return(Zu.AsyncWebDriver.By.Id(description.Substring("By.Id: ".Length))); } if (description.StartsWith("By.LinkText: ")) { return(Zu.AsyncWebDriver.By.LinkText(description.Substring("By.LinkText: ".Length))); } if (description.StartsWith("By.Name: ")) { return(Zu.AsyncWebDriver.By.Name(description.Substring("By.Name: ".Length))); } if (description.StartsWith("By.XPath: ")) { return(Zu.AsyncWebDriver.By.XPath(description.Substring("By.XPath: ".Length))); } if (description.StartsWith("By.ClassName[Contains]: ")) { return(Zu.AsyncWebDriver.By.ClassName(description.Substring("By.ClassName[Contains]: ".Length))); } if (description.StartsWith("By.PartialLinkText: ")) { return(Zu.AsyncWebDriver.By.PartialLinkText(description.Substring("By.PartialLinkText: ".Length))); } if (description.StartsWith("By.TagName: ")) { return(Zu.AsyncWebDriver.By.TagName(description.Substring("By.TagName: ".Length))); } if (description.StartsWith("By.CssSelector: ")) { return(Zu.AsyncWebDriver.By.CssSelector(description.Substring("By.CssSelector: ".Length))); } throw new NotSupportedException(description); }
public void WaitForElementNotPresent(By by) { try { var currentElement = this.Driver.FindElement(by); bool notVisible = this.Wait.Until<bool>((d) => { return !currentElement.Displayed; }); if (notVisible) { return; } throw new ElementStillPresentException(by.ToString(), this.BaseUri); } catch (NoSuchElementException ex) { log.Info(ex.Message); return; } catch (TimeoutException ex) { log.Error(ex.Message); throw new ElementStillPresentException(by.ToString(), this.BaseUri); } }
/// <summary> /// Defines the locator parts ("How" and "Using"), sets the current By locator and uses that By locator to set the current element /// </summary> /// <param name="by">Current By value</param> public void setBy(By by) { //Split the By locator into the "How" and "Using" parts arrLocator = by.ToString().Split(':'); this.by = by; //Set the current element this.element = getDriver().FindElement(getBy()); }
public static void WaitForNotVisible(this IWebDriver driver, By by, int timeout = 0) { if (timeout == 0) timeout = Config.Settings.runTimeSettings.ElementTimeoutSec; var then = DateTime.Now.AddSeconds(timeout); for (var now = DateTime.Now; now < then; now = DateTime.Now) { var eles = driver.FindElements(by); if (eles.Count == 0 || !eles[0].Displayed) return; Common.Delay(1000); } throw new ElementNotVisibleException(string.Format("Element ({0}) was still visible after {1} seconds", by.ToString(), timeout)); }
internal static Dictionary<string, string> ReadElementAttributes(By by, IWebDriver webDriver) { /* * [ { "Key": "href", "Value": "http://example.com" }, { "Key": "class", "Value": " " } ] */ var result = new Dictionary<string, string>(); var elements = webDriver.FindElements(by); if (elements.Count == 0) { throw new NotFoundException("ReadElementAttributes: Element was not found" + by.ToString()); } var currentElement = elements[0]; IJavaScriptExecutor jsExec = webDriver as IJavaScriptExecutor; string json = (string)jsExec.ExecuteScript( @" var jsonResult = ""[\n""; var attrs = arguments[0].attributes; for (var l = 0; l < attrs.length; ++l) { var a = attrs[l]; var name = a.name.replace(/\\/g, ""\\\\"").replace(/\""/g, ""\\\""""); var value = a.value.replace(/\\/g, ""\\\\"").replace(/\""/g, ""\\\""""); jsonResult += '{ ""Key"": ""' + name + '"", ""Value"": ""' + value + '""},'; } jsonResult += ""]\n""; return jsonResult; ", currentElement); MyLog.Write("JSON:\n" + json); var attributesList = DeserializeAttributesFromJson(json); foreach (var attr in attributesList) { result.Add(attr.Key, attr.Value); } result.Add("TagName", currentElement.TagName); return result; }
private static void AssertLocatorValue(IWebElement element, By findBy) { var proxy = element as WebElement; if (proxy != null) { if (proxy.Locators.Any(l => l.ToString() == findBy.ToString())) { return; } var properties = proxy.Locators.Count > 0 ? string.Join(", ", proxy.Locators) : "NONE"; Assert.Fail( "Element should have contained property '{0}' but did not. Available Properties: {1}", findBy, properties); } Assert.Fail("Instance of this class cannot be inspected."); }
public static IWebElement WaitForElementDisplayed(this IWebDriver driver, By by, int timeoutInSeconds = 10) { try { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); if (wait.Until<bool>(x => x.FindElement(by).Displayed)) { return driver.FindElement(by); } else { ITakesScreenshot screenshotDriver = driver as ITakesScreenshot; if (screenshotDriver != null) { string filename = string.Format("webdriverwait-failure{0}.png", DateTime.Now.Ticks); string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename); Screenshot screenshot = screenshotDriver.GetScreenshot(); screenshot.SaveAsFile(fullPath, ImageFormat.Png); Console.WriteLine("Took screenshot: {0} ", fullPath); } return null; } } catch (WebDriverException e) { Assert.Fail("Unable to find element '{0}' on '{1}' - {2}", by.ToString(), driver.Url, e.Message); return null; } }
public static bool IsElementDisplayed(this IWebDriver driver, By by, int timeoutInSeconds = 10) { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); try { bool result = wait.Until<bool>(x => x.FindElement(by).Displayed); return result; } catch (WebDriverException e) { Assert.Fail("Unable to find element '{0}' on '{1}' - {2}", by.ToString(), driver.Url, e.Message); return false; } }
private IWebElement TryToFindElement(By by) { try { //return _wait.Until<IWebElement>(x => x.FindElement(by)); //return _wait.Until(ExpectedConditions.ElementIsVisible(by)); return _wait.Until(ExpectedConditions.ElementExists(by)); } catch (Exception) { throw new ElementNotFound(by.ToString()); } }
/// <summary> /// Finds the elements, wait until they're visible. /// </summary> /// <returns>The elements visible.</returns> /// <param name="by">By.</param> /// <param name="timeoutInSeconds">Timeout in seconds.</param> public static ReadOnlyCollection<IWebElement> FindElementsVisible(By by, double timeoutInSeconds = 15.0) { IWebDriver driver = Factory.Instance; Console.WriteLine("FindElements by '{0}' timeout '{1}'", by.ToString(), timeoutInSeconds); if (timeoutInSeconds > 0) { var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); wait.Until(ExpectedConditions.ElementIsVisible(by)); return driver.FindElements(by); } return driver.FindElements(by); }
public void WaitForNotChecked(By by) { IWebElement currentElement = this.GetElement(by); bool isSelected = currentElement.Selected; if (!isSelected) { Log.ErrorFormat("The element with find expression {0} was checked.", by.ToString()); throw new StillCheckedException(by, this); } }
/// <summary> /// Pauses play until a given element is no longer on the DOM. /// <para>@param by - the by selector for the given element</para> /// <para>@param timeout (optional) - the time, in milliseconds, to wait for the element to be deleted.</para> /// <para>If no time is given for the timeout, will use the default timeout.</para> /// </summary> protected void WaitForElementToBeDeleted(By by, int timeout) { var _stopwatch = new Stopwatch(); _stopwatch.Start(); while (FindAll(by).Count > 0) { if (_stopwatch.ElapsedMilliseconds > timeout) { string errMsg = string.Format( "Element '{0}' was still visible after {1} seconds!", by.ToString(), timeout / 1000); throw new WrongPageException(errMsg); } } _stopwatch.Stop(); _stopwatch.Reset(); }
/// <summary> /// Waits for element visible. /// </summary> /// <returns>The for element visible.</returns> /// <param name="by">By.</param> public static IWebElement WaitForElementVisible(By by) { IWebDriver driver = Factory.Instance; double timeoutInSeconds = Factory.DefaultTimeoutValue; Console.WriteLine("WaitForElementVisible by '{0}'", by.ToString()); var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); return wait.Until(ExpectedConditions.ElementIsVisible(by)); }
/// <summary> /// Pauses play until a given element becomes visible. /// <para>@param by - the by selector for the given element</para> /// <para>@param timeout (optional) - the time, in milliseconds, to wait for the element to exist</para> /// <para>If no time is given for the timeout, will use the default timeout.</para> /// </summary> protected void WaitForElementToExist(By by, int timeout) { var _stopwatch = new Stopwatch(); _stopwatch.Start(); while (FindAll(by).Count == 0) { if (_stopwatch.ElapsedMilliseconds > timeout) { var errMsg = string.Format( "Could not find element '{0}' after {1} seconds!", by.ToString(), timeout / 1000); throw new ElementNotVisibleException(errMsg); } } _stopwatch.Stop(); _stopwatch.Reset(); }
public static IWebElement WaitForPresent(this IWebDriver driver, By by, int timeout = 0) { if (timeout == 0) timeout = Config.Settings.runTimeSettings.ElementTimeoutSec; var then = DateTime.Now.AddSeconds(timeout); for (var now = DateTime.Now; now < then; now = DateTime.Now) { var eles = driver.FindElements(by); if (eles.Count > 0) return eles[0]; Common.Delay(1000); } throw new NoSuchElementException(string.Format("Element ({0}) was not present after {1} seconds", by.ToString(), timeout)); }
public IWebElement FindElement(By @by) { IWebElement element = _elements.First(x => x.Key.ToString() == @by.ToString()).Value; return element; }
/// <summary>Finds the element by the given selector /// <para> @param by - the by selector for the given element</para> /// </summary> protected IWebElement Find(By by) { var _stopwatch = new Stopwatch(); _stopwatch.Start(); while (_driver.FindElements(by).Count == 0) { if (_stopwatch.ElapsedMilliseconds > _defaultTimeout) { throw new NoSuchElementException("Could not find element " + by.ToString()); } } _stopwatch.Stop(); _stopwatch.Reset(); return _driver.FindElement(by); }
protected void Click(By by) { try { FindElement(by).Click(); } catch (ElementNotVisibleException ex) { throw new ElementNotVisibleException("Element is not visible " + by, ex); } catch (StaleElementReferenceException ex) { throw new StaleElementReferenceException(by.ToString(), ex); } }
public void WaitForChecked(By by) { try { var currentElement = this.GetElement(by); bool notChecked = this.Wait.Until<bool>((d) => { return currentElement.Selected; }); if (notChecked) { return; } throw new ElementStillNotCheckedException(by.ToString(), this.BaseUri); } catch (NoSuchElementException ex) { log.Info(ex.Message); return; } catch (TimeoutException ex) { log.Error(ex.Message); throw new ElementStillNotCheckedException(by.ToString(), this.BaseUri); } }
/// <summary>Selects an option from a select box based on text /// <para> @param by - the by selector for the given element </para> /// <para> @param optionText - the text to select by </para> /// </summary> internal void SelectByText(By by, string optionText) { if (_logActions) { _logger.LogMessage(string.Format("Selct: {0}", optionText)); _logger.LogMessage(string.Format(" at: {0}", by)); } var select = new SelectElement(Find(by)); if (!select.Equals(null)) { try { select.SelectByText(optionText); } catch { var errMsg = String.Format( "PageObjectBase: There is no option '{0}' in {1}.", optionText, by); throw new InvalidSelectOptionException(errMsg); } } else { string errMsg = "Cannot find element " + by.ToString(); throw new NoSuchElementException(errMsg); } }