Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Test URL Redirects with WebDriver and HttpWebRequest

5.00/5 (3 votes)
21 Jun 2015Ms-PL3 min read 24.9K  
Explains in detail how to test URL redirects. Test URL Redirects directly in browsers via WebDriver and browserless via HttpWebRequests.

Introduction

If you are involved in web development, you most probably need to sometimes create redirects from one page to another. Thus, you need to test URL redirects. Usually, it is OK to check them only once when they are created. However, the best practice is to create an automation regression validation engine - for example via integration tests. In this publication, I will show you how to test URL redirects via WebDriver and HttpWebRequests. The redirects checker engine will use Strategy Design Pattern, which will make the change of the validation algorithm easier without changing the core.

Image 1

Test URL Redirects Configuration

I believe that the most straightforward way to configure redirects is via XML configuration.

XML
<?xml version="1.0" encoding="utf-8" ?>
<sites>
  <site url="http://automatetheplanet.com/" name="AutomateThePlanet">
    <redirects>
      <redirect from=
      "http://automatetheplanet.com/singleton-design-pattern-design-patterns-in-automation-testing/" 
      to="/singleton-design-pattern/" />
      <redirect from="/advanced-strategy-design-pattern-design-patterns-in-automation-testing/" 
      to="/advanced-strategy-design-pattern/" />
    </redirects>
  </site>
</sites>

In the above sample configuration, you can test more than one site. Under its node are placed the different redirects rules- the source page (from URL) and destination page (to URL). The engine supports partial and full URLs.

There are four classes to which the above configuration is deserialized once it is read.

C#
[XmlRoot(ElementName = "sites")]
public class Sites
{
    [XmlElement(ElementName = "site")]
    public List<Site> Site { get; set; }
}

[XmlRoot(ElementName = "site")]
public class Site
{
    [XmlElement(ElementName = "redirects")]
    public Redirects Redirects { get; set; }

    [XmlAttribute(AttributeName = "url")]
    public string Url { get; set; }

    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName = "redirects")]
public class Redirects
{
    [XmlElement(ElementName = "redirect")]
    public List<Redirect> Redirect { get; set; }
}

[XmlRoot(ElementName = "redirect")]
public class Redirect
{
    [XmlAttribute(AttributeName = "from")]
    public string From { get; set; }

    [XmlAttribute(AttributeName = "to")]
    public string To { get; set; }
}

Test URL Redirects Service

The main class that is used to test URL redirects is the RedirectService. It accepts IRedirectStrategy, which defines the base redirect engine algorithm methods.

C#
public class RedirectService : IDisposable
{
    readonly IRedirectStrategy redirectEngine;
    private Sites sites;

    public RedirectService(IRedirectStrategy redirectEngine)
    {
        this.redirectEngine = redirectEngine;
        this.redirectEngine.Initialize();
        this.InitializeRedirectUrls();
    }

    public void TestRedirects()
    {
        bool shouldFail = false;

        foreach (var currentSite in this.sites.Site)
        {
            Uri baseUri = new Uri(currentSite.Url);

            foreach (var currentRedirect in currentSite.Redirects.Redirect)
            {
                Uri currentFromUrl = new Uri(baseUri, currentRedirect.From);
                Uri currentToUrl = new Uri(baseUri, currentRedirect.To);

                string currentSitesUrl = 
                   this.redirectEngine.NavigateToFromUrl(currentFromUrl.AbsoluteUri);
                try
                {
                    Assert.AreEqual<string>(currentToUrl.AbsoluteUri, currentSitesUrl);
                    Console.WriteLine(string.Format("{0} \n OK", currentFromUrl));
                }
                catch (Exception)
                {
                    shouldFail = true;
                    Console.WriteLine(string.Format
                    ("{0} \n was NOT redirected to \n {1}", currentFromUrl, currentToUrl));
                }
            }
        }
        if (shouldFail)
        {
            throw new Exception("There were incorrect redirects!");
        }
    }

    public void Dispose()
    {
        redirectEngine.Dispose();
    }

    private void InitializeRedirectUrls()
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(Sites));
        TextReader reader = new StreamReader(@"redirect-URLs.xml");
        this.sites = (Sites)deserializer.Deserialize(reader);
        reader.Close();
    }
}

The InitializeRedirectUrls transforms the previously mentioned XML configuration to the shown C# classes. The primary method of the service - TestRedirects is used to test URL redirects calling the NavigateToFromUrl engine’s function that returns the destination URL. After that, the service compares the setup target URL and the output one. It is repeated for all URLs from the XML configuration. If there are any mismatches, an exception is thrown. The RedirectsService should be called wrapped in using statement in order for the engine to be able to be disposed.

The interface of the strategy design pattern contains of only three methods.

C#
public interface IRedirectStrategy : IDisposable
{
    void Initialize();

    string NavigateToFromUrl(string fromUrl);

    void Dispose();
}

Image 2

Test URL Redirects via WebDriver

The first implementation of the redirects strategy uses WebDriver test framework.

C#
public class WebDriverRedirectStrategy : IRedirectStrategy
{
    private IWebDriver driver;

    public void Initialize()
    {
        this.driver = new FirefoxDriver();
    }

    public void Dispose()
    {
        this.driver.Quit();
    }

    public string NavigateToFromUrl(string fromUrl)
    {
        this.driver.Navigate().GoToUrl(fromUrl);
        string currentSitesUrl = this.driver.Url;

        return currentSitesUrl;
    }
}

The strategy can be extended to specify a different browser, however for the example, I’m using Firefox. In the Initialize method, a new driver instance is created and disposed in the Dispose method. The core method navigates to the configured URL, and when the page is completely loaded, it saves the destination URL and returns it.

Image 3

Test URL Redirects via HttpWebRequest

The fastest way to test HTTP redirects is via HttpWebRequest C# class.

C#
public class WebRequestRedirectStrategy : IRedirectStrategy
{
    public void Initialize()
    {
    }

    public string NavigateToFromUrl(string fromUrl)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(fromUrl);
        request.Method = "HEAD";
        request.Timeout = (int)TimeSpan.FromHours(1).TotalMilliseconds;
        string currentSitesUrl = string.Empty;
        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                currentSitesUrl = response.ResponseUri.ToString();
            }
        }
        catch (WebException)
        {
            currentSitesUrl = null;
        }

        return currentSitesUrl;
    }
    public void Dispose()
    {
    }
}

A simple HTTP HEAD request is created, and when its response is returned, the destination URL is extracted from it. There is no need to initialize or dispose anything in this method.

Test URL Redirects Usage in Integration Tests

C#
[TestClass]
public class RedirectsTester
{
    [TestMethod]
    public void TestRedirects()
    {
        var redirectService = new RedirectService(new WebRequestRedirectStrategy());
        using (redirectService)
        {
            redirectService.TestRedirects();
        }
    }
}

If you need to change the redirects engine implementation, pass the another implementation to the constructor of the RedirectService.

So Far in the 'Pragmatic Automation with WebDriver' Series

If you enjoy my publications, feel free to SUBSCRIBE
Also, hit these share buttons. Thank you!

Source Code

The post Test URL Redirects with WebDriver and HttpWebRequest appeared first on Automate The Planet.

License

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