📜 ⬆️ ⬇️

Automated testing of a web application (MS Unit Testing Framework + Selenium WebDriver C #). Part 2.1: Selenium API wrapper - Browser

Selenium + C #
Introduction

Hello again! I present to you the second part of the article on automated testing of web applications on Selenium and C #. And if the first part was from the category of "captain obvious", which caused the indignation of readers, then in this part there will be a lot of code. And so, why write a wrapper over the Selenium API? In my opinion, users may encounter the following problems:

Well, a lot of problems - a lot of solutions. I do not want and can not explain everything at once in this part. A long post will be uninteresting, and while writing it enthusiasm drops sharply) Therefore, this part has the number 2.1, in it I will show my wrapper over the browser.

Links

Part 1: Introduction
Part 2.1: Selenium API wrapper - Browser
Part 2.2: Selenium API wrapper - WebElement
Part 3: WebPages - describing pages
Part 4: Finally writing tests
Framework Publishing

Go. Wrapper implementation over the browser: Browser class

I really hope that the above code does not seem difficult to you.
In the example, all IWebDriver-specific code is encapsulated, the pants are not protruding to the outside, i.e. autotest developers will not have direct access to the driver. As a consequence, there are methods in which the driver method with the same name is called.
There are no comments in the code - this is a good tone, and as one intelligent person said: “Comments in the code are like hair in soup. Would you eat hair soup ?! ”
I use Microsoft Code Contracts, do not be intimidated by the calls.
It is also worth noting that jquery is connected in the product under test, and some actions will be performed using it.
')
The Browser class supports 3 browsers:

It’s a pity that there are no C # drivers for Opera :(

Implemented a set of standard methods and properties like:

I think the names are quite obvious, so go ahead.

Also implemented specific functions:

namespace Autotests.Utilities { [Serializable] public enum Browsers { [Description("Windows Internet Explorer")] InternetExplorer, [Description("Mozilla Firefox")] Firefox, [Description("Google Chrome")] Chrome } public static class Browser { #region Public properties public static Browsers SelectedBrowser { get { return Settings.Default.Browser; } } public static Uri Url { get { WaitAjax(); return new Uri(WebDriver.Url); } } public static string Title { get { WaitAjax(); return string.Format("{0} - {1}", WebDriver.Title, EnumHelper.GetEnumDescription(SelectedBrowser)); } } public static string PageSource { get { WaitAjax(); return WebDriver.PageSource; } } #endregion #region Public methods public static void Start() { _webDriver = StartWebDriver(); } public static void Navigate(Uri url) { Contract.Requires(url != null); WebDriver.Navigate().GoToUrl(url); } public static void Quit() { if (_webDriver == null) return; _webDriver.Quit(); _webDriver = null; } public static void WaitReadyState() { Contract.Assume(WebDriver != null); var ready = new Func<bool>(() => (bool)ExecuteJavaScript("return document.readyState == 'complete'")); Contract.Assert(Executor.SpinWait(ready, TimeSpan.FromSeconds(60), TimeSpan.FromMilliseconds(100))); } public static void WaitAjax() { Contract.Assume(WebDriver != null); var ready = new Func<bool>(() => (bool)ExecuteJavaScript("return (typeof($) === 'undefined') ? true : !$.active;")); Contract.Assert(Executor.SpinWait(ready, TimeSpan.FromSeconds(60), TimeSpan.FromMilliseconds(100))); } public static void SwitchToFrame(IWebElement inlineFrame) { WebDriver.SwitchTo().Frame(inlineFrame); } public static void SwitchToPopupWindow() { foreach (var handle in WebDriver.WindowHandles.Where(handle => handle != _mainWindowHandler)) // TODO: { WebDriver.SwitchTo().Window(handle); } } public static void SwitchToMainWindow() { WebDriver.SwitchTo().Window(_mainWindowHandler); } public static void SwitchToDefaultContent() { WebDriver.SwitchTo().DefaultContent(); } public static void AcceptAlert() { var accept = Executor.MakeTry(() => WebDriver.SwitchTo().Alert().Accept()); Executor.SpinWait(accept, TimeSpan.FromSeconds(5)); } public static IEnumerable<IWebElement> FindElements(By selector) { Contract.Assume(WebDriver != null); return WebDriver.FindElements(selector); } public static Screenshot GetScreenshot() { WaitReadyState(); return ((ITakesScreenshot)WebDriver).GetScreenshot(); } public static void SaveScreenshot(string path) { Contract.Requires(!string.IsNullOrEmpty(path)); GetScreenshot().SaveAsFile(path, ImageFormat.Jpeg); } public static void DragAndDrop(IWebElement source, IWebElement destination) { (new Actions(WebDriver)).DragAndDrop(source, destination).Build().Perform(); } public static void ResizeWindow(int width, int height) { ExecuteJavaScript(string.Format("window.resizeTo({0}, {1});", width, height)); } public static void NavigateBack() { WebDriver.Navigate().Back(); } public static void Refresh() { WebDriver.Navigate().Refresh(); } public static object ExecuteJavaScript(string javaScript, params object[] args) { var javaScriptExecutor = (IJavaScriptExecutor)WebDriver; return javaScriptExecutor.ExecuteScript(javaScript, args); } public static void KeyDown(string key) { new Actions(WebDriver).KeyDown(key); } public static void KeyUp(string key) { new Actions(WebDriver).KeyUp(key); } public static void AlertAccept() { Thread.Sleep(2000); WebDriver.SwitchTo().Alert().Accept(); WebDriver.SwitchTo().DefaultContent(); } #endregion #region Private private static IWebDriver _webDriver; private static string _mainWindowHandler; private static IWebDriver WebDriver { get { return _webDriver ?? StartWebDriver(); } } private static IWebDriver StartWebDriver() { Contract.Ensures(Contract.Result<IWebDriver>() != null); if (_webDriver != null) return _webDriver; switch (SelectedBrowser) { case Browsers.InternetExplorer: _webDriver = StartInternetExplorer(); break; case Browsers.Firefox: _webDriver = StartFirefox(); break; case Browsers.Chrome: _webDriver = StartChrome(); break; default: throw new Exception(string.Format("Unknown browser selected: {0}.", SelectedBrowser)); } _webDriver.Manage().Window.Maximize(); _mainWindowHandler = _webDriver.CurrentWindowHandle; return WebDriver; } private static InternetExplorerDriver StartInternetExplorer() { var internetExplorerOptions = new InternetExplorerOptions { IntroduceInstabilityByIgnoringProtectedModeSettings = true, InitialBrowserUrl = "about:blank", EnableNativeEvents = true }; return new InternetExplorerDriver(Directory.GetCurrentDirectory(), internetExplorerOptions); } private static FirefoxDriver StartFirefox() { var firefoxProfile = new FirefoxProfile { AcceptUntrustedCertificates = true, EnableNativeEvents = true }; return new FirefoxDriver(firefoxProfile); } private static ChromeDriver StartChrome() { var chromeOptions = new ChromeOptions(); var defaultDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\..\Local\Google\Chrome\User Data\Default"; if (Directory.Exists(defaultDataFolder)) { Executor.Try(() => DirectoryExtension.ForceDelete(defaultDataFolder)); } return new ChromeDriver(Directory.GetCurrentDirectory(), chromeOptions); } #endregion } } 

Perhaps it is worth commenting that Settings.Default.Browser is a parameter that is set in the project properties, and Executor.SpinWait is some helper that waits until the condition is met with a timeout and returns true / false. Also there are magic strings, I apologize)

Source: https://habr.com/ru/post/180047/


All Articles