Advertisement
Guest User

C# Webdriver Element Location Wrapper

a guest
Aug 3rd, 2012
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.59 KB | None | 0 0
  1. using System;
  2. using OpenQA.Selenium;
  3. using OpenQA.Selenium.Firefox;
  4. using OpenQA.Selenium.Remote;
  5. using Microsoft.VisualStudio.TestTools.UnitTesting;
  6. using System.Collections.ObjectModel;
  7.  
  8. namespace MyProject
  9. {
  10.     [TestClass]
  11.     public class WebDriverTestScript
  12.     {
  13.         #region "Configuration"
  14.  
  15.         IWebDriver driver;
  16.         string TARGET = "http://my_target/";
  17.         const int STANDARD_TIMEOUT = 1; // In seconds.
  18.         string SCREENSHOT_PATH = System.AppDomain.CurrentDomain.BaseDirectory + @"\Screenshots\";
  19.  
  20.         #endregion "Configuration"
  21.  
  22.         #region "Inputs"
  23.         // Any standard inputs (e.g. login details) can be put here.
  24.         // If we end up with a relatively small number of inputs we may want
  25.         // to put them in a config file.
  26.         #endregion "Inputs"
  27.  
  28.         #region "Setup and Teardown"
  29.  
  30.         /// <summary>
  31.         /// The TestInitialize() tag signifies that any code within this method will be
  32.         /// executed prior to each test.
  33.         /// </summary>
  34.         /// <remarks>We will use this to initialise the test state.  E.g. Profile
  35.         /// issues (proxies, etc), test window management.</remarks>
  36.         [TestInitialize()]
  37.         public void SetupTest()
  38.        {
  39.             // Create custom profile
  40.             FirefoxProfile profile = new FirefoxProfile();
  41.  
  42.             // Create custom proxy
  43.             Proxy prx = new Proxy();
  44.             prx.IsAutoDetect = true;
  45.            
  46.             // Assign proxy
  47.             profile.SetProxyPreferences(prx);
  48.  
  49.             // Start the local firefox driver
  50.             driver = new FirefoxDriver(profile);
  51.  
  52.  
  53.             // The lines below can be used to specify the usage of a version of
  54.             // Firefox NOT installed to the default path
  55.             // (Useful when your main installation upgrades to an incompatible version
  56.             //  and breaks your tests.)
  57.             //
  58.             // FirefoxBinary binary = new FirefoxBinary("path/to/firefox");
  59.             // driver = new FirefoxDriver(binary, null);
  60.  
  61.             // Maximise the automated browser window  
  62.             driver.Manage().Window.Maximize();
  63.             // Set an implicit timeout
  64.             SetImplicitTimeout(STANDARD_TIMEOUT);
  65.             // Navigate to the landing page
  66.             driver.Navigate().GoToUrl(TARGET);
  67.         }
  68.  
  69.         /// <summary>
  70.         /// The TestCleanup() tag signifies that any code within this method will be
  71.         /// executed after each test completes.
  72.         /// </summary>
  73.         /// <remarks>We will generally use this to close the driver and clear common state
  74.         /// (e.g. logging out of the site if necessary) </remarks>
  75.         [TestCleanup()]
  76.         public void TeardownTest()
  77.         {
  78.             try
  79.             { driver.Quit(); }
  80.             catch (Exception)
  81.             {// Ignore errors if unable to close the browser
  82.             }
  83.         }
  84.  
  85.         /// <summary>
  86.         /// Define a period to automatically poll the DOM for elements when Locating
  87.         /// </summary>
  88.         /// <param name="iSecs">The timeout in seconds</param>
  89.         /// <remarks>If you EXPECT an element to not exist, be aware that
  90.         /// you will incur this timeout delay each time you check for it.
  91.         /// (e.g. asserting error text is not present)</remarks>
  92.         private void SetImplicitTimeout(int iSecs)
  93.         { driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(iSecs)); }
  94.         #endregion "Setup and Teardown"
  95.  
  96.         #region "Tests"
  97.  
  98.         /// <summary>
  99.         /// This is the test template.  Just rename this to create your first test.
  100.         /// </summary>
  101.         [TestMethod, TestCategory("Example Category")]
  102.         public void TestTemplate()
  103.         {
  104.            
  105.         }
  106.  
  107.         #endregion "Tests"
  108.  
  109.         #region "Location methods"
  110.         /// <summary>
  111.         /// This will attempt to locate the web element uniquely identified by the supplied parameters,
  112.         /// with the specified timeout.
  113.         /// </summary>
  114.         /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
  115.         /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
  116.         /// <param name="strText">The value text to expect (e.g. btnLogin)</param>
  117.         /// <param name="iTimeout">The amount of time (in seconds) to wait for the element to appear. This is optional.</param>
  118.         /// <returns>The IWebElement that matches the specified locator specification</returns>
  119.         /// <remarks>This method is essentially the most atomic state of a WebElement, so cannot be broken down further.  
  120.         /// An encapsulated element reference using this method is probably the most efficient form of existence
  121.         /// assertion as it's inherent to the method.</remarks>
  122.         private IWebElement Locate(string strElementType, string strAttrib, string strText, int iTimeout = STANDARD_TIMEOUT)
  123.         {
  124.             SetImplicitTimeout(iTimeout);
  125.             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))); }
  126.             catch (Exception) { Assert.Fail("Timeout of [" + iTimeout + "sec] expired for element [" + strElementType + "," + strAttrib + "," + strText + "] at URL '" + driver.Url + "'"); return null; }
  127.             finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
  128.         }
  129.  
  130.         private IWebElement LocateParentOf(string strElementType, string strAttrib, string strText, int iTimeout = STANDARD_TIMEOUT)
  131.         {
  132.             SetImplicitTimeout(iTimeout);
  133.             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))); }
  134.             catch (Exception) { Assert.Fail("Timeout of [" + iTimeout + "sec] expired for element [" + strElementType + "," + strAttrib + "," + strText + "] at URL '" + driver.Url + "'"); return null; }
  135.             finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
  136.         }
  137.  
  138.         /// <summary>
  139.         /// This will attempt to locate the web element of the specified type, containing the specified text.
  140.         /// </summary>
  141.         /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
  142.         /// <param name="strContainingText">The text to check for.</param>
  143.         /// <param name="iTimeout">The amount of time (in seconds) to wait for the element to appear. This is optional.</param>
  144.         /// <returns>The IWebElement that matches the specified locator specification</returns>
  145.         /// <remarks>While convenient this locator is much more prone to multiple matches so should be used with care.</remarks>
  146.         private IWebElement Locate(string strElementType, string strContainingText, int iTimeout = STANDARD_TIMEOUT)
  147.         {
  148.             SetImplicitTimeout(iTimeout);
  149.             try { return driver.FindElement(By.XPath(@"//" + strElementType + "[contains(text(),'" + strContainingText + "')]")); }
  150.             catch (Exception) { Assert.Fail("Timeout of [" + iTimeout + "sec] expired for element [" + strElementType + ", text:" + strContainingText + "] at URL '" + driver.Url + "'"); return null; }
  151.             finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
  152.         }
  153.  
  154.         /// <summary>
  155.         /// This will locate the web elements uniquely identified by the supplied parameters.
  156.         /// </summary>
  157.         /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
  158.         /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
  159.         /// <param name="strText">The value text to expect (e.g. btnLogin)</param>
  160.         /// <returns>A ReadOnlyCollection of IWebElements matching the supplied signature</returns>
  161.         private ReadOnlyCollection<IWebElement> LocateAll(string strElementType, string strAttrib, string strText)
  162.         {
  163.             if (strAttrib == ".")
  164.                 return driver.FindElements(By.XPath(String.Format("//{0}[contains({1},'{2}')]", strElementType, strAttrib, strText)));
  165.             else
  166.                 return driver.FindElements(By.XPath(String.Format("//{0}[contains(@{1},'{2}')]", strElementType, strAttrib, strText)));
  167.         }
  168.  
  169.         /// <summary>
  170.         /// This will locate the first (preferably only) web element within the specified parent, that matches
  171.         /// the supplied signature.
  172.         /// </summary>
  173.         /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
  174.         /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
  175.         /// <param name="strText">The value text to expect (e.g. btnLogin)</param>
  176.         /// <param name="Parent">The Parent element to search within</param>
  177.         /// <param name="iTimeout">The amount of time (in seconds) to wait for the element to appear. This is optional.</param>
  178.         /// <returns>The WebElement matching the supplied signature.</returns>
  179.         /// <remarks>TODO: Deal with '.' Attribute</remarks>
  180.         private IWebElement LocateWithin(string strElementType, string strAttrib, string strText, IWebElement Parent, int iTimeout = STANDARD_TIMEOUT)
  181.         {
  182.             SetImplicitTimeout(iTimeout);
  183.             try { return Parent.FindElement(By.XPath(@".//" + strElementType + "[contains(@" + strAttrib + ",'" + strText + "')]")); }
  184.             catch (Exception) { Assert.Fail("Timeout of [" + iTimeout + "sec] expired for element [" + strElementType + "," + strAttrib + "," + strText + "] at URL '" + driver.Url + "'"); return null; }
  185.             finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
  186.         }
  187.  
  188.  
  189.         /// <summary>
  190.         /// This will locate the all web elements within the specified parent, that matches the supplied signature.
  191.         /// </summary>
  192.         /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
  193.         /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
  194.         /// <param name="strText">The value text to expect (e.g. btnLogin)</param>
  195.         /// <param name="Parent">The Parent element to search within</param>
  196.         /// <returns>The WebElements matching the supplied signature.</returns>
  197.         /// <remarks>TODO: Deal with '.' Attribute</remarks>
  198.         private ReadOnlyCollection<IWebElement> LocateAllWithin(string strElementType, string strAttrib, string strText, IWebElement Parent)
  199.         { return Parent.FindElements(By.XPath(@".//" + strElementType + "[contains(@" + strAttrib + ",'" + strText + "')]")); }
  200.  
  201.         /// <summary>
  202.         /// This will effectively check the web element uniquely identified by the supplied parameters.
  203.         /// </summary>
  204.         /// <param name="strElementType">The type of the element to locate (e.g. input, div, a)</param>
  205.         /// <param name="strAttrib">The attribute to check (e.g. id, class, title)</param>
  206.         /// <param name="strText">The text to expect (e.g. btnLogin)</param>
  207.         /// <param name="iTimeout">The amount of time (in seconds) to wait for the element to appear. This is optional.</param>
  208.         /// <returns>Whether or not the specified element exists</returns>
  209.         private bool Exists(string strElementType, string strAttrib, string strText, int iTimeout = STANDARD_TIMEOUT)
  210.         {
  211.  
  212.             SetImplicitTimeout(iTimeout);
  213.             try { driver.FindElement(By.XPath(String.Format("//{0}[contains({1},'{2}')]", strElementType, strAttrib, strText))); return true; }
  214.             catch (Exception) { return false; }
  215.             finally { SetImplicitTimeout(STANDARD_TIMEOUT); }
  216.         }
  217.         #endregion "Location methods"
  218.  
  219.         #region "Support methods"
  220.        
  221.         /// <summary>
  222.         /// This will take a screenshot of the currently rendered page and save it to the path set in the script.
  223.         /// </summary>
  224.         /// <param name="strFilename">The filename to save the screenshot to, without extension.</param>
  225.         /// <remarks>This method will require a reference to System.Drawing.</remarks>
  226.         private void TakeScreenshot(string strFilename)
  227.         {
  228.             ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(SCREENSHOT_PATH + strFilename + ".png", System.Drawing.Imaging.ImageFormat.Png);
  229.         }
  230.  
  231.         /// <summary> This will switch WebDriver focus to the original window. </summary>
  232.         private void SwitchToOriginalWindow()
  233.         { driver.SwitchTo().Window(driver.WindowHandles[0]); }
  234.  
  235.         /// <summary> This will switch WebDriver focus to the window last spawned. </summary>
  236.         private void SwitchToNewWindow()
  237.         { driver.SwitchTo().Window(driver.WindowHandles[driver.WindowHandles.Count - 1]); }
  238.  
  239.         /// <summary> This will switch WebDriver focus to the window at the specified index. </summary>
  240.         /// <remarks>Indexed from zero.</remarks>
  241.         private void SwitchToWindow(int index)
  242.         { driver.SwitchTo().Window(driver.WindowHandles[index]); }
  243.  
  244.         /// <summary>This will cause the driver to open the specified link. </summary>
  245.         /// <param name="strLink">The URL to open.</param>
  246.         /// <remarks>This will assume the specified link is in valid http format.</remarks>
  247.         private void Open(string strLink)
  248.         { driver.Navigate().GoToUrl(strLink); }
  249.  
  250.         #endregion "Support methods"
  251.     }
  252. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement