public static DefaultWait<IWebDriver> GetWait(this IWebDriver driver, int seconds) { var wait = new DefaultWait<IWebDriver>(driver) { PollingInterval = TimeSpan.FromMilliseconds(100), Timeout = new TimeSpan(0, 0, seconds) }; return wait; }
public SearchingInterceptor(IEnumerable<By> bys, IElementLocator locator, TimeOutDuration waitingTimeSpan, bool shouldCache) { this.locator = locator; this.waitingTimeSpan = waitingTimeSpan; this.shouldCache = shouldCache; this.bys = bys; waitingForElementList = new DefaultWait<IElementLocator>(locator); waitingForElementList.IgnoreExceptionTypes(new Type[] { typeof(StaleElementReferenceException)}); }
public static IWebElement FindElement(this IWebElement element, By by, int timeoutInSeconds) { if (timeoutInSeconds <= 0) return element.FindElement(@by); var wait = new DefaultWait<IWebElement>(element) { Timeout = TimeSpan.FromSeconds(timeoutInSeconds), PollingInterval = TimeSpan.FromMilliseconds(500.0) }; wait.IgnoreExceptionTypes(new[] { typeof(NotFoundException) }); return wait.Until(e => e.FindElement(@by)); }
/// <summary> /// Find an element, waiting until a timeout is reached if necessary. /// </summary> /// <param name="context">The search context.</param> /// <param name="by">Method to find elements.</param> /// <param name="timeout">How many seconds to wait.</param> /// <param name="displayed">Require the element to be displayed?</param> /// <returns>The found element.</returns> public static IWebElement FindElement(this ISearchContext context, By by, uint timeout, bool displayed = false) { var wait = new DefaultWait<ISearchContext>(context); wait.Timeout = TimeSpan.FromSeconds(timeout); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); return wait.Until(ctx => { var elem = ctx.FindElement(by); if (displayed && !elem.Displayed) return null; return elem; }); }
public void TestDefaultWait() { NavigationHelper.NavigateToUrl(ObjectRepository.Config.GetWebsite()); LinkHelper.ClickLink(By.LinkText("File a Bug")); TextBoxHelper.TypeInTextBox(By.Id("Bugzilla_login"), ObjectRepository.Config.GetUsername()); TextBoxHelper.TypeInTextBox(By.Id("Bugzilla_password"), ObjectRepository.Config.GetPassword()); ButtonHelper.ClickButton(By.Id("log_in")); LinkHelper.ClickLink(By.LinkText("Testng")); ObjectRepository.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1)); GenericHelper.WaitForWebElement(By.Id("bug_severity"), TimeSpan.FromSeconds(50)); IWebElement ele = GenericHelper.WaitForWebElementInPage(By.Id("bug_severity"), TimeSpan.FromSeconds(50)); DefaultWait<IWebElement> wait = new DefaultWait<IWebElement>(ObjectRepository.Driver.FindElement(By.Id("bug_severity"))); wait.PollingInterval = TimeSpan.FromMilliseconds(200); wait.Timeout = TimeSpan.FromSeconds(50); wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException)); Console.WriteLine("After wait : {0}", wait.Until(this.Changeofvalue())); }
public static IWebElement GetWebElement(this IWebDriver webDriver, By by) { IWebElement webElement = null; webElement = webDriver.FindElement(by); webElementFluentWait = new DefaultWait <IWebElement>(webElement); webElementFluentWait.Timeout = TimeSpan.FromSeconds(appConfigMember.ObjectTimeout); webElementFluentWait.PollingInterval = TimeSpan.FromMilliseconds(appConfigMember.PollingInterval); webElementFluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(StaleElementReferenceException)); Func <IWebElement, IWebElement> waiter = new Func <IWebElement, IWebElement>((IWebElement ele) => { if (webElement.Enabled & webElement.Displayed & webDriver.FindElement(by).Size.Width > 0 & webDriver.FindElement(by).Size.Height > 0) { return(webElement); } else { return(null); } }); webElementFluentWait.Until(waiter); return(webElement); }
public static IWebElement ForWebElement(IWebElement element, TimeSpan?timeSpan = null) { Wait.Time(100); DefaultWait <IWebElement> wait = new DefaultWait <IWebElement>(element) { Timeout = timeSpan ?? Config.WaitForWebElementDisplayed, PollingInterval = TimeSpan.FromMilliseconds(500) }; Func <IWebElement, bool> condition = (IWebElement elementToCheck) => { try { return(elementToCheck.Displayed); } catch (NoSuchElementException exception) { return(false); } catch (TargetInvocationException exception) { if (exception.InnerException is NoSuchElementException) { return(false); } throw; } catch (StaleElementReferenceException exception) { return(false); } }; wait.Until(condition); return(element); }
public void Perform(IWebElement ele, string operation, string sendvalue) { WebDriverWait wait = new WebDriverWait(Properties.driver, TimeSpan.FromSeconds(10)); DefaultWait <IWebDriver> fluentWait = new DefaultWait <IWebDriver>(Properties.driver); fluentWait.Timeout = TimeSpan.FromSeconds(20); fluentWait.PollingInterval = TimeSpan.FromSeconds(4); fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException)); // fluentWait.IgnoreExceptionTypes(typeof(ElementNotVisibleException)); fluentWait.Until <IWebElement>((d) => { //IWebElement element = d.FindElement(By.Id("myid")); if (ele.Displayed && ele.Enabled && (ele.GetAttribute("aria-disabled") == null)) { return(ele); } return(null); }); smallwait(); if (operation.Equals("click")) { ele.Click(); } else if (operation.Equals("sendkeys")) { ele.Click(); ele.SendKeys(sendvalue.Replace("(", "{(}")); } else if (operation.Equals("clear")) { ele.Clear(); } }
/// <summary> /// Waits for the element to meet a certain condition. /// </summary> /// <param name="element">The element.</param> /// <param name="waitCondition">The wait condition.</param> /// <param name="timeout">The timeout to wait before failing.</param> /// <returns><c>true</c> if the condition is met, <c>false</c> otherwise.</returns> public override bool WaitForElement(IWebElement element, WaitConditions waitCondition, TimeSpan?timeout) { var waiter = new DefaultWait <IWebElement>(element); waiter.Timeout = timeout.GetValueOrDefault(waiter.Timeout); waiter.IgnoreExceptionTypes(typeof(ElementNotVisibleException), typeof(NotFoundException)); try { switch (waitCondition) { case WaitConditions.NotExists: waiter.Until(e => !e.Displayed); break; case WaitConditions.Enabled: waiter.Until(e => e.Enabled); break; case WaitConditions.NotEnabled: waiter.Until(e => !e.Enabled); break; case WaitConditions.Exists: waiter.Until(e => e.Displayed); break; } } catch (WebDriverTimeoutException) { return(false); } return(true); }
public void CreateRetrospective_SubmitWithoutValidation_ShowsValidationMessages() { // Given this.Page.Navigate(this.App); // When this.Page.Submit(); // Then string[] messages = new DefaultWait <CreateRetrospectivePage>(this.Page) .Until(p => { ReadOnlyCollection <IWebElement> collection = p.GetValidationMessages(); if (collection.Count == 0) { return(null); } return(collection); }) .Select(el => el.Text) .ToArray(); Assert.That(messages, Has.One.Contain("'Title' must not be empty")); Assert.That(messages, Has.One.Contain("'Facilitator Passphrase' must not be empty")); }
protected void WaitUntil(Func <object, bool> a, string message = null, int timeOutInSec = 10, bool throwExceptionIfTimeoutReached = true) { var wait = new DefaultWait <object>(new object(), new SystemClock()); if (message != null) { wait.Message = message; } wait.Timeout = TimeSpan.FromSeconds(timeOutInSec); wait.IgnoreExceptionTypes(typeof(Exception)); try { wait.Until(a); } catch (Exception) { if (throwExceptionIfTimeoutReached) { throw; } } }
public static IWebElement waitForElement(this By element, int seconds) { By newElement = element; //try //{ // var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(seconds)); // return wait.Until(drv => drv.FindElement(newElement)); //} //catch (Exception ex) //{ // logMe(null, ex); // return null; //} try { var wait = new DefaultWait <RemoteWebDriverExtended>(driver); wait.Timeout = TimeSpan.FromSeconds(seconds); wait.PollingInterval = TimeSpan.FromMilliseconds(500); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); return(wait.Until <IWebElement>(ExpectedConditions.ElementExists(newElement))); } catch (Exception ex) { return(null); } }
/// <summary> /// /// </summary> /// <returns></returns> public TaskResult Scrape(TransactionParameter transactionParameter) { var counter = 0; foreach (var import in _imports) { counter++; Logger.Info($"processing {counter} out of {_imports.Count}"); LogicalThreadContext.Properties["symbol"] = import.Symbol; var importTracker = new ImportTracker(import.Symbol, transactionParameter.FromDate); try { //create new transaction parameter to avoid threading issues var parameter = new TransactionParameter { Symbol = import.Symbol, FromDate = transactionParameter.FromDate, ToDate = transactionParameter.ToDate }; _brokerTransactionSimulator.Simulate(parameter); var fluentWait = new DefaultWait <IWebDriver>(_webDriver) { Timeout = TimeSpan.FromSeconds(30), PollingInterval = TimeSpan.FromMilliseconds(250) }; fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException)); var rows = fluentWait .Until(x => x.FindElements(By.XPath("/html/body/form/table/tbody/tr"))); if (rows.Count > 0) { Logger.Info("initiating transaction builder"); var brokerTransactions = _brokerTransactionBuilder.Build(rows.ToList(), parameter); Logger.Info("initiating transaction process"); _brokerTransactionProcessor.Process(brokerTransactions); _brokerTransactionBuilder.Transactions.Clear(); importTracker.Status = "Success"; Logger.Info($"broker transactions for completed for symbol: {import.Symbol}"); } importTracker.Status = "None"; } catch (Exception e) { Logger.Warn($"An issue trying to download broker transactions found, adding to retry queue for later processing", e); importTracker.Status = "Retry"; } //switch back to main frame to prevent _brokerTabNavigator.NavigateHeaderFrame(); _brokerTabNavigator.Navigate(true); _importProcessor.AddTracker(importTracker); } Logger.Info($"broker table scraping completed."); return(new TaskResult { IsSuccessful = true }); }
/// <summary> /// Create new instance of command builder /// </summary> public CommandBuilder() { _wait = new DefaultWait <CommandBuilder <TTarget> >(this); }
public void RetentionArch_Contact() { try { Console.WriteLine("Contact Retention & Archiving Operation Started"); DefaultWait <IWebDriver> waitRetention = new DefaultWait <IWebDriver>(driver); waitRetention.Timeout = TimeSpan.FromSeconds(60); waitRetention.PollingInterval = TimeSpan.FromSeconds(10); waitRetention.IgnoreExceptionTypes(typeof(NoSuchElementException)); waitRetention.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); waitRetention.IgnoreExceptionTypes(typeof(InvalidElementStateException)); waitRetention.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(NewContact)); waitRetention.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.VisibilityOfAllElementsLocatedBy(NewContact)); driver.SwitchTo().Frame(driver.FindElement(contentIFrame0)); ele_SearchForRecord = driver.FindElement(SearchForRecord); ele_SearchForRecord.SendKeys(searchRec); ele_SearchForRecord.SendKeys(OpenQA.Selenium.Keys.Enter); Thread.Sleep(2000); // Wait until search table is loaded in search grid iWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(SearchGrid)); ele_SearchTable = driver.FindElement(SearchGrid); recordSize = ele_SearchTable.FindElements(By.TagName("tr")).Count; if (recordSize < 2) { Console.WriteLine("Multiple records are not present for entered search criteria"); log.Info("Multiple records are not present for entered search criteria"); Assert.AreEqual(true, false); } else { // Select Records to Deactivate ele_firstRecord = ele_SearchTable.FindElements(By.TagName("tr")).ElementAt(0); // Get the first record from search table ele_secondRecord = ele_SearchTable.FindElements(By.TagName("tr")).ElementAt(1); // Get the second record from search table Helper.IsJavaScriptActive(driver); contactRefNoRec0 = ele_firstRecord.FindElement(By.CssSelector("td:nth-child(2)")).Text.ToString(); contactRefNo1 = ele_firstRecord.FindElement(By.CssSelector("td:nth-child(12)>nobr>span")).Text.ToString(); contactRefNoRec1 = ele_secondRecord.FindElement(By.CssSelector("td:nth-child(2)")).Text.ToString(); contactRefNo2 = ele_secondRecord.FindElement(By.CssSelector("td:nth-child(12)>nobr>span")).Text.ToString(); Console.WriteLine("Contact Ref No. First Rec is" + contactRefNo1); Console.WriteLine("Contact Ref No. Second Rec is" + contactRefNo2); Console.WriteLine("Contact Ref name. First Rec is" + contactRefNoRec0); Console.WriteLine("Contact Ref Name. Second Rec is" + contactRefNoRec1); // Select first and second record for deactivate ele_firstRecCheckbox = ele_firstRecord.FindElement(By.CssSelector("td:nth-child(1)")); ele_secRecCheckbox = ele_secondRecord.FindElement(By.CssSelector("td:nth-child(1)")); ele_firstRecCheckbox.Click(); Thread.Sleep(2000); ele_secRecCheckbox.Click(); Thread.Sleep(2000); } } catch (Exception e) { log.Error(e.Message + "\n" + e.StackTrace + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Console.WriteLine(e.Message + "\n" + e.StackTrace + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Assert.AreEqual(true, false); } }
public static bool MatchCondition( this IWebElement element, Func<IWebElement, bool> predicate, int timeoutInSeconds) { if (timeoutInSeconds <= 0) return predicate(element); var wait = new DefaultWait<IWebElement>(element) { Timeout = TimeSpan.FromSeconds(timeoutInSeconds), PollingInterval = TimeSpan.FromMilliseconds(500.0) }; return wait.Until(predicate); }
public void AnimateResizeWidthAndHeight() { var resizablePage = new ResizablePage(this.driver); resizablePage.AnimateIncreaseWidthAndHeightBy(250, 200); resizablePage.AssertAnimation(); DefaultWait <IWebElement> wait = new DefaultWait <IWebElement>(resizablePage.AnimateResizeWindow); wait.Timeout = TimeSpan.FromMinutes(2); wait.PollingInterval = TimeSpan.FromMilliseconds(250); Func <IWebElement, bool> waiter = new Func <IWebElement, bool>((IWebElement ele) => { String styleAttrib = resizablePage.AnimateResizeWindow.GetAttribute("style"); if (!styleAttrib.Contains("overflow")) { return(true); } return(false); }); wait.Until(waiter); resizablePage.AssertAnimateNewSize(250, 200); /*Stop script for some time * * Thread.Sleep(6000); * driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(50); * driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(500); * driver.Manage().Timeouts().PageLoad =TimeSpan.FromSeconds(500); * * Case 1 (wait): * * WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“myId"))); * * WebDriverWait wait = new WebDriverWait(this.Driver, TimeSpan.FromSeconds(10)); * wait.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("input"))); * * wait.Until(driver => driver.FindElement(By.Id("someLabelId")).Text == "expectedValue") * * Case 2 (wait): * * WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1)); * Func<IWebDriver, bool> waitForElement = new Func<IWebDriver, bool>((IWebDriver Web) => * { * Console.WriteLine(Web.FindElement(By.Id("target")).GetAttribute("innerHTML")); * return true; * }); * wait.Until(waitForElement); * * Case 3 (wait): * * IWebElement element = driver.FindElement(By.Id("colorVar")); * DefaultWait<IWebElement> wait = new DefaultWait<IWebElement>(element); * wait.Timeout = TimeSpan.FromMinutes(2); * wait.PollingInterval = TimeSpan.FromMilliseconds(250); * * Func<IWebElement, bool> waiter = new Func<IWebElement, bool>((IWebElement ele) => * { * String styleAttrib = element.GetAttribute("style"); * if (styleAttrib.Contains("red")) * { * return true; * } * Console.WriteLine("Color is still " + styleAttrib); * return false; * }); * wait.Until(waiter); */ resizablePage.AnimateIncreaseWidthAndHeightBy(100); resizablePage.AssertAnimation(); wait.Timeout = TimeSpan.FromMinutes(2); wait.PollingInterval = TimeSpan.FromMilliseconds(250); wait.Until(waiter); resizablePage.AssertAnimateNewSize(100, 100); resizablePage.AnimateIncreaseWidthBy(100); resizablePage.AssertAnimation(); wait.Timeout = TimeSpan.FromMinutes(2); wait.PollingInterval = TimeSpan.FromMilliseconds(250); wait.Until(waiter); resizablePage.AssertAnimateNewSize(100, 0); resizablePage.AnimateIncreaseHeightBy(100); resizablePage.AssertAnimation(); wait.Timeout = TimeSpan.FromMinutes(2); wait.PollingInterval = TimeSpan.FromMilliseconds(250); wait.Until(waiter); resizablePage.AssertAnimateNewSize(0, 100); }
// FluenttWait Wait and Find element // This method behavior is exactly the same as the Explicit Wait Method /// set the browser Implict wait time = Explict wait time * 2 ///to prevent browser nosuchelement exception being displayed before the Impliict wait time expires /// <summary> /// Is Page Element Displayed with a Timeout Parameter /// </summary> /// <param name="browser"></param> /// <param name="searchType"></param> /// <param name="searchString"></param> /// <param name="seconds"></param> /// <returns></returns> public static bool FluenttWaitIsPageElementDisplayed(IWebDriver browser, RunTimeVars.ELEMENTSEARCH searchType, string searchString, int seconds) { //Date - 12/21/18 Can't read current browser.ImplicitWait time, get not implemented //set the browser Implict wait time = Explict wait time * 2 //to prevent Explict waits nosuchelement exception being displayed before the Impliict wait time expires browser.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(seconds * 2); //Fluent wait initialize DefaultWait <IWebDriver> fluentWait = new DefaultWait <IWebDriver>(browser); fluentWait.Timeout = TimeSpan.FromSeconds(seconds); fluentWait.PollingInterval = TimeSpan.FromMilliseconds(500); fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException)); var isFound = false; IWebElement element = null; try { if (searchType == RunTimeVars.ELEMENTSEARCH.ClassName) { element = fluentWait.Until(x => x.FindElement(By.ClassName(searchString))); } if (searchType == RunTimeVars.ELEMENTSEARCH.CssSelector) { element = fluentWait.Until(x => x.FindElement(By.CssSelector(searchString))); } if (searchType == RunTimeVars.ELEMENTSEARCH.ID) { element = fluentWait.Until(x => x.FindElement(By.Id(searchString))); } if (searchType == RunTimeVars.ELEMENTSEARCH.LinkText) { element = fluentWait.Until(x => x.FindElement(By.LinkText(searchString))); } if (searchType == RunTimeVars.ELEMENTSEARCH.PartialLinkText) { element = fluentWait.Until(x => x.FindElement(By.PartialLinkText(searchString))); } if (searchType == RunTimeVars.ELEMENTSEARCH.NAME) { element = fluentWait.Until(x => x.FindElement(By.Name(searchString))); } if (searchType == RunTimeVars.ELEMENTSEARCH.TagName) { element = fluentWait.Until(x => x.FindElement(By.TagName(searchString))); } if (searchType == RunTimeVars.ELEMENTSEARCH.XPATH) { element = fluentWait.Until(x => x.FindElement(By.XPath(searchString))); } //include this in the try section if (element.Displayed) { isFound = true; } else { isFound = false; } } catch { isFound = false; } //restore the browser Implict wait time = initial wait time browser.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(RunTimeVars.WEBDRIVERWAIT); return(isFound); }
public Page(IWebDriver driver) { this.driver = driver; webDriverWait = GetWebDriverWait(driver); }
public void TypesofWaits() { //**************** Explicit or Fluent waits //Navigates the browser to given URL driver.Navigate().GoToUrl("http://google.com"); check.Until(ExpectedConditions.ElementExists(By.Name("btnK"))); Assert.True(driver.Url.Contains("https://www.google"), "Validate Navigation to google url"); driver.Navigate().GoToUrl("https://www.facebook.com/");//Clicks on forward button of browser, navigates as per browseer history IWebElement CreateAccount = check.Until(ExpectedConditions.ElementToBeClickable(By.Name("websubmit"))); Assert.AreEqual(driver.Url, "https://www.facebook.com/", "Validate Navigation to facebook url"); //************** Default wait is Webdriver independent //Go to http://toolsqa.wpengine.com/automation-practice-switch-windows/ //There is a clock on the page that counts down till 0 from 60 second. //You have to wait for the clock to show text “Buzz Buzz” driver.Navigate().GoToUrl("http://toolsqa.wpengine.com/automation-practice-switch-windows/"); IWebElement element1 = driver.FindElement(By.Id("clock")); DefaultWait <IWebElement> wait1 = new DefaultWait <IWebElement>(element1); wait1.Timeout = TimeSpan.FromMinutes(2); wait1.PollingInterval = TimeSpan.FromMilliseconds(250); Func <IWebElement, bool> waiter = new Func <IWebElement, bool>((IWebElement ele) => { String styleAttrib = element1.Text; if (styleAttrib.Contains("Buzz")) { return(true); } Console.WriteLine("Current time is " + styleAttrib); return(false); }); wait1.Until(waiter); //Go to http://toolsqa.wpengine.com/automation-practice-switch-windows/ //There is a button which color will change after some time //You have to wait for the newc color driver.Navigate().GoToUrl("http://toolsqa.wpengine.com/automation-practice-switch-windows/"); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1)); Func <IWebDriver, bool> waitForElement = new Func <IWebDriver, bool>((IWebDriver Web) => { Console.WriteLine("Waiting for color to change"); IWebElement element = Web.FindElement(By.Id("target")); if (element.GetAttribute("style").Contains("red")) { return(true); } return(false); }); wait.Until(waitForElement); //Go to http://toolsqa.wpengine.com/automation-practice-switch-windows/ //There is a button which color will change after some time //You have to wait for the newc color //this time we'll return a element type only // driver.Navigate().GoToUrl("http://toolsqa.wpengine.com/automation-practice-switch-windows/"); // WebDriverWait wait2 = new WebDriverWait(driver, TimeSpan.FromMinutes(1)); // Func<IWebDriver, IWebElement> waitForElement2 = new Func<IWebDriver, IWebElement>((IWebDriver Web) => // { // Console.WriteLine("Waiting for color to change"); // IWebElement element = Web.FindElement(By.Id("target")); // if (element.GetAttribute("style").Contains("red")) // { // return element; // } // return null; // }); //// IWebElement targetElement = wait2.Until(waitForElement); //*****************conversion error is coming we need to look into this // Console.WriteLine("Inner HTML of element is " + targetElement.GetAttribute("innerHTML")); //**************** Implicit waits driver.Url = "http://facebook.com"; //Almost same as Navigate().GoToUrl() method driver.Manage().Timeouts().ImplicitWait = TimeSpan.MaxValue; //Implicit wait //wait till the time span max value(2.5hrs) Assert.AreEqual(driver.Url, "https://www.facebook.com/", "Validate Navigation to facebook url"); driver.Navigate().GoToUrl("http://google.com"); //Clicks on back button of browser, navigates back to previously visited url (browser history) Thread.Sleep(1000); //explicit wait Assert.True(driver.Url.Contains("http://google.com"), "Validate Navigation to google url"); driver.Url = "http://facebook.com"; //Almost same as Navigate().GoToUrl() method driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(10); }
public string ProductText() { DefaultWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[contains(text()[2], 'Product' )]"))); return(ProductAddedText.Text); }
private static IWebElement WaitTill(this IWebElement element, int timeOutSeconds, Func<IWebElement, bool> condition, string desc) { timeOutSeconds *= Settings.Default.WaitFactor; Trace.Write(BasePage.TraceLevelLow + desc); Trace.WriteLine("Max waiting time: " + timeOutSeconds + " sec"); var wait = new DefaultWait<IWebElement>(element); wait.Timeout = TimeSpan.FromSeconds(timeOutSeconds); wait.Until(condition); return element; }
public ContactPage SubmitForm() { SubmitButton.Click(); DefaultWait.Until(driver => driver.FindElement(By.Id("submit-btn")).Text != "SENDING..."); return(this); }
public static void EntireFlow() { IWebDriver driver; // var options = new InternetExplorerOptions(); //options.IntroduceInstabilityByIgnoringProtectedModeSettings = true; //driver = new InternetExplorerDriver(options); driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://frilp.com"); driver.Manage().Window.Maximize(); string currentwindow = driver.CurrentWindowHandle; //IJavaScriptExecutor js = (IJavaScriptExecutor)driver; //String script = "document.getElementById('btn_signin').click()"; //js.ExecuteScript(script); //Thread.Sleep(2000); driver.FindElement(By.Id("btn_signin")).Click(); var handles = driver.WindowHandles; string popupHandle = string.Empty; foreach (var handle in handles) { if (handle != currentwindow) { popupHandle = handle; break; } } driver.SwitchTo().Window(popupHandle); //WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(Duration)); DefaultWait <IWebDriver> wait = new DefaultWait <IWebDriver>(driver); wait.Timeout = TimeSpan.FromSeconds(5); wait.PollingInterval = TimeSpan.FromMilliseconds(500); wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(WebDriverTimeoutException)); bool isLogin = false; try { IWebElement element = wait.Until(ExpectedConditions.ElementExists(By.Id("email"))); } catch (WebDriverTimeoutException) { isLogin = true; } catch (NoSuchElementException) { isLogin = true; } if (!isLogin) { driver.FindElement(By.Id("email")).Clear(); driver.FindElement(By.Id("email")).SendKeys("Manishankar2"); driver.FindElement(By.Id("pass")).SendKeys("Maverick1234"); driver.FindElement(By.Name("login")).Click(); driver.SwitchTo().Window(currentwindow); } WebDriverWait wait5 = new WebDriverWait(driver, TimeSpan.FromSeconds(25)); wait5.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[@class='nav-top']//li[@id='link_ask']"))); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(25)); //driver.FindElement(By.Id("main_search_box")).SendKeys("restaurants"); //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(25)); //driver.FindElement(By.XPath("//*[@class='d_autocomplete_result_name' and contains(text(),'restaurants')]")).Click(); ////driver.FindElement(By.ClassName("d_autocomplete_result_name")).Click(); ////driver.FindElement(By.Id("main_search_box")).SendKeys(Keys.Enter); //WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(15)); //IWebElement elementToWait = wait1.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[@id='search_count_text']/*[contains(text(),'restaurants')]"))); ////driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(7000)); ////IJavaScriptExecutor js1 = (IJavaScriptExecutor)driver; ////String script1 = "document.getElementsByClassName('d_autocomplete_result_name')[0]"; ////string firstresult =(string)js1.ExecuteScript(script1); ////if (firstresult.Trim().ToLower() == "restaurants") ////{ //// IJavaScriptExecutor js2 = (IJavaScriptExecutor)driver; //// String script2 = "document.getElementsByClassName('d_autocomplete_result_name')[0].click()"; //// js2.ExecuteScript(script2); ////} //// Scroll Logic //int count = ScrollWebPage(driver, By.ClassName("business-name")); //// Check category and Duplicates //Dictionary<string, string> Restaurant = new Dictionary<string, string>(); //Dictionary<string, string> InvalidCategory = new Dictionary<string, string>(); //List<string> duplicate = new List<string>(); //List<string> duplicateandInvalidcategory = new List<string>(); //string businessname = string.Empty; //string businessid = string.Empty; //bool isrestaurant; //for (int i = 1; i < count; i++) //{ // var getcategory = driver.FindElements(By.XPath("(//div[@class='business-name'])[" + i + "]//a[@class='category_filter']")); // var getbusinessinfo = driver.FindElement(By.XPath("(//div[@class='business-name'])[" + i + "]//a[@class='business_profile']")); // businessid = getbusinessinfo.GetAttribute("business_id"); // businessname = getbusinessinfo.Text; // isrestaurant = getcategory.Any(l => l.GetAttribute("category_id") == "40"); // if (!isrestaurant) // { // try // { // InvalidCategory.Add(businessid, businessname); // } // catch (ArgumentException) // { // if (!duplicateandInvalidcategory.Contains(businessid)) // duplicateandInvalidcategory.Add(businessid); // } // } // else // { // try // { // Restaurant.Add(businessid, businessname); // } // catch (ArgumentException) // { // if (!duplicate.Contains(businessid)) // duplicate.Add(businessid); // } // } //} ////Back to the top //driver.FindElement(By.Id("btn_top")).Click(); // Select Questions in activity //driver.FindElement(By.ClassName("tab_activities")).Click(); //driver.FindElement(By.XPath("//li[@class='d_activity_entity_filter' and @entity_type='14']")).Click(); //int count1 = ScrollWebPage(driver,By.ClassName("d_activity_list_item")); //ASK Question driver.FindElement(By.XPath("//div[@class='nav-top']//li[@id='link_ask']")).Click(); JavaScriptExecutor(driver, "document.getElementById('link_ask').click()"); driver.FindElement(By.Id("ask_message")).SendKeys("Looking for a Chinese restaurant"); driver.FindElement(By.Id("ask_category_chooser")).SendKeys("restaurant"); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(25)); driver.FindElement(By.XPath("//*[@class='d_autocomplete_result_name' and contains(text(),'restaurants')]")).Click(); driver.FindElement(By.Id("ask_location_chooser")).SendKeys("Adyar"); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(25)); driver.FindElement(By.XPath("//*[@class='d_autocomplete_result_name' and contains(text(),'Adyar')]")).Click(); driver.FindElement(By.Id("usertaggerbox")).SendKeys("Manishankar"); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(25)); driver.FindElement(By.XPath("//*[@class='d_usertagger_result_name' and contains(text(),'manishankar ')]")).Click(); driver.FindElement(By.XPath("//div[contains(@class,'btn2') and contains(text(),'Ask')]")).Click(); driver.FindElement(By.XPath("//div[contains(@class,'btn2') and contains(text(),'Ok')]")).Click(); //WebDriverWait wait2 = new WebDriverWait(driver, TimeSpan.FromSeconds(150)); //IWebElement elementToWait1 = wait2.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[contains(@class,'postcontent')]/p[contains(text(),'restaurant')]"))); driver.FindElement(By.ClassName("logo_new")).SendKeys(Keys.Home); bool isvisible = false; int limit = 0; while (!isvisible) { driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5)); isvisible = driver.FindElements(By.XPath("//div[contains(@class,'postcontent')]/p[contains(text(),'restaurant')]")).Count > 0; driver.FindElement(By.XPath("//*[contains(@class,'d_activity_entity_filter') and @entity_type='14']")).Click(); limit++; if (limit > 30) { isvisible = true; } } //usertaggerbox // Signout driver.FindElement(By.ClassName("profile")).Click(); driver.FindElement(By.Id("link_signout")).Click(); //Close and Quit driver.Close(); driver.Quit(); //foreach(var invalid in InvalidCategory) //{ // Console.WriteLine(invalid.Value+ Environment.NewLine); //} Console.ReadLine(); }
public Page(IWebDriver driver) { fluentWait = GetFluentWait(driver); PageFactory.InitElements(driver, this); this.driver = driver; }
public Basepage(IWebDriver driver) { Wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); Component = Wait.Until(ExpectedConditions.ElementIsVisible(By.TagName("body"))); }
public void TestMethod1() { driver = new ChromeDriver(); driver.Manage().Window.Maximize(); //driver.Url = "http://www.ankpro.com/"; driver.Url = "http://uitestpractice.com/students/Select"; wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); //Webdriver wait syntax wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); //webdriver ignore syntax fluentwait = new DefaultWait <IWebDriver>(driver); //Fluent wait syntax fluentwait.Timeout = TimeSpan.FromSeconds(5); //Fluent wait timeout fluentwait.PollingInterval = TimeSpan.FromMilliseconds(250); //fluent wait pollingInterval fluentwait.IgnoreExceptionTypes(typeof(NoSuchElementException)); fluentwait.Message = "Element not found"; //var login = wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText //("Log in"))); //login.Click();//Using webdriver wait to click login by linktext //var login = fluentwait.Until(z=> z.FindElement(By.LinkText //("Log in"))); //login.Click();//Using webdriver wait to click login by linktext //var checkbox = fluentwait.Until(m => m.FindElement(By.XPath //(".//*[starts-with(@id,'Rem')]"))); //checkbox.Click(); //bool selected = driver.FindElement(By.XPath(".//*[starts-with(@id,'Rem')]")).Selected; //bool selected = driver.FindElement(By.CssSelector("input[type=checkbox]:checked")).Selected; //Console.WriteLine(selected); //Console.WriteLine(selected); /*if (selected==true) * { * * Console.WriteLine("Checkbox is selected"); * * } * else if (selected==false) * { * Console.WriteLine("Checkbox is not selected"); * var checkbox = fluentwait.Until(x => x.FindElement(By.XPath * (".//*[starts-with(@id,'Rem')]"))); * checkbox.Click(); * Console.WriteLine("Checkbox is now selected"); * * } * * bool submitbtn = driver.FindElement(By.CssSelector("input[type=submit]")).Displayed; * if (submitbtn == true) * { * Console.WriteLine("Btn is displayed"); * } * else * { * Console.WriteLine("Btn not displayed"); * }*/ try { string choice = "China"; var element = fluentwait.Until(x => x.FindElement(By.Id("countriesSingle"))) .FindElements(By.TagName("option")); for (var i = 0; i < element.Count; i++) { element[i].Click(); Console.WriteLine(element[i].Text); if (element[i].Text == choice) { break; } } SelectElement Multiple = new SelectElement(driver.FindElement(By.Id("countriesMultiple"))); foreach (var option in Multiple.Options) { option.Click(); Console.WriteLine(option.Text); Thread.Sleep(1000); if (option.Text == "England") { break; } } } catch (Exception e) { Console.WriteLine(e.Message); throw; } finally { if (driver != null) { driver.Quit(); } } Thread.Sleep(3000); driver.Quit(); }
public void fillandresetform() { fluentWait = new DefaultWait <IWebDriver>(driver); fluentWait.Timeout = TimeSpan.FromMinutes(1); fluentWait.PollingInterval = TimeSpan.FromSeconds(1); fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException)); IWebElement BP = fluentWait.Until(x => x.FindElement(By.XPath("//a[@title= 'Maintain Business Partners']"))); BP.Click(); Thread.Sleep(5000); IWebElement Cnclbtn = driver.FindElement(By.XPath("//*[@title='Cancel']")); Cnclbtn.Click(); IWebElement BP1 = driver.FindElement(By.XPath("//*[@title= 'Maintain Business Partners']")); BP1.Click(); Thread.Sleep(5000); IWebElement skey = driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/table[1]/tbody[1]/tr[1]/td[2]/div[1]/div[1]/input[1]")); skey.SendKeys("Placeholder text"); //Enter Name //Thread.Sleep(5000); IWebElement name = driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/table[1]/tbody[1]/tr[2]/td[2]/div[1]/div[1]/input[1]")); name.SendKeys("sagar"); //Enter Name 2 IWebElement name2 = driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/table[1]/tbody[1]/tr[3]/td[2]/div[1]/div[1]/input[1]")); name2.SendKeys("vande"); //Enter Description IWebElement desc = driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/table[1]/tbody[1]/tr[4]/td[2]/div[1]/div[1]/input[1]")); desc.SendKeys("A/P:Bhilwadi"); Thread.Sleep(2000); IWebElement rstbtn = driver.FindElement(By.XPath("//*[@title= 'Reset']")); rstbtn.Click(); //verify each text field is empty string skeytxt = skey.GetAttribute("value"); string nametext = name.GetAttribute("value"); string name2text = name2.GetAttribute("value"); string desctext = desc.GetAttribute("value"); if ((skeytxt.Equals("") && name2text.Equals("")) && (nametext.Equals("") && desctext.Equals(""))) { Console.WriteLine("All values are resetted"); } else { Console.WriteLine("Values are not resetted"); } IWebElement skey1 = driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/table[1]/tbody[1]/tr[1]/td[2]/div[1]/div[1]/input[1]")); skey1.SendKeys("Placeholder text"); //Enter Name IWebElement name1 = driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/table[1]/tbody[1]/tr[2]/td[2]/div[1]/div[1]/input[1]")); name1.SendKeys("sagar"); //Enter Name 2 IWebElement name3 = driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/table[1]/tbody[1]/tr[3]/td[2]/div[1]/div[1]/input[1]")); name3.SendKeys("vande"); //Enter Description IWebElement desc1 = driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/table[1]/tbody[1]/tr[4]/td[2]/div[1]/div[1]/input[1]")); desc1.SendKeys("A/P:Bhilwadi"); IWebElement okbtn = driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/div[1]/div[4]/div[1]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[3]/div[1]/button[1]/img[1]")); okbtn.Click(); }
public Element(string tagName) { _wait = new DefaultWait <IWebDriver>(BrowserSession.Current); _locator = new Locator(tagName); _timeout = BasinEnv.Browser.ElementTimeout; }
public void Update_Contact() { try { DefaultWait <IWebDriver> waitUpdate = new DefaultWait <IWebDriver>(driver); waitUpdate.Timeout = TimeSpan.FromSeconds(60); waitUpdate.PollingInterval = TimeSpan.FromSeconds(10); waitUpdate.IgnoreExceptionTypes(typeof(NoSuchElementException)); waitUpdate.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); waitUpdate.IgnoreExceptionTypes(typeof(InvalidElementStateException)); waitUpdate.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(NewContact)); waitUpdate.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.VisibilityOfAllElementsLocatedBy(NewContact)); // Update Operation Console.WriteLine("Update operation started"); driver.SwitchTo().Frame(driver.FindElement(contentIFrame0)); IList <string> contactDetails = objConfig.readSysConfigFile("SilverBearCRM", "Contact", "SysConfig.xml"); string updateRecord = contactDetails.ElementAt(0).ToString() + " " + contactDetails.ElementAt(1).ToString(); Console.WriteLine("Update Record " + updateRecord); ele_SearchForRecord = driver.FindElement(SearchForRecord); ele_SearchForRecord.SendKeys(updateRecord); ele_SearchForRecord.SendKeys(OpenQA.Selenium.Keys.Enter); Thread.Sleep(2000); // Wait until search table is loaded in search grid iWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(SearchGrid)); ele_SearchTable = driver.FindElement(SearchGrid); recordSize = ele_SearchTable.FindElements(By.TagName("tr")).Count; if (recordSize < 1) { Console.WriteLine("No Record present for entered search criteria"); log.Info("No Record present for entered search criteria"); Assert.AreEqual(true, false); } else { ele_firstRecord = ele_SearchTable.FindElements(By.TagName("tr")).ElementAt(0); // Get the first record from search table string contactRefNo = ele_firstRecord.FindElement(By.CssSelector("td:nth-child(12) span")).Text.ToString(); // changed the td:nth-child(2) to td:nth-child(12) as contact reference column is posited at 12th Console.WriteLine("Contact Ref No. is" + contactRefNo); Assert.That(contactDetails.ElementAt(48).ToString(), Is.EqualTo(contactRefNo.Trim().ToString()).IgnoreCase); // Verify the contact ref no. is correct for search record in grid // Click on searched record for update ele_firstRecord.FindElement(By.CssSelector("td:nth-child(2) a")).Click(); //changed td:nth-child(3) a to td:nth-child(2) a Helper.AlertHandling(driver, "alert", null, null); iWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.InvisibilityOfElementLocated(Loading)); iWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(NewContactHeader)); } } catch (Exception e) { log.Error(e.Message + "\n" + e.StackTrace + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Console.WriteLine(e.Message + "\n" + e.StackTrace + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Assert.AreEqual(true, false); } }
public static void Run(IWebDriver driver, DefaultWait <IWebDriver> wait) { try { ReadOnlyCollection <IWebElement> stockData = wait.Until(element => element.FindElements( By.CssSelector("#data-util-col > section:nth-child(1) > table > tbody > tr > td"))); var stockList = new List <string>(); var singleStock = new List <string>(); const int totalDataPointsPerStock = 4; var timeStamp = getCurrentTimeStamp(); foreach (var stockDataCell in stockData) { singleStock.Add(stockDataCell.Text.Trim()); if (singleStock.Count() != totalDataPointsPerStock) { continue; } var companyNameAndSymbol = singleStock[0].Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); Console.WriteLine("timeStamp: {0}", timeStamp); var symbol = companyNameAndSymbol[0]; Console.WriteLine("symbol: {0}", symbol); var companyName = companyNameAndSymbol[1]; Console.WriteLine("companyName: {0}", companyName); var lastPrice = singleStock[1]; Console.WriteLine("lastPrice: {0}", lastPrice); var change = singleStock[2]; Console.WriteLine("change: {0}", change); var percentChange = singleStock[3]; Console.WriteLine("percentChange: {0}", percentChange); Console.WriteLine("===================="); Store.Data(timeStamp, symbol, companyName, lastPrice, change, percentChange); stockList.AddRange(singleStock); singleStock = new List <string>(); } driver.Quit(); } catch (Exception e) { Console.WriteLine("Could not collect data!"); Console.WriteLine(e.ToString()); driver.Quit(); } }
public void VerifyWebKey() { int searchTryCnt = 0; Boolean cntFound = false; driver.SwitchTo().DefaultContent(); iWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(SalesDropDown)); IWebElement ele_salesDropDown = driver.FindElement(SalesDropDown); // Wait until content is loading on SilverBear CRM //iWait.Until(ExpectedConditions.InvisibilityOfElementLocated(Loading)); //changed by diksha 18/05/2020 // Get the 'Marketing Dropdown' object and click ele_salesDropDown.Click(); // Click on 'Contact' on Dropdown panel ele_Contact = driver.FindElement(Contacts); ele_Contact.Click(); // Wait until content is loading on SilverBear CRM //iWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.InvisibilityOfElementLocated(Loading)); DefaultWait <IWebDriver> waitUpdate = new DefaultWait <IWebDriver>(driver); waitUpdate.Timeout = TimeSpan.FromSeconds(60); waitUpdate.PollingInterval = TimeSpan.FromSeconds(10); waitUpdate.IgnoreExceptionTypes(typeof(NoSuchElementException)); waitUpdate.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); waitUpdate.IgnoreExceptionTypes(typeof(InvalidElementStateException)); Thread.Sleep(2000); waitUpdate.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(NewContact)); // // waitUpdate.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.CssSelector(OR.readingXMLFile("Contact", "NewContact", "SilverBearCRM_OR.xml")))); // Search and Verify operation driver.SwitchTo().Frame(driver.FindElement(contentIFrame0)); Thread.Sleep(2000); IList <string> contactDetails = cf.readSysConfigFile("SilverBearCRM", "Contact", "SysConfig.xml"); string contRefName = contactDetails.ElementAt(48).ToString(); Thread.Sleep(3000); Console.WriteLine("Data Verification for Contact Module Started on PeopleSoft"); Console.WriteLine("Contact Ref. No. is:" + contRefName); while (searchTryCnt < 10) { ele_SearchForRecord = driver.FindElement(SearchForRecord); //ele_SearchForRecord.Clear(); ele_SearchForRecord.SendKeys(contRefName); ele_SearchForRecord.SendKeys(OpenQA.Selenium.Keys.Enter); Thread.Sleep(2000); // Wait until search table is loaded in search grid iWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(SearchGrid)); ele_SearchTable = driver.FindElement(SearchGrid); recordSize = ele_SearchTable.FindElements(By.TagName("tr")).Count; if (recordSize == 1) { cntFound = true; break; } searchTryCnt++; Thread.Sleep(4000); } if (cntFound) { Console.WriteLine("Searched Record is found in SilverBear CRM"); ele_firstRecord = ele_SearchTable.FindElements(By.TagName("tr")).ElementAt(0); // Get the first record from search table ele_firstRecord.FindElement(By.CssSelector("td:nth-child(2)")).Click(); Thread.Sleep(7000); //iWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.InvisibilityOfElementLocated(Loading)); iWait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(NewContactHeader)); driver.SwitchTo().DefaultContent(); driver.SwitchTo().Frame(driver.FindElement(contentIFrame1)); //ele_IetWebKey = driver.FindElement(By.CssSelector("div#sbiet_ietwebkey>div>span")); ele_IetWebKey = driver.FindElement(By.Id("IET Web Key_label")); //changed by diksha 26/03/2020 bool contactRefCheck = true; string contactIETWebKey = null; Helper.ScrollToViewElement(ele_IetWebKey, driver); contactIETWebKey = ele_IetWebKey.Text.ToString(); contactRefCheck = Regex.IsMatch(contactIETWebKey, "[0-9]"); StringAssert.IsMatch("[0-9]", contactIETWebKey); } else { Console.WriteLine("Searched contact not found in SilverBear CRM"); log.Info("Searched contact not found in Darwin CRM"); Assert.AreEqual(true, false); } }
public int GanTuDong(string CustomerCode, string SenderPhone, string trungtam, string buucuc) { int kq = 0; Thread.Sleep(5000); m_themtudong.Click(); // PropretiesCollection.driver.SwitchTo().ActiveElement().FindElement(By.XPath("/html/body/div[4]/div[1]/div[2]/div/div/div[2]/div/button")).Click(); Thread.Sleep(10000); DefaultWait <IWebDriver> flusername = new DefaultWait <IWebDriver>(PropretiesCollection.driver); flusername.Timeout = TimeSpan.FromSeconds(10); flusername.PollingInterval = TimeSpan.FromMilliseconds(250); flusername.IgnoreExceptionTypes(typeof(NoSuchElementException)); IWebElement searchusername = flusername.Until(x => x.FindElement(By.Id("CustomerCode"))); if (searchusername != null) { m_txtCustomerCode.Clear(); m_txtCustomerCode.SendKeys(CustomerCode); Thread.Sleep(1000); m_txtSenderPhone.Clear(); m_txtSenderPhone.SendKeys(SenderPhone); Thread.Sleep(3000); try { m_cmbtrungtam.Click(); } catch { } try { m_cmbtrungtam1.Click(); } catch { } Thread.Sleep(1000); SeleniumSetMeThor.SelectDropDownVaules(cmbtrungtam, trungtam); Thread.Sleep(1000); try { m_cmbtrungtam.Click(); } catch { } try { m_cmbtrungtam1.Click(); } catch { } Thread.Sleep(1000); try { m_cmbbuucuc.Click(); } catch { } try { m_cmbbuucuc1.Click(); } catch { } Thread.Sleep(2000); SeleniumSetMeThor.SelectDropDownVaules(cmbbuucuc, buucuc); Thread.Sleep(1000); try { m_cmbbuucuc.Click(); } catch { } try { m_cmbbuucuc1.Click(); } catch { } Thread.Sleep(1000); try { btnthemtuyen.Click(); } catch { } try { btnthemtuyen1.Click(); } catch { } Thread.Sleep(1000); switch (kq) { case 0: System.Threading.Thread.Sleep(3000); goto case 1; break; case 1: try { string thongbao = SeleniumGetMeThor.GetText2(txtketqua); if (thongbao == "Cập nhật dữ liệu thành công") { kq = 1; } else if (thongbao.IndexOf("đã được thiết lập") != -1) { kq = 1; try { PropretiesCollection.driver.SwitchTo().ActiveElement().FindElement(By.XPath("/html/body/div[4]/div[7]/div/div/div/div[3]/button")).Click(); } catch { } Thread.Sleep(1000); try { PropretiesCollection.driver.SwitchTo().ActiveElement().FindElement(By.XPath("/html/body/div[4]/div[1]/div[2]/div/div/div[4]/div/div/div/div[3]/button[2]")).Click(); } catch { } Thread.Sleep(1000); try { PropretiesCollection.driver.SwitchTo().ActiveElement().FindElement(By.XPath("/html/body/div[4]/div[1]/div[2]/div/div/div[3]/div[2]/div/div/div/div[3]/button[2]")).Click(); } catch { } } else { goto case 0; } } catch { goto case 0; } break; } Thread.Sleep(4000); try { PropretiesCollection.driver.SwitchTo().ActiveElement().FindElement(By.XPath("/html/body/div[4]/div[7]/div/div/div/div[3]/button")).Click(); } catch { } } return(kq); }
/// <summary> /// Waits for the element to meet a certain condition. /// </summary> /// <param name="element">The element.</param> /// <param name="waitCondition">The wait condition.</param> /// <param name="timeout">The timeout to wait before failing.</param> /// <returns><c>true</c> if the condition is met, <c>false</c> otherwise.</returns> public override bool WaitForElement(IWebElement element, WaitConditions waitCondition, TimeSpan?timeout) { var waiter = new DefaultWait <IWebElement>(element); waiter.Timeout = timeout.GetValueOrDefault(waiter.Timeout); try { switch (waitCondition) { case WaitConditions.BecomesNonExistent: // AKA NotExists this.ExecuteWithElementLocateTimeout( new TimeSpan(), () => { try { waiter.Until(e => !e.Displayed); } catch (NoSuchElementException) { } catch (NotFoundException) { } catch (ElementNotVisibleException) { } catch (StaleElementReferenceException) { } }); break; case WaitConditions.RemainsNonExistent: return(this.EvaluateWithElementLocateTimeout( waiter.Timeout, () => { try { return this.DoesFullTimeoutElapse(waiter, e => e.Displayed); } catch (NoSuchElementException) { return true; } catch (NotFoundException) { return true; } catch (ElementNotVisibleException) { return true; } catch (StaleElementReferenceException) { return true; } })); case WaitConditions.BecomesEnabled: // AKA Enabled waiter.IgnoreExceptionTypes(typeof(ElementNotVisibleException), typeof(NotFoundException)); waiter.Until(e => e.Enabled); break; case WaitConditions.BecomesDisabled: // AKA NotEnabled waiter.IgnoreExceptionTypes(typeof(ElementNotVisibleException), typeof(NotFoundException)); waiter.Until(e => !e.Enabled); break; case WaitConditions.BecomesExistent: // AKA Exists waiter.IgnoreExceptionTypes(typeof(ElementNotVisibleException), typeof(NotFoundException)); waiter.Until(e => e.Displayed); break; case WaitConditions.NotMoving: waiter.IgnoreExceptionTypes(typeof(ElementNotVisibleException), typeof(NotFoundException)); waiter.Until(e => e.Displayed); waiter.Until(e => !this.Moving(e)); break; case WaitConditions.RemainsEnabled: return(this.DoesFullTimeoutElapse(waiter, e => !e.Enabled)); case WaitConditions.RemainsDisabled: return(this.DoesFullTimeoutElapse(waiter, e => e.Enabled)); case WaitConditions.RemainsExistent: return(this.DoesFullTimeoutElapse(waiter, e => !e.Displayed)); } } catch (WebDriverTimeoutException) { return(false); } return(true); }
public void TestDynamicWait() { DefaultWait <IWebElement> iWait = new DefaultWait <IWebElement>(ObjectRepository.driver.FindElement(By.Id(""))); }
public void AddNewItemWithNewCategory() { var capabilities = new AppiumOptions(); capabilities.AddAdditionalCapability(MobileCapabilityType.App, "8b831c56-bc54-4a8b-af94-a448f80118e7_sezxftbtgh66j!App"); capabilities.AddAdditionalCapability(MobileCapabilityType.PlatformName, "Windows"); capabilities.AddAdditionalCapability(MobileCapabilityType.DeviceName, "WindowsPC"); var _appiumLocalService = new AppiumServiceBuilder().UsingAnyFreePort().Build(); _appiumLocalService.Start(); var driver = new WindowsDriver <WindowsElement>(_appiumLocalService, capabilities); // Create new Category item first var categoryButton = driver.FindElement(MobileBy.AccessibilityId("AddCategory")); categoryButton.Click(); // fill out the form for a new category var categoryName = driver.FindElement(MobileBy.AccessibilityId("categoryName")); categoryName.Clear(); categoryName.SendKeys("New category from automation"); //save category var saveCategory = driver.FindElement(MobileBy.AccessibilityId("Save")); saveCategory.Click(); var el1 = driver.FindElementByAccessibilityId("Add"); el1.Click(); var elItemText = driver.FindElementByAccessibilityId("ItemText"); elItemText.Clear(); elItemText.SendKeys("This is a new Item"); var elItemDetail = driver.FindElementByAccessibilityId("ItemDescription"); elItemDetail.Clear(); elItemDetail.SendKeys("These are the details"); var elItemCategory = driver.FindElement(MobileBy.AccessibilityId("ItemCategory")); elItemCategory.Click(); var categoryListItem = elItemCategory.FindElement(By.Name("New category from automation")); categoryListItem.Click(); var elSave = driver.FindElementByAccessibilityId("Save"); elSave.Click(); elSave.ClearCache(); //wait for progress bar to disapear var wait = new DefaultWait <WindowsDriver <WindowsElement> >(driver) { Timeout = TimeSpan.FromSeconds(60), PollingInterval = TimeSpan.FromMilliseconds(500) }; wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); wait.Until(d => d.FindElementByName("Second item")); var listview = driver.FindElementByAccessibilityId("ItemsListView"); //now use wait to scroll untill we find item wait = new DefaultWait <WindowsDriver <WindowsElement> >(driver) { Timeout = TimeSpan.FromSeconds(60), PollingInterval = TimeSpan.FromMilliseconds(500) }; wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); var elementfound = wait.Until(d => { var input = new PointerInputDevice(PointerKind.Touch); ActionSequence FlickUp = new ActionSequence(input); FlickUp.AddAction(input.CreatePointerMove(listview, 0, 0, TimeSpan.Zero)); FlickUp.AddAction(input.CreatePointerDown(MouseButton.Left)); FlickUp.AddAction(input.CreatePointerMove(listview, 0, -300, TimeSpan.FromMilliseconds(200))); FlickUp.AddAction(input.CreatePointerUp(MouseButton.Left)); driver.PerformActions(new List <ActionSequence>() { FlickUp }); return(d.FindElementByName("This is a new Item")); }); Assert.IsTrue(elementfound != null); driver.CloseApp(); }
public Element(By by) { FoundBy = by; _wait = new DefaultWait <IWebDriver>(BrowserSession.Current); _timeout = BasinEnv.Browser.ElementTimeout; }