public void TestCleanup() { if (Properties.Settings.Default.BROWSER == BrowserType.Ie) { driver.Quit(); driver = null; } try { if (MyBook.Name != "") { MyBook.Save(); MyBook.Close(); } if (MyApp.Name != "") { MyApp.Quit(); } }catch { } KillProcess("EXCEL"); KillProcess("IEDriverServer"); KillProcess("iexplore"); }
private void GetDriver() { _driver = (IWebDriver)Registry.hashTable["driver"]; //забираем из хештаблицы сохраненный ранее драйвер _driver.Navigate().GoToUrl(Paths.UrlCreatePk); //заходим по ссылке _driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); //ставим ожидание в 10 сек на случай, если страница медленно грузится и нужные эл-ты появятся не сразу }
public void BaseTestInitialize(IWebDriver initialDriver, string baseUri, int timeout) { this.Driver = initialDriver; this.BaseUri = baseUri; this.Timeout = timeout; this.Wait = new WebDriverWait(initialDriver, TimeSpan.FromSeconds(timeout)); }
public CreateCustomerPage(IWebDriver driver) : base(driver) { if (!driver.PageSource.Contains("Server Error") && driver.Title != "Nuovo cliente") { throw new ArgumentException("This is not the create customer page: " + driver.Title); } }
public void PasswordlessAuthentication() { string email = "admin@test"; _webDriver = new RemoteWebDriver(new Uri("http://localhost:9515"), DesiredCapabilities.Chrome()); _webDriver.Manage().Window.Maximize(); _webDriver.Navigate().GoToUrl("http://dev.icms/Account/Login"); //Enter email address on login page IWebElement emailLogin = _webDriver.FindElement(By.Id("Email")); emailLogin.Clear(); emailLogin.SendKeys(email); IWebElement authenticateButton = _webDriver.FindElement(By.Id("requestauth")); authenticateButton.Click(); //this should have sent me an email //Let's pretend we got the email and check the server for the authtoken and plug it into the URL string token = HttpUtility.UrlEncode(TestUtilities.AuthenticationUtil.GetAuthToken(email)); string goToUrl = string.Format("http://dev.icms/account/authorize/?authtoken={0}&email={1}&returnUrl=%2f", token, email); _webDriver.Quit(); _webDriver = new RemoteWebDriver(new Uri("http://localhost:9515"), DesiredCapabilities.Chrome()); _webDriver.Navigate().GoToUrl(goToUrl); //Check DOM to see if we are logged in IWebElement elem = _webDriver.FindElement(By.CssSelector("h1")); Assert.IsTrue(elem.Text == "Welcome Admin Development"); }
public void Logout(IWebDriver driverToUse = null) { if (driverToUse == null) driverToUse = driver; driverToUse.FindElement(By.Id("LoginStatus1")).Click(); }
/// <summary> /// Handles the command. /// </summary> /// <param name="driver">The driver used to execute the command.</param> /// <param name="locator">The first parameter to the command.</param> /// <param name="value">The second parameter to the command.</param> /// <returns>The result of the command.</returns> protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value) { UserLookupStrategy strategy = new UserLookupStrategy(value); this.finder.AddStrategy(locator, strategy); return null; }
public void Login() { driver = new InternetExplorerDriver(); try { //Run before any test driver.Navigate().GoToUrl(url + "MDM"); driver.FindElement(By.Id("userNameTextBox")).SendKeys(user); driver.FindElement(By.Id("passwordTextBox")).SendKeys(password); driver.FindElement(By.Id("loginBtn")).Click(); Common.WaitForElement(driver, By.ClassName("breadcrumbs"), 30); } catch (TimeoutException e) { System.Console.WriteLine("TimeoutException: " + e.Message); Assert.Fail(e.Message); } catch (NoSuchElementException e) { Assert.Fail(e.Message); } catch (Exception e) { System.Console.WriteLine("unhandled exception: " + e.Message); Assert.Fail(e.Message); } }
internal static void DestroyVisualSearch(IWebDriver webDriver) { MyLog.Write("DestroyVisualSearch: Started"); IJavaScriptExecutor jsExec = webDriver as IJavaScriptExecutor; string[] JavaSCriptObjectsToDestroy = new string[] { "document.SWD_Page_Recorder", "document.Swd_prevActiveElement", "document.swdpr_command", }; StringBuilder deathBuilder = new StringBuilder(); foreach (var sentencedToDeath in JavaSCriptObjectsToDestroy) { deathBuilder.AppendFormat(@" try {{ delete {0}; }} catch (e) {{ if (console) {{ console.log('ERROR: |{0}| --> ' + e.message)}} }} ", sentencedToDeath); } if (IsVisualSearchScriptInjected(webDriver)) { MyLog.Write("DestroyVisualSearch: Scripts have been injected previously. Kill'em all!"); jsExec.ExecuteScript(deathBuilder.ToString()); } MyLog.Write("DestroyVisualSearch: Finished"); }
protected override object HandleSeleneseCommand(IWebDriver driver, string pattern, string ignored) { string text = string.Empty; IWebElement body = driver.FindElement(By.XPath("/html/body")); IJavaScriptExecutor executor = driver as IJavaScriptExecutor; if (executor == null) { text = body.Text; } else { text = JavaScriptLibrary.CallEmbeddedHtmlUtils(driver, "getTextContent", body).ToString(); } text = text.Trim(); string strategyName = "implicit"; string use = pattern; if (TextMatchingStrategyAndValueRegex.IsMatch(pattern)) { Match textMatch = TextMatchingStrategyAndValueRegex.Match(pattern); strategyName = textMatch.Groups[1].Value; use = textMatch.Groups[2].Value; } ITextMatchingStrategy strategy = textMatchingStrategies[strategyName]; return strategy.IsAMatch(use, text); }
public void SetupTest() { driver = new FirefoxDriver(); driver.Manage().Window.Maximize(); baseURL = WebDriverExtension.BASE_URL; verificationErrors = new StringBuilder(); }
public static string GetElementXPath(IWebElement webElement, IWebDriver webDriver) { IJavaScriptExecutor jsExec = webDriver as IJavaScriptExecutor; return (string)jsExec.ExecuteScript( @" function getPathTo(element) { if (element === document.body) return '/html/' + element.tagName.toLowerCase(); var ix = 0; var siblings = element.parentNode.childNodes; for (var i = 0; i < siblings.length; i++) { var sibling = siblings[i]; if (sibling === element) { return getPathTo(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']'; } if (sibling.nodeType === 1 && sibling.tagName === element.tagName) ix++; } } var element = arguments[0]; var xpath = ''; xpath = getPathTo(element); return xpath; ", webElement); }
public void Recreate() { SeleniumTestBase.LogDriverId(driver, "Recreation - SelfCleanUpWebDriver (OLD)"); Dispose(); driver = CreateInstance(); SeleniumTestBase.LogDriverId(driver, "Recreation - SelfCleanUpWebDriver (NEW)"); }
public static void Start(BrowserType browserType = BrowserType.Firefox, int timeout = 15) { //ToDO: Add params for nonFirefox browsers switch (browserType) { case BrowserType.Firefox: WebDriver = new FirefoxDriver(); break; case BrowserType.Ie: WebDriver = new ChromeDriver(); break; case BrowserType.Chrome: WebDriver = new ChromeDriver(); break; case BrowserType.Edge: WebDriver = new EdgeDriver(); break; case BrowserType.PhantomJs: WebDriver = new PhantomJSDriver(); break; default: throw new ArgumentOutOfRangeException(nameof(browserType), browserType, null); } BrowserWait = new WebDriverWait(WebDriver, TimeSpan.FromSeconds(timeout)); }
public void TakeScreenshot(IWebDriver driver, string path) { ITakesScreenshot screenshotDriver = driver as ITakesScreenshot; Screenshot screenshot = screenshotDriver.GetScreenshot(); screenshot.SaveAsFile(path, System.Drawing.Imaging.ImageFormat.Png); screenshot.ToString(); }
ManageQueueSection( IWebDriver webBrowserDriver) : base(webBrowserDriver) { this.QueueInformation = new QueueInformationSection(webBrowserDriver); this.QueueClient = new QueueClientSection(webBrowserDriver); }
public static void Init() { if (TestEnvironment.BrowserName == BrowserType.FireFox & Driver == null) { Driver = new FirefoxDriver(); Driver.Manage().Window.Maximize(); //LoadPage(); } if (TestEnvironment.BrowserName == BrowserType.Chrome & Driver == null) { //Driver = new ChromeDriver(@"D:\Projects\Solution1\Eclips\Lib\BrowserExe"); Driver = new ChromeDriver(); Driver.Manage().Window.Maximize(); //LoadPage(); } if (TestEnvironment.BrowserName == BrowserType.IE & Driver == null) { Driver = new InternetExplorerDriver(); Driver.Manage().Window.Maximize(); //LoadPage(); } LoadPage(); //clearBrowserCache(); Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20)); }
/// <summary> /// Handles the command. /// </summary> /// <param name="driver">The driver used to execute the command.</param> /// <param name="locator">The first parameter to the command.</param> /// <param name="value">The second parameter to the command.</param> /// <returns>The result of the command.</returns> protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value) { StringBuilder builder = new StringBuilder(); this.mutator.Mutate(locator, builder); ((IJavaScriptExecutor)driver).ExecuteScript(builder.ToString()); return null; }
public SearchPage(IWebDriver driver) { this.driver = driver; Boolean isPresent = driver.FindElement(By.CssSelector("#btnFTPOutputFile")).Size > 0; if (isPresent == false) throw new NoSuchElementException("This is not the Search page"); }
public static void Dispose() { Driver.Quit(); Driver = null; }
public void Selectanoption(IWebDriver driver, By by, string optiontoselect) { var data = driver.FindElement(@by); //IList<IWebElement> dataoptions = data.FindElements(By.TagName("option")); var select = new SelectElement(data); @select.SelectByText(optiontoselect); }
public void Setup() { _driver = Starter.WebDriver; _driver.Navigate().GoToUrl("http://qm-homework.wikia.com"); _hp = PageObjects.HomePage; }
public IWebDriver LaunchBrowser(Browser browser) { switch (browser) { case Browser.IE: driver = StartIEBrowser(); break; case Browser.Chrome: driver = StartChromeBrowser(); break; case Browser.Safari: driver = StartSafariBrowser(); break; case Browser.Firefox: default: driver = StartFirefoxBrowser(); break; } driver.Manage().Cookies.DeleteAllCookies(); SetBrowserSize(); var eDriver = new EventedWebDriver(driver); return eDriver.driver; }
public void WhereIsMyCheese(string url) { try { _driver = Browser.GetFirefoxDriver(); _driver.Navigate().GoToUrl(url); _driver.FindElement(By.Id("windowOpener")).Click(); _driver.SwitchTo().Window("windowName"); _driver.FindElement(By.Id("CheesyButton")).Click(); _driver.SwitchTo().Alert().Accept(); } catch (System.Exception ex) { Console.WriteLine("An exception occured: " + ex.Message); Debug.WriteLine("An exception occured: " + ex.Message); } finally { _driver.Quit(); } }
private void TrySetupSteps(DriverType driverType, SeleniteTest test, IWebDriver webDriver) { if (test.TestCollection.SetupSteps.IsNullOrNotAny()) return; var fileName = String.IsNullOrWhiteSpace(test.TestCollection.SetupStepsFile) ? test.TestCollection.ResolvedFile : test.TestCollection.SetupStepsFile; foreach (var pair in _setupStepsMap) { if (pair.Key.Target != webDriver) continue; if (pair.Value.Any(f => String.Equals(f, fileName, StringComparison.InvariantCultureIgnoreCase))) return; } foreach (var setupStep in test.TestCollection.SetupSteps) _testService.ExecuteTest(webDriver, driverType, setupStep, true); var weakReference = new WeakReference(webDriver); var testFiles = new List<string> { fileName }; _setupStepsMap.Add(weakReference, testFiles); }
/// <summary> /// Initializes a new instance of the <see cref="TouchActions"/> class. /// </summary> /// <param name="driver">The <see cref="IWebDriver"/> object on which the actions built will be performed.</param> public TouchActions(IWebDriver driver) : base(driver) { IHasTouchScreen touchScreenDriver = driver as IHasTouchScreen; if (touchScreenDriver == null) { IWrapsDriver wrapper = driver as IWrapsDriver; while (wrapper != null) { touchScreenDriver = wrapper.WrappedDriver as IHasTouchScreen; if (touchScreenDriver != null) { break; } wrapper = wrapper.WrappedDriver as IWrapsDriver; } } if (touchScreenDriver == null) { throw new ArgumentException("The IWebDriver object must implement or wrap a driver that implements IHasTouchScreen.", "driver"); } this.touchScreen = touchScreenDriver.TouchScreen; }
public void Run(IWebDriver webDriver, Step step) { var e = ((ElementHasStyleStep)step); try { var element = ElementHelper.GetVisibleElement(webDriver, e.Element); string style = element.GetAttribute("style"); var styles = style.Split(';').Select(x => { var parts = x.Replace(" ", "").Split(':'); if (parts.Length != 2) return null; return new Style(parts[0], parts[1]); }).Where(x => x != null).ToList(); if (styles.All(x => x.Key != e.StyleKey)) throw new StepException(string.Format("The element '{0}' did not have the '{1}' style.", e.Element, e.StyleKey)); if (!styles.Any(x => x.Key == e.StyleKey && x.Value == e.StyleValue)) throw new StepException( string.Format("The element '{0}' had the '{1}' style, but it's value was not '{2}'.", e.Element, e.StyleKey, e.StyleValue)); } catch (NoSuchElementException ex) { throw new StepException(string.Format("The document does not contain an element that matches '{0}'.", e.Element)); } }
//Start the browser depending on the setting public void GetDriver(WebBrowsers webBrws) { WebBrws = webBrws; if (webBrws == WebBrowsers.Ie) { //Secutiry setting for IE var capabilitiesInternet = new InternetExplorerOptions { IntroduceInstabilityByIgnoringProtectedModeSettings = true }; Driver = new InternetExplorerDriver(capabilitiesInternet); } else if (webBrws == WebBrowsers.FireFox) { //FirefoxBinary binary = new FirefoxBinary(@"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"); FirefoxProfile profile = new FirefoxProfile(); // profile.SetPreference("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); Driver = new FirefoxDriver(profile); } else if (webBrws == WebBrowsers.Chrome) { //Chrome driver requires the ChromeDriver.exe Driver = new ChromeDriver(@"..\..\..\lib\BrowserDriver\Chrome"); } else { throw new WebDriverException(); } Selenium = new WebDriverBackedSelenium(Driver, BaseUrl); }
protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value) { string tableString = string.Empty; if (!TableParts.IsMatch(locator)) { throw new SeleniumException("Invalid target format. Correct format is tableName.rowNum.columnNum"); } Match tableMatch = TableParts.Match(locator); string tableName = tableMatch.Groups[0].Value; long row = int.Parse(tableMatch.Groups[1].Value, CultureInfo.InvariantCulture); long col = int.Parse(tableMatch.Groups[2].Value, CultureInfo.InvariantCulture); IWebElement table = finder.FindElement(driver, tableName); string script = "var table = arguments[0]; var row = arguments[1]; var col = arguments[2];" + "if (row > table.rows.length) { return \"Cannot access row \" + row + \" - table has \" + table.rows.length + \" rows\"; }" + "if (col > table.rows[row].cells.length) { return \"Cannot access column \" + col + \" - table row has \" + table.rows[row].cells.length + \" columns\"; }" + "return table.rows[row].cells[col];"; object returnValue = JavaScriptLibrary.ExecuteScript(driver, script, table, row, col); IWebElement elementReturned = returnValue as IWebElement; if (elementReturned != null) { tableString = ((IWebElement)returnValue).Text.Trim(); } else { throw new SeleniumException(returnValue.ToString()); } return tableString; }
public override void Specify() { given("the browser is firefox", delegate { Browser = arrange(() => new FirefoxBrowser()); go(); }); // maybe support skip remaining tests if any have failed so far? given("the browser is internet explorer", delegate { Browser = arrange(() => new InternetExplorerBroser()); go(); }); given("the browser is chrome", delegate { Browser = arrange(() => new ChromeBrowser()); go(); }); }
public void AddStorageLocationDialogSetupOneTime() { driver = TestConfig.RepositoryTestSetup(); wait = Root.SetUptWebDriverWait(driver); }
static void ScrapeOberloOrders(IWebDriver driver, List <OberloOrder> oberloOrders, DateTime from, DateTime to, int page) { // https://app.oberlo.com/orders?from=2017-01-01&to=2017-12-31&page=1 string url = string.Format("https://app.oberlo.com/orders?from={0:yyyy-MM-dd}&to={1:yyyy-MM-dd}&page={2}", from, to, page); driver.Navigate().GoToUrl(url); var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); var ready = wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete")); IJavaScriptExecutor js = driver as IJavaScriptExecutor; var json = js.ExecuteScript("return window.App.payload.orders;"); // convert to json dynamic object string jsonString = JsonConvert.SerializeObject(json); dynamic jsonD = JsonConvert.DeserializeObject(jsonString); // https://app.oberlo.com/orders?from=2017-01-01&to=2017-12-31&page=1 // identify how many pages on order page // current_page // last_page // per_page // data (System.Collections.ObjectModel) int current_page = jsonD.current_page; int last_page = jsonD.last_page; int per_page = jsonD.per_page; // process orders on page var orders = jsonD.data; foreach (var order in orders) { // order_name // processed_at // total_price // shipping_name // shipping_zip // shipping_city // shipping_address1 // orderitems var orderName = order.order_name; var processedAt = order.processed_at; var totalPrice = order.total_price; var financialStatus = order.financial_status; var fulfillmentStatus = order.fullfullment_status; var shippingName = order.shipping_name; var shippingZip = order.shipping_zip; var shippingCity = order.shipping_city; var shippingAddress1 = order.shipping_address1; var shippingAddress2 = order.shipping_address2; var orderNote = order.local_note; var orderitems = order.orderitems; foreach (var orderitem in orderitems) { var aliOrderNumber = orderitem.ali_order_no; var SKU = orderitem.sku; var supplier = orderitem.supplier_name; var productName = orderitem.title; var variant = orderitem.variant_title; var cost = orderitem.cost; var quantity = orderitem.quantity; string trackingNumber = ""; foreach (var fulfillment in orderitem.fulfillments) { if (trackingNumber.Equals("")) { trackingNumber = fulfillment.tracking_number; } else { trackingNumber += ", " + fulfillment.tracking_number; } } var oberloOrder = new OberloOrder(); oberloOrder.OrderNumber = orderName; oberloOrder.CreatedDate = processedAt; oberloOrder.FinancialStatus = financialStatus; oberloOrder.FulfillmentStatus = fulfillmentStatus; oberloOrder.Supplier = supplier; oberloOrder.SKU = SKU; oberloOrder.ProductName = productName; oberloOrder.Variant = variant; oberloOrder.Quantity = quantity; oberloOrder.TrackingNumber = trackingNumber; oberloOrder.AliOrderNumber = aliOrderNumber; oberloOrder.CustomerName = shippingName; oberloOrder.CustomerAddress = shippingAddress1; oberloOrder.CustomerAddress2 = shippingAddress2; oberloOrder.CustomerCity = shippingCity; oberloOrder.CustomerZip = shippingZip; oberloOrder.OrderNote = orderNote; //oberloOrder.OrderState = orderState; oberloOrder.Cost = cost; oberloOrders.Add(oberloOrder); } } }
public ProductSearchSteps(IWebDriver driver) { _searchPage = new ProductSearchPage(driver); _lenguageChangePage = new LenguageChangePage(driver); }
public MenuDashboardPage(IWebDriver driver) : base(driver) { }
public Inventory(IWebDriver _driver) => driver = _driver;
public PlaceOrderPage(IWebDriver ldriver) { this.driver = ldriver; PageFactory.InitElements(driver, this); }
public FaleConoscoSteps(IWebDriver driver, TestContext test) { this.driver = driver; this.test = test; }
public static IJavaScriptExecutor JavaScriptExecutor(this IWebDriver driver) { return((IJavaScriptExecutor)driver); }
public void GivenUserIsOnTheEcommercePage() { driver = utilities.DriverFactory.newBrowser("firefox"); driver.Navigate().GoToUrl("http://sdettraining.com/online/"); }
/// <summary> /// Method that tries to wait /// </summary> /// <param name="driver"></param> /// <param name="byOfElementToWaitForToBeVisable"></param> public static void Wait(IWebDriver driver, By byOfElementToWaitForToBeVisable) { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); wait.Until(ExpectedConditions.ElementIsVisible(byOfElementToWaitForToBeVisable)); }
public void StartBrowser(IWebDriver _driver) { _driver.Url = "https://www.switchyourenergy.com/"; }
public void KillBrowser(IWebDriver _driver) { _driver.Close(); }
public AccountLogPage(IWebDriver webDriver, Uri baseUri) : base(webDriver, baseUri, PageTitles.ACCOUNT_LOG) { MenuBar = new MenuBar(webDriver, baseUri); }
public Logout(IWebDriver driver) { this.driver = driver; PageFactory.InitElements(driver, this); }
public PageDepositPaysec(IWebDriver driver, string lng = "en") : base(driver, lng) { }
public SearchByFeatureSteps(IWebDriver _driver, ExtentTest test) { this._driver = _driver; this.test = test; }
public Web_Front_End_Page(IWebDriver driver) { _driver = driver; }
public ListOfiPhone7Page() { _driver = DriverHelper.Driver; }
public T ExecuteAndGet <T>(IWebDriver driver) { return(ExecuteAndGet <T>((IJavaScriptExecutor)driver)); }
public void Execute(IWebDriver driver) { Execute((IJavaScriptExecutor)driver); }
public void Close() { driver.Close(); driver = null; }
public object ExecuteAndGet(IWebDriver driver) { return(ExecuteAndGet((IJavaScriptExecutor)driver)); }
public void Initialize() { this.driver = new ChromeDriver(); this.driver.Manage().Window.Maximize(); }
//constructor public ProfilepageTitleandFooter(IWebDriver driver) { this.driver = driver; //calls init method this.Init(); }
public WebElement(IWebElement implicitElement, IWebDriver driver) : this(implicitElement, null, driver) { }
public void AddNewRepositoryDialogSetupOnetime() { driver = TestConfig.RepositoryTestSetup(); wait = Root.SetUptWebDriverWait(driver); }
public Past341MeetingsCountPage(IWebDriver driver) : base(driver, pageExpectedTitle) { }
public static IWebElement WaitForElementToBeClickable(this IWebDriver driver, int waitTime, IWebElement waitingElement) { IWebElement wait = new WebDriverWait(driver, TimeSpan.FromSeconds(waitTime)).Until(ExpectedConditions.ElementToBeClickable(waitingElement)); return(wait); }
private static void SearchingQuery(string query, IWebDriver driver, IWebElement searchBarElement, out Actions searchAction) { searchAction = new Actions(driver).MoveToElement(searchBarElement) .Click().SendKeys(query).SendKeys(Keys.Enter); searchAction.Perform(); }
public ServiceListingPage(IWebDriver driver) { this.driver = driver; }