Click here to Skip to main content
13,901,221 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4.6K views
3 bookmarked
Posted 12 Jun 2016
Licenced Ms-PL

7 Enhanced Browser Automation Tricks You Need to Know- Testing Framework

, 12 Jun 2016
Rate this:
Please Sign up or sign in to vote.
Learn how to control browser to the maximum extent with various techniques. Handle multiple browser instances. Intercept raw HTTP traffic and assert requests and responses. Download files with a single line of code.

Introduction

One of the common things between the fast and maintainable UI tests is the know-how of the automation engineer to use the automation framework correctly. A large part of it is how to handle the different browsers properly in various situations. In this article, part of the Testing Framework Series, I am going to share with you a couple of compelling features of this framework.

Browser Automation Tricks

1. Handle Logon Dialogs

Logon Dialog

Usually, it is not so trivial to automate similar to the above dialog. Through Testing Framework, you only need to add a LogonDialog instance to DialogMonitor via the AddDialog method. In the constructor of LogonDialog, specify the exact username and password. Then, you need only to navigate to the desired protected page. Also, you need to add a using statement to ArtOfTest.WebAii.Win32.Dialogs.

[TestMethod]
public void LogonDialog()
{
    // add using to ArtOfTest.WebAii.Win32.Dialogs
    manager.DialogMonitor.AddDialog(
    new LogonDialog(manager.ActiveBrowser, "<username>", "<password>", DialogButton.OK));
    manager.DialogMonitor.Start();

    // Navigate to a page that need a logon
    manager.ActiveBrowser.NavigateTo("<Exchange with the URL to LogOn>");
}

Official Documentation

2. Http Proxy- Intercept RAW HTTP Traffic

Testing Framework includes the ArtOfTest.WebAii.Messaging.Http namespace. With it, you have the ability to intercept raw HTTP traffic under the cover. Using the HTTP proxy, you can intercept an HTTP request originating from the browser before it is sent to the web server and/or intercept HTTP responses coming from the web server just before they reach the browser and are rendered by it.

[TestInitialize]
public void TestInitialize()
{
    Settings mySettings = new Settings();
    mySettings.Web.DefaultBrowser = BrowserType.FireFox;
    mySettings.Web.UseHttpProxy = true;
    manager = new Manager(mySettings);
    manager.Settings.Web.RecycleBrowser = true;
    manager.Settings.Web.KillBrowserProcessOnClose = true;
    manager.Settings.AnnotateExecution = true;
    manager.Start();
    manager.LaunchNewBrowser();        
}

It is important to set the property UseHttpProxy to true, you can do it via code as shown above. Or you can configure it directly in your app.config.

<configuration>
  <configSections>
    <section name="WebAii.Settings" 

    type="ArtOfTest.WebAii.Core.SettingsConfigSectionHandler,ArtOfTest.WebAii"/>
    <section name="WebAii.Settings.Web" 

    type="ArtOfTest.WebAii.Core.WebSettingsConfigSectionHandler,ArtOfTest.WebAii"/>
    <section type="ArtOfTest.WebAii.Core.WpfSettingsConfigSectionHandler,ArtOfTest.WebAii"

    name="WebAii.Settings.Wpf"/>
  </configSections>
  <WebAii.Settings

                logLocation="F:\Log\"

                executionTimeout="30000"

                clientReadyTimeout="20000"

                queryEventLogErrorsOnExit="false"

                executionDelay="0"

                annotateExecution="true"

                annotationMode="All"

                logAnnotations="false"

                waitCheckInterval="633"

                createLogFile="true"

                Manager.Settings.Web.UseHttpProxy="true">
  </WebAii.Settings>
  <WebAii.Settings.Web baseUrl="http://automatetheplanet.com">
  </WebAii.Settings.Web>
</configuration>

You need to add Manager.Settings.Web.UseHttpProxy="true" to WebAii.Settings section.

[TestMethod]
public void InterceptRawHttpTraffic()
{
    ResponseListenerInfo responseListner = 
    new ResponseListenerInfo(AssertJavaScriptIsGZiped);
    manager.Http.AddBeforeResponseListener(responseListner);

    manager.ActiveBrowser.NavigateTo(
        "http://automatetheplanet.com/healthy-diet-menu-generator/");

    manager.Http.RemoveBeforeResponseListener(responseListner);
}

private void AssertJavaScriptIsGZiped(object sender, HttpResponseEventArgs e)
{
    Debug.WriteLine(String.Format("Request for {0}", e.Response.Request.RequestUri));
    if (e.Response.Headers["Content-Type"] != null &&
    e.Response.Headers["Content-Type"].Equals("application/javascript"))
    {
        Assert.AreEqual("gzip", e.Response.Headers["Content-Encoding"]);
    }
}

First, you need to create a response listener and pass to it the method that will assert the responses. In our case, I created logic to assert that every JavaScript file is GZiped. After that, you need to associate the created listener with the current Testing Framework manager via the AddBeforeResponseListener method. When you navigate to the desired URL, your handler method will be called for every request. Finally, you need to remove the listener.

Official Documentation

3. Browser History

[TestMethod]
public void BrowserHistory()
{
    manager.ActiveBrowser.NavigateTo(
        "http://automatetheplanet.com/healthy-diet-menu-generator/");
    manager.ActiveBrowser.Refresh();

    Assert.AreEqual(
        "Healthy Diet Menu Generator - Automate The Planet",
        manager.ActiveBrowser.PageTitle);

    manager.ActiveBrowser.NavigateTo(
        "http://automatetheplanet.com/");
    manager.ActiveBrowser.GoBack();

    Assert.AreEqual(
        "Healthy Diet Menu Generator - Automate The Planet",
        manager.ActiveBrowser.PageTitle);

    manager.ActiveBrowser.GoForward();

    Assert.AreEqual(
        "Automate The Planet",
        manager.ActiveBrowser.PageTitle);
}

Before you can work with the cookies of a site, you need to navigate to some of its pages. To work with cookies, you use the Cookies property of the current active browser instance.ActiveBrowser property has handy methods for going forward and backwards. Also, you can refresh the page. You can get the current page's title through the PageTitle property.

Official Documentation

4. Manage Cookies

Set New Cookie

var newCookie = new System.Net.Cookie(
"AutomateThePlanet", 
"Rocks", 
"/",
"http://automatetheplanet.com");
manager.ActiveBrowser.Cookies.SetCookie(newCookie);

Get All Cookies

System.Net.CookieCollection siteCookies =
    manager.ActiveBrowser.Cookies.GetCookies("http://automatetheplanet.com");

Delete Cookie

manager.ActiveBrowser.Cookies.DeleteCookie(newCookie);

Purge All Cookies

foreach (System.Net.Cookie cookie in siteCookies)
{
    manager.ActiveBrowser.Cookies.DeleteCookie(cookie);
}

Official Documentation

5. Scroll to Visible

[TestMethod]
public void ScrollToVisible()
{
    manager.ActiveBrowser.NavigateTo(
        "http://automatetheplanet.com/healthy-diet-menu-generator/");
    HtmlInputRadioButton coffeeRadioButton = 
        manager.ActiveBrowser.Find.ByExpression<htmlinputradiobutton>("value=^1 x Trenta");
    coffeeRadioButton.ScrollToVisible(ScrollToVisibleType.ElementTopAtWindowTop);
}</htmlinputradiobutton>

Scroll to visible is a straightforward operation with Testing Framework. You only need to call the ScrollToVisible method of the found element. You have two options- the element to be visible on the top of the screen or the bottom.

Official Documentation

6. Multi-Browser Instance Support

You can create as many browser instances as you want. I am not sure that it is the best practice to do it often but in some rare cases, you might need just that. Once you got the browser instance, you can set focus on it and perform separate actions from all other instances. You start a new browser instance via the LaunchNewBrowser method where you can specify the type of the browser. Through the Browsers collection of the Manager, you can access all active instances.

[TestMethod]
public void MultiBrowserInstanceSuppprt()
{
    Browser firefox = manager.ActiveBrowser;
    manager.ActiveBrowser.NavigateTo(
        "http://automatetheplanet.com/healthy-diet-menu-generator/");
            
    manager.LaunchNewBrowser(BrowserType.InternetExplorer, true);            
    Browser internetExplorer = manager.ActiveBrowser;
    internetExplorer.NavigateTo(
        "http://automatetheplanet.com/healthy-diet-menu-generator/");
            
    HtmlInputRadioButton coffeeRadioButton = 
    firefox.Find.ByExpression<HtmlInputRadioButton>("value=^1 x Trenta");
    coffeeRadioButton.ScrollToVisible(ScrollToVisibleType.ElementTopAtWindowTop);
            
    Browser firefox2 = manager.Browsers[0];
    firefox2.Window.SetFocus();

    internetExplorer.Window.SetFocus();

    firefox.Close(40);
}

Official Documentation

7. Download Files

Download of files with Testing Framework is a simple task. You only need to locate the download button's element and call its Download method. Then, configure the settings of the process such as- should perform clicks via mouse, which dialog button to be clicked, download file's location and timeout in milliseconds.

[TestMethod]
public void DownloadFiles()
{
    string fileToDownload =
        System.IO.Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory,
            @"myw3schoolsimage.jpg");
    if (File.Exists(fileToDownload))
    {
        File.Delete(fileToDownload);
    }

    manager.ActiveBrowser.NavigateTo(
        "http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_a_download");
    Browser myFrame = manager.ActiveBrowser.Frames.ById("iframeResult");
    HtmlImage image = myFrame.Find.AllByTagName<HtmlImage>("img")[0];
    image.Download(false, DownloadOption.Save, fileToDownload, 50000);
}

Official Documentation

All images are purchased from DepositPhotos.com and cannot be downloaded and used for free.
License Agreement

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

Share

About the Author

Anton Angelov
CEO Automate The Planet
Bulgaria Bulgaria
Anton Angelov is an IT Consultant and Quality Assurance Architect at Innovative Lab. He is passionate about automation testing and designing test harness and tools, having the best industry development practices in mind. In addition, he is an active blogger and the founder of Automate The Planet. He strives to make the site one of the leading authorities in Automation Testing by presenting compelling articles, inspiring ardent discussions amongst the community. He is also one of the most-rated-answer authors of questions about Test Automation Frameworks (WebDriver) on Stack Overflow.

You may also be interested in...

Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190306.1 | Last Updated 12 Jun 2016
Article Copyright 2016 by Anton Angelov
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid