public void Submitting_Form_Redirects_To_Homepage() { //get driver Driver = GetChromeDriver(); //create an instance of a sampleApplicationPage var sampleApplicationPage = new SampleApplicationPage(Driver); //go to sample application page sampleApplicationPage.GoTo(); //assert it's a right page Assert.IsTrue(sampleApplicationPage.IsVisible); //fill out and submit form sampleApplicationPage.FillOutAndSumbitForm("Ira"); //create instance of a Home Page var ultimateQAHomePage = new UltimateQAHomePage(Driver); //wait and assert the redirection var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); wait.Until(ExpectedConditions.TitleContains(ultimateQAHomePage.getTitle())); Assert.AreEqual(Driver.Title, ultimateQAHomePage.getTitle()); //clean up Driver.Close(); Driver.Quit(); }
protected void WaitForTitle(string title, double timeoutSeconds) { var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeoutSeconds)); wait.Message = "Expected page title to contain '" + title + "', Actual page title: '" + Driver.Title + "'"; wait.Until(ExpectedConditions.TitleContains(title)); }
public static void SwitchTo(string windowTitle, bool partialMatch = false) { RetriableRunner.Run(() => { var handles = Web.PortalDriver.WindowHandles; try { var handle = partialMatch ? handles.First(h => Web.PortalDriver.SwitchTo().Window(h).Title.Contains(windowTitle)) : handles.First(h => Web.PortalDriver.SwitchTo().Window(h).Title == windowTitle); Web.PortalDriver.SwitchTo().Window(handle); } catch (Exception) { var windowTitles = handles.Select(h => Web.PortalDriver.SwitchTo().Window(h).Title); var titleList = String.Join(",", windowTitles); Trace.WriteLine("unable to find '" + windowTitle + "'"); Trace.WriteLine("available windows: [" + titleList + "]"); throw; } var wait = new WebDriverWait(Web.PortalDriver, TimeSpan.FromSeconds(10)); try { wait.Until(ExpectedConditions.TitleContains(windowTitle)); } catch (Exception ex) { ExceptionHandler.HandleException(ex, false); } }); }
/// <summary> /// Amazonから商品と価格を調べる /// </summary> /// <param name="pSearchValue"></param> public void Execute(string pSearchValue) { try { // ドライバが存在する場合は終了させる DriverKill(); // デフォルトサービス設定(ドライバを指定するexeは"MicrosoftWebDriver.exe"固定みたい) var eService = EdgeDriverService.CreateDefaultService(AppDir, "MicrosoftWebDriver.exe"); // コマンドプロンプト非表示 eService.HideCommandPromptWindow = true; // オプション設定 var eOptions = new EdgeOptions { PageLoadStrategy = (PageLoadStrategy)EdgePageLoadStrategy.Normal }; // ドライバ生成 WebDriver = new EdgeDriver(eService, eOptions); // URLセット WebDriver.Url = TargetURL; // 表示されるまで待つ WebDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(4); // ページタイトルに検索結果が含まれるまで ExecuteScript <IWebDriver>(WebDriver, $"document.getElementsByName('field-keywords')[0].value = \"{pSearchValue}\""); // 検索ボタンをクリック var eWebElement = WebDriver.FindElement(By.ClassName("nav-input")); eWebElement.Submit(); // 検索結果のページが読み込み完了するまで待機する var eDriverWait = new WebDriverWait(WebDriver, TimeSpan.FromSeconds(20)); eDriverWait.Until(ExpectedConditions.TitleContains(pSearchValue)); // 商品ごとのXPath var eByPath = By.XPath("//span[contains(@class, 'a-size-base-plus a-color-base a-text-normal')]"); // 商品一覧 var eProducts = WebDriver.FindElements(eByPath); foreach (var eProduct in eProducts) { // 商品から4つ上がって価格を調べる IWebElement parent = eProduct.FindElement(By.XPath("../../../..")); // 価格の要素を取得する var ePrice = parent.FindElement(By.ClassName("a-price-whole")); // コンソール出力 Console.WriteLine($"商品名:{eProduct.Text} 価格:{ePrice.Text}"); } } catch (Exception eException) { // コンソール出力 Console.WriteLine(eException.Message); // デバッグログ出力 Debug.WriteLine(eException.Message); } finally { // ドライバの終了 WebDriver.Quit(); } }
public void TitleContainsSearchWord() { driver.Url = "https://yandex.ru/"; driver.FindElement(By.Name("text")).SendKeys("webdriver"); driver.FindElement(By.Name("text")).SendKeys(Keys.Enter); wait.Until(ExpectedConditions.TitleContains("webdriver — Яндекс: нашлось")); }
public void GoToSentMailSection() { SentMailSectionLink.Click(); CustomWait. Until(ExpectedConditions.TitleContains("Sent Mail")); }
/// <summary> /// Wait for page title conatins given text for given timeout seconds /// </summary> /// <param name="titleText"></param> /// <param name="timeOutSeconds"></param> public static void WaitForPageTitleContains(string titleText, TimeSpan timeOutSecs) { try { WebDriverWait wait = new WebDriverWait(DriverInstance.Instance, timeOutSecs); wait.Until(ExpectedConditions.TitleContains(titleText)); LoggerInstance.log.Info("Driver explicitly waits " + explicitTimeOutPeriod + " seconds for page title text contains " + "\"" + titleText + "\"."); } catch (NoSuchElementException elementNotPresent) { LoggerInstance.log.Error(elementNotPresent.Message, elementNotPresent); } catch (WebDriverTimeoutException webdriverTimeOut) { LoggerInstance.log.Error(webdriverTimeOut.Message, webdriverTimeOut); } catch (TimeoutException timeOutEx) { LoggerInstance.log.Error(timeOutEx.Message, timeOutEx); } catch (Exception e) { LoggerInstance.log.Error(e.Message, e); } }
public Product ClickOnProduct(IWebDriver driver, WebDriverWait wait, string category, int order) { IWebElement productOnMainPage = null; Product product = new Product(); category = category.ToLower().Replace(" ", "-"); productOnMainPage = driver.FindElement(By.XPath(".//*[@id='box-" + category + "']//li[" + order + "]/a[1]")); //product.price1 = productOnMainPage.FindElement(By.ClassName("regular-price")).GetAttribute("textContent"); if (productOnMainPage.FindElements(By.ClassName("campaign-price")).Count > 0) { product.price2 = productOnMainPage.FindElement(By.ClassName("campaign-price")).GetAttribute("textContent"); } else { product.price2 = productOnMainPage.FindElement(By.ClassName("price")).GetAttribute("textContent"); } /*product.className1 = productOnMainPage.FindElement(By.ClassName("regular-price")).GetAttribute("className"); * product.className2 = productOnMainPage.FindElement(By.ClassName("campaign-price")).GetAttribute("className"); * product.title = productOnMainPage.GetAttribute("title"); * product.fontStyle1 = productOnMainPage.FindElement(By.ClassName("regular-price")).GetCssValue("font-weight"); * product.fontStyle2 = productOnMainPage.FindElement(By.ClassName("campaign-price")).GetCssValue("font-weight"); * product.fontDecoration1 = productOnMainPage.FindElement(By.ClassName("regular-price")).GetCssValue("text-decoration"); * product.fontDecoration2 = productOnMainPage.FindElement(By.ClassName("campaign-price")).GetCssValue("text-decoration");*/ productOnMainPage.Click(); wait.Until(ExpectedConditions.TitleContains(product.title)); return(product); }
public void Can_create_webdriver_then_connect_to_Google_and_read_the_window_title() { // Arrange var driverFactory = GetWebDriverFactory.FromConfiguration(); string result; // Act using (var webDriver = driverFactory.CreateWebDriver(scenarioName: ConnectToGoogleScenarioName)) { webDriver.Navigate().GoToUrl(GoogleHomeUrl); var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(TimeoutSecondsToConnectToGoogleHomePage)) .Until(ExpectedConditions.TitleContains(Google)); result = webDriver.Title; // Assert var statusDriver = webDriver as ICanReceiveScenarioOutcome; try { Assert.That(result, Contains.Substring(Google)); } catch (AssertionException) { if (statusDriver != null) { statusDriver.MarkScenarioAsFailure(); } throw; } if (statusDriver != null) { statusDriver.MarkScenarioAsSuccess(); } } }
public void OpeningTheFirstResultByClickingeLink() { try { string valueToSearch = "iPhone 11"; //Enter the search value in the search bar amazon.searchBar.SendKeys(valueToSearch); //Click search icon in the search bar amazon.searchBarSubmitButton.Click(); //wait for the page to load with the result wait.Until(ExpectedConditions.TitleContains(valueToSearch)); //Click the Title of the first item in the search's outcome IWebElement firstResultTitleLink = driver.FindElement(By.XPath($"//span[contains(text(),'{valueToSearch}')]/parent::a")); //I had to use this here instead of PageObject because of the value to search is dynamic firstResultTitleLink.Click(); //wait 30 seconds before closing the browser wait.Until(ExpectedConditions.ElementToBeClickable(amazon.productDetailMainSection)); Thread.Sleep(3000); } catch (Exception e) { e.Message.ToString(); } }
public void SignIn(string Name) { txt_userName.SendKeys(ConfigurationManager.AppSettings["userID"]); txt_password.SendKeys(ConfigurationManager.AppSettings["password"]); btn_signIn.Click(); wait.Until(ExpectedConditions.TitleContains(Name)); }
public static void HandleCertificateError() { if (TestBasics.Browser.ToUpper() == "IE") { try { TestBasics.Wait.Until(ExpectedConditions.TitleContains("Certificate")); } catch { } int click = 100; while (TestBasics.driver.Title.Contains("Certificate")) { CustomWait.WaitForPageLoad(30); try { TestBasics.driver.Navigate().GoToUrl("javascript:document.getElementById('overridelink').click()"); } catch { } Thread.Sleep(1000); click--; if (click < 0) { break; } } } }
public void SearchGoogle() { _driver.Navigate().GoToUrl("https://www.google.com"); _driver.FindElement(By.Name("q")).SendKeys("Егор лучший?!"); _driver.FindElement(By.Name("btnK")).Click(); _wait.Until(ExpectedConditions.TitleContains("Егор лучший?! - Поиск в Google")); }
private void ClickElement(IWebElement element, string checkTitle) { Initializer.Driver.Scripts().ExecuteScript("arguments[0].click();", element); WebDriverWait wait = new WebDriverWait(Initializer.Driver, TimeSpan.FromSeconds(10)); wait.Until(ExpectedConditions.TitleContains(checkTitle)); }
public void Method() { wait.Until(ExpectedConditions.TitleIs("webdriver - Поиск в Google")); wait.Until(ExpectedConditions.TitleContains("webdriver - Поиск в")); wait.Until(ExpectedConditions.UrlContains("login.php")); wait.Until(ExpectedConditions.UrlToBe("http://pagination.js.org/")); var regex = @"\d"; wait.Until(ExpectedConditions.UrlMatches(regex)); wait.Until(ExpectedConditions.AlertIsPresent()); //В С# я не нашел wait.Until(ExpectedConditions.NumberOfWindowsToBe()); //нужно проверять то, что у элемента есть какой-то класс, вместо того, чтобы проверять стиль элемента. //как правило, разработчики не меняют стили напрямую, они присваивают классы. wait.Until(x => x.FindElement(By.CssSelector("locator")).GetAttribute("class").Contains("error")); wait.Until(ExpectedConditions.TextToBePresentInElement(element, "text")); wait.Until(ExpectedConditions.ElementToBeSelected(element, false)); wait.Until(ExpectedConditions.ElementToBeClickable(element)); //ElementToBeClickable - не соответствует своему названию. Сдесь проверяется то, что //елемент 1.Видимый, 2.Не disabled. И конечно, здесь нет никаких проверок, что эта кнопка НЕ ЗАКРЫТА никаким другим //элементом а если она прозрачная, то она будет считаться невидимой. Так, что название этого метода просто напросто врет. //По-настоящему ИНТЕРАКТИВНОСТЬ ОНО НЕ ПРОВЕРЯЕТ. //условие количества элементов с локатором var elements = driver.FindElements(By.CssSelector("locator")); wait.Until(x => elements.Count == 10); //но здесь мы возвращаем коллекцию элементов. var returnedElements = wait.Until(x => { var elements2 = x.FindElements(By.CssSelector("locaotr")); return(elements2.Count == 10 ? elements2 : null); }); //хз что это... var wait2 = new DefaultWait <IWebElement>(element); }
protected override void PageValidationCheck() { if (!_wait.Until(ExpectedConditions.TitleContains(InboxTitle[0])) && !_wait.Until(ExpectedConditions.TitleContains(InboxTitle[1]))) { throw new NoValidPageException("This no inbox page"); } }
public RepeatingInvoicesPage Save() { _saveButton.Click(); WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); wait.Until(ExpectedConditions.TitleContains("Invoices")); return(PageFactory.InitElements <RepeatingInvoicesPage>(Driver)); }
public string SelectProductCategory() { ProductCategoryMenu.Click(); WebDriverWait wait = new WebDriverWait(driver, controlTimeOut); wait.Until(ExpectedConditions.TitleContains("Product Category")); return(driver.Title); }
public void verifyPageTitle(String expectedTitle) { WebDriverWait wd = new WebDriverWait(driver, new TimeSpan(0, 0, 15)); wd.Until(ExpectedConditions.TitleContains(expectedTitle)); actualTitle = driver.Title; Assert.AreEqual(expectedTitle, actualTitle); }
protected override void PageValidationCheck() { if (!_wait.Until(ExpectedConditions.TitleContains(_letterTitle))) { throw new NoValidPageException("This no inbox page"); } _replyButton = driver.GetIWebElementBy(_replyButtonLocator); }
protected override void PageValidationCheck() { if (!_wait.Until(ExpectedConditions.TitleContains(_loginTitle))) { throw new NoValidPageException("This no inbox page"); } _usernameInput = driver.GetIWebElementBy(_usernameInputLocator); _passwordInput = driver.GetIWebElementBy(_passwordInputLocator); }
public void FirstTest() { driver.Url = "http://www.google.com/"; wait.Until(ExpectedConditions.TitleContains("Google")); driver.FindElement(By.Name("q")).SendKeys("webdriver"); wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("div.logocont a > img"))); driver.FindElement(By.CssSelector("button.sbico-c")).Click(); wait.Until(ExpectedConditions.TitleIs("webdriver - Поиск в Google")); }
public void SwitchToPageByUrl(string PageURL, string title) { Driver.Navigate().GoToUrl(PageURL); new WebDriverWait(Driver, TimeSpan.FromSeconds(10)) .Until(ExpectedConditions.TitleContains(title)); Console.WriteLine("Switching to page url: '" + PageURL + "' correctly."); }
public void SwitchToMainPageByUrl(string pageTitle) { SwitchToPageByUrl("https://en.wikipedia.org/wiki/Main_Page", pageTitle); new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) .Until(ExpectedConditions.TitleContains(pageTitle)); Console.WriteLine("Switching to MainPage correctly."); }
public void LoginTest() { driver.Url = "http://localhost/litecart/admin/login.php"; wait.Until(ExpectedConditions.TitleContains("My Store")); wait.Until(ExpectedConditions.ElementIsVisible(By.Name("username"))).SendKeys("admin"); wait.Until(ExpectedConditions.ElementIsVisible(By.Name("password"))).SendKeys("admin"); wait.Until(ExpectedConditions.ElementIsVisible(By.Name("login"))).Click(); wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("[title=\"Logout\"]"))); }
public void Loginsteps() { //Maximize the window driver.Manage().Window.Maximize(); //Navigate to Turn up login page URL driver.Navigate().GoToUrl("http://horse-dev.azurewebsites.net"); wait.Until(ExpectedConditions.TitleContains("Log In - Dispatching System")); //Get current url and store it in a variable String CurrentUrl = driver.Url; //Validate if user had navigated to Turnup login page successfully /* if (CurrentUrl == "http://horse-dev.azurewebsites.net/Account/Login?ReturnUrl=%2f") * { * Console.WriteLine("Passed - Browser navigated to Turnup login page "); * } * else * { * Console.WriteLine("Failed - Browser navigated to wrong url"); * }*/ Assert.That(CurrentUrl, Is.EqualTo("http://horse-dev.azurewebsites.net/Account/Login?ReturnUrl=%2f")); //Enter username IWebElement Username = driver.FindElement(By.Id("UserName")); Username.SendKeys("Hari"); //Enter password IWebElement Password = driver.FindElement(By.Id("Password")); Password.SendKeys("123123"); //Click on login button IWebElement Login = driver.FindElement(By.XPath("//*[@id='loginForm']/form/div[3]/input[1]")); Login.Click(); //Validate if user had logged in successfully IWebElement Hellohari = driver.FindElement(By.XPath("//*[@id='logoutForm']/ul/li/a")); /*if (Hellohari.Text == "Hello hari!") * { * Console.WriteLine("Passed - user login successfully "); * } * else * { * Console.WriteLine("Failed - unable to logged in "); * } */ Assert.That(Hellohari.Text, Is.EqualTo("Hello hari!")); }
public void CheckProductPage() { string regularPriceExpectedClassMain = "regular-price"; string campaignPriceExpectedClassMain = "campaign-price"; string regularPriceExpectedClassProduct = "regular-price"; string campaignPriceExpectedClassProduct = "campaign-price"; driver.Url = ("http://localhost/litecart/en/"); IWebElement webElement = driver.FindElement(By.CssSelector("div#box-campaigns li:nth-of-type(1) a.link")); ProductProperties propertiesMainPage = new ProductProperties(webElement); webElement.Click(); wait.Until(ExpectedConditions.TitleContains(propertiesMainPage.productName)); webElement = driver.FindElement(By.CssSelector("div#box-product")); ProductProperties propertiesProductPage = new ProductProperties(webElement); //Check styles if (propertiesMainPage.regularPriceeClass != regularPriceExpectedClassMain) { throw new System.Exception("Class of regular price on Main page isn't correct"); } if (propertiesMainPage.campaignPriceClass != campaignPriceExpectedClassMain) { throw new System.Exception("Class of campaign price on Main page isn't correct"); } if (propertiesProductPage.regularPriceeClass != regularPriceExpectedClassProduct) { throw new System.Exception("Class of regular price on Product page isn't correct"); } if (propertiesProductPage.campaignPriceClass != campaignPriceExpectedClassProduct) { throw new System.Exception("Class of campaign price on Product page isn't correct"); } //Check prices if (propertiesMainPage.regularPricee != propertiesProductPage.regularPricee) { throw new System.Exception("Regular prise on Product page is different from regular prise on Main page"); } if (propertiesMainPage.campaignPrice != propertiesProductPage.campaignPrice) { throw new System.Exception("Campaign prise on Product page is different from campaign prise on Main page"); } //Check Titles if (propertiesMainPage.productName != propertiesProductPage.productName) { throw new System.Exception("Title on Product page is different from title on Main page"); } }
public void CreateNewOrder(IWebDriver driver, WebDriverWait wait) { driver.FindElement(By.LinkText("Create New Order")).Click(); wait.Until(ExpectedConditions.TitleContains("Create New Order")); Assert.IsTrue(driver.Manage().Logs.GetLog("browser").Count == 0, "Log is not empty"); /*foreach (LogEntry l in driver.Manage().Logs.GetLog("browser")) * { * Console.WriteLine(l); * }*/ }
public CartPage ToCartPage() { var checkout = driver.FindElement(By.CssSelector("a[href*=checkout]")); checkout.Click(); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); wait.Until(ExpectedConditions.TitleContains("Checkout")); wait = new WebDriverWait(driver, TimeSpan.Zero); return(new CartPage(driver)); }
//declare methods //Select flight and click continue and assert for select book a flight page public void SelectFlight() { WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(60)); wait.Until(ExpectedConditions.ElementIsVisible(By.Name(ContinueBtn2.GetAttribute("Name")))); ContinueBtn2.Click(); wait.Until(ExpectedConditions.TitleContains("Book a Flight")); //Wait for next page load and assert for title of that page Assert.That(_driver.Title, Contains.Substring("Book a Flight")); }