Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using OpenQA.Selenium;
- using OpenQA.Selenium.Firefox;
- using OpenQA.Selenium.Remote;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
- using System.Collections.ObjectModel;
- namespace MyProject
- {
- [TestClass]
- public class WebDriverTestScript
- {
- #region "Configuration"
- IWebDriver driver;
- string TARGET = "http://my_target/";
- const int STANDARD_TIMEOUT = 1; // In seconds.
- string SCREENSHOT_PATH = System.AppDomain.CurrentDomain.BaseDirectory + @"\Screenshots\";
- #endregion "Configuration"
- #region "Inputs"
- // Any standard inputs (e.g. login details) can be put here.
- // If we end up with a relatively small number of inputs we may want
- // to put them in a config file.
- #endregion "Inputs"
- #region "Setup and Teardown"
- /// <summary>
- /// The TestInitialize() tag signifies that any code within this method will be
- /// executed prior to each test.
- /// </summary>
- /// <remarks>We will use this to initialise the test state. E.g. Profile
- /// issues (proxies, etc), test window management.</remarks>
- [TestInitialize()]
- public void SetupTest()
- {
- // Create custom profile
- FirefoxProfile profile = new FirefoxProfile();
- // Create custom proxy
- Proxy prx = new Proxy();
- prx.IsAutoDetect = true;
- // Assign proxy
- profile.SetProxyPreferences(prx);
- // Start the local firefox driver
- driver = new FirefoxDriver(profile);
- // The lines below can be used to specify the usage of a version of
- // Firefox NOT installed to the default path
- // (Useful when your main installation upgrades to an incompatible version
- // and breaks your tests.)
- //
- // FirefoxBinary binary = new FirefoxBinary("path/to/firefox");
- // driver = new FirefoxDriver(binary, null);
- // Maximise the automated browser window
- driver.Manage().Window.Maximize();
- // Set an implicit timeout
- SetImplicitTimeout(STANDARD_TIMEOUT);
- // Navigate to the landing page
- driver.Navigate().GoToUrl(TARGET);
- }
- /// <summary>
- /// The TestCleanup() tag signifies that any code within this method will be
- /// executed after each test completes.
- /// </summary>
- /// <remarks>We will generally use this to close the driver and clear common state
- /// (e.g. logging out of the site if necessary) </remarks>
- [TestCleanup()]
- public void TeardownTest()
- {
- try
- { driver.Quit(); }
- catch (Exception)
- {// Ignore errors if unable to close the browser
- }
- }
- /// <summary>
- /// Define a period to automatically poll the DOM for elements when Locating
- /// </summary>
- /// <param name="iSecs">The timeout in seconds</param>
- /// <remarks>If you EXPECT an element to not exist, be aware that
- /// you will incur this timeout delay each time you check for it.
- /// (e.g. asserting error text is not present)</remarks>
- private void SetImplicitTimeout(int iSecs)
- { driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(iSecs)); }
- #endregion "Setup and Teardown"
- #region "Tests"
- /// <summary>
- /// This is the test template. Just rename this to create your first test.
- /// </summary>
- [TestMethod, TestCategory("Example Category")]
- public void TestTemplate()
- {
- }
- #endregion "Tests"
- #region "Location methods"
- /// <summary>
- /// This will attempt to locate the web element uniquely identified by the supplied parameters,
- /// with the specified timeout.
- /// </summary>
- /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
- /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
- /// <param name="strText">The value text to expect (e.g. btnLogin)</param>
- /// <param name="iTimeout">The amount of time (in seconds) to wait for the element to appear. This is optional.</param>
- /// <returns>The IWebElement that matches the specified locator specification</returns>
- /// <remarks>This method is essentially the most atomic state of a WebElement, so cannot be broken down further.
- /// An encapsulated element reference using this method is probably the most efficient form of existence
- /// assertion as it's inherent to the method.</remarks>
- private IWebElement Locate(string strElementType, string strAttrib, string strText, int iTimeout = STANDARD_TIMEOUT)
- {
- SetImplicitTimeout(iTimeout);
- try { return strAttrib == "." ? driver.FindElement(By.XPath(String.Format("//{0}[contains({1},'{2}')]", strElementType, strAttrib, strText))) : driver.FindElement(By.XPath(String.Format("//{0}[contains(@{1},'{2}')]", strElementType, strAttrib, strText))); }
- catch (Exception) { Assert.Fail("Timeout of [" + iTimeout + "sec] expired for element [" + strElementType + "," + strAttrib + "," + strText + "] at URL '" + driver.Url + "'"); return null; }
- finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
- }
- private IWebElement LocateParentOf(string strElementType, string strAttrib, string strText, int iTimeout = STANDARD_TIMEOUT)
- {
- SetImplicitTimeout(iTimeout);
- try { return strAttrib == "." ? driver.FindElement(By.XPath(String.Format("//{0}[contains({1},'{2}')]/..", strElementType, strAttrib, strText))) : driver.FindElement(By.XPath(String.Format("//{0}[contains(@{1},'{2}')]/..", strElementType, strAttrib, strText))); }
- catch (Exception) { Assert.Fail("Timeout of [" + iTimeout + "sec] expired for element [" + strElementType + "," + strAttrib + "," + strText + "] at URL '" + driver.Url + "'"); return null; }
- finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
- }
- /// <summary>
- /// This will attempt to locate the web element of the specified type, containing the specified text.
- /// </summary>
- /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
- /// <param name="strContainingText">The text to check for.</param>
- /// <param name="iTimeout">The amount of time (in seconds) to wait for the element to appear. This is optional.</param>
- /// <returns>The IWebElement that matches the specified locator specification</returns>
- /// <remarks>While convenient this locator is much more prone to multiple matches so should be used with care.</remarks>
- private IWebElement Locate(string strElementType, string strContainingText, int iTimeout = STANDARD_TIMEOUT)
- {
- SetImplicitTimeout(iTimeout);
- try { return driver.FindElement(By.XPath(@"//" + strElementType + "[contains(text(),'" + strContainingText + "')]")); }
- catch (Exception) { Assert.Fail("Timeout of [" + iTimeout + "sec] expired for element [" + strElementType + ", text:" + strContainingText + "] at URL '" + driver.Url + "'"); return null; }
- finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
- }
- /// <summary>
- /// This will locate the web elements uniquely identified by the supplied parameters.
- /// </summary>
- /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
- /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
- /// <param name="strText">The value text to expect (e.g. btnLogin)</param>
- /// <returns>A ReadOnlyCollection of IWebElements matching the supplied signature</returns>
- private ReadOnlyCollection<IWebElement> LocateAll(string strElementType, string strAttrib, string strText)
- {
- if (strAttrib == ".")
- return driver.FindElements(By.XPath(String.Format("//{0}[contains({1},'{2}')]", strElementType, strAttrib, strText)));
- else
- return driver.FindElements(By.XPath(String.Format("//{0}[contains(@{1},'{2}')]", strElementType, strAttrib, strText)));
- }
- /// <summary>
- /// This will locate the first (preferably only) web element within the specified parent, that matches
- /// the supplied signature.
- /// </summary>
- /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
- /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
- /// <param name="strText">The value text to expect (e.g. btnLogin)</param>
- /// <param name="Parent">The Parent element to search within</param>
- /// <param name="iTimeout">The amount of time (in seconds) to wait for the element to appear. This is optional.</param>
- /// <returns>The WebElement matching the supplied signature.</returns>
- /// <remarks>TODO: Deal with '.' Attribute</remarks>
- private IWebElement LocateWithin(string strElementType, string strAttrib, string strText, IWebElement Parent, int iTimeout = STANDARD_TIMEOUT)
- {
- SetImplicitTimeout(iTimeout);
- try { return Parent.FindElement(By.XPath(@".//" + strElementType + "[contains(@" + strAttrib + ",'" + strText + "')]")); }
- catch (Exception) { Assert.Fail("Timeout of [" + iTimeout + "sec] expired for element [" + strElementType + "," + strAttrib + "," + strText + "] at URL '" + driver.Url + "'"); return null; }
- finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
- }
- /// <summary>
- /// This will locate the all web elements within the specified parent, that matches the supplied signature.
- /// </summary>
- /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
- /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
- /// <param name="strText">The value text to expect (e.g. btnLogin)</param>
- /// <param name="Parent">The Parent element to search within</param>
- /// <returns>The WebElements matching the supplied signature.</returns>
- /// <remarks>TODO: Deal with '.' Attribute</remarks>
- private ReadOnlyCollection<IWebElement> LocateAllWithin(string strElementType, string strAttrib, string strText, IWebElement Parent)
- { return Parent.FindElements(By.XPath(@".//" + strElementType + "[contains(@" + strAttrib + ",'" + strText + "')]")); }
- /// <summary>
- /// This will effectively check the web element uniquely identified by the supplied parameters.
- /// </summary>
- /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
- /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
- /// <param name="strText">The text to expect (e.g. btnLogin)</param>
- /// <param name="iTimeout">The amount of time (in seconds) to wait for the element to appear. This is optional.</param>
- /// <returns>Whether or not the specified element exists</returns>
- private bool Exists(string strElementType, string strAttrib, string strText, int iTimeout = STANDARD_TIMEOUT)
- {
- SetImplicitTimeout(iTimeout);
- try { driver.FindElement(By.XPath(String.Format("//{0}[contains({1},'{2}')]", strElementType, strAttrib, strText))); return true; }
- catch (Exception) { return false; }
- finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
- }
- #endregion "Location methods"
- #region "Support methods"
- /// <summary>
- /// This will take a screenshot of the currently rendered page and save it to the path set in the script.
- /// </summary>
- /// <param name="strFilename">The filename to save the screenshot to, without extension.</param>
- /// <remarks>This method will require a reference to System.Drawing.</remarks>
- private void TakeScreenshot(string strFilename)
- {
- ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(SCREENSHOT_PATH + strFilename + ".png", System.Drawing.Imaging.ImageFormat.Png);
- }
- /// <summary> This will switch WebDriver focus to the original window. </summary>
- private void SwitchToOriginalWindow()
- { driver.SwitchTo().Window(driver.WindowHandles[0]); }
- /// <summary> This will switch WebDriver focus to the window last spawned. </summary>
- private void SwitchToNewWindow()
- { driver.SwitchTo().Window(driver.WindowHandles[driver.WindowHandles.Count - 1]); }
- /// <summary> This will switch WebDriver focus to the window at the specified index. </summary>
- /// <remarks>Indexed from zero.</remarks>
- private void SwitchToWindow(int index)
- { driver.SwitchTo().Window(driver.WindowHandles[index]); }
- /// <summary>This will cause the driver to open the specified link. </summary>
- /// <param name="strLink">The URL to open.</param>
- /// <remarks>This will assume the specified link is in valid http format.</remarks>
- private void Open(string strLink)
- { driver.Navigate().GoToUrl(strLink); }
- #endregion "Support methods"
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement