Code & QA

Setting up Browsers

Setting up environment and browser options via registry adjustments is a very powerful tool but in most cases, you do not need to change settings of your OS or additional third-party applications. Usually, it’s sufficient to set up only the browser you launch for testing. The easiest way to do this is by launching a browser with settings different from the default. It may be done using special classes located in OpenQA.Selenium.IE, OpenQA.Selenium.Firefox and OpenQA.Selenium.Chrome namespaces.

Setting up the Internet Explorer

There is the InternetExplorerOptions class in the OpenQA.Selenium.IE namespace which provides the ability to launch IE browser with desired options. The number of options is a bit limited but it is sufficient for most cases. Here is the full list of all options allowed:

https://selenium.googlecode.com/git/docs/api/dotnet/html/AllMembers_T_Op

enQA_Selenium_IE_InternetExplorerOptions.htm

Example of usage:

App.config

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <configSections>
    <section name="IESettings" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>
  <appSettings>
    <add key="emailTo" value="me@gmail.com;My_collegue@gmail.com;my_boss@gmail.com"/>
    <add key="testSessionName" value="Tested Application build 001"/>
    <add key="browserType" value="Firefox"/>
  </appSettings>
  <IESettings>
    <add key="IgnoreZoomLevel" value="true" />
  </IESettings>
</configuration>

BaseTest.cs

using Logger;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.IO;
using MSTest = Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
  public class BaseTest
  {
    . . .
    IWebDriver SetUpDriverInstance(string browserType)
    {
      switch (browserType)
        {
          case "Firefox":
            return new FirefoxDriver();
          case "Internet Explorer":
            var IEoptions = new InternetExplorerOptions();
            var ieSettings = ConfigurationManager.GetSection("IESettings") as NameValueCollection;
              if (ieSettings != null)
                {
                  IEoptions.IgnoreZoomLevel = ieSettings["IgnoreZoomLevel"].ToString(CultureInfo.InvariantCulture) == "true";
                  IEoptions.IntroduceInstabilityByIgnoringProtectedModeSettings = ieSettings["IntroduceInstabilityByIgnoringProtectedModeSettings"] == "true";
                }
            return new InternetExplorerDriver(IEoptions);
          case "Chrome":
            return new ChromeDriver();
          default:
            Report.AddError(browserType + " web driver instance cannot be initialized. Test will by terminated. Verify configuration parameters.");
            throw new Exception();
      }
    }
  }
. . .

}

In the code above IEoptions.IgnoreZoomLevel property is True because there is the appropriate node in the App.config file –

<add key=”IgnoreZoomLevel” value=”true” /> – and its value is “true”.

Contrariwise IEoptions.IntroduceInstabilityByIgnoringProtectedModeSettings property is False because no corresponding node is found in the App.config since there is no one.

Setting up Google Chrome

For launching the Chrome browser with desired options special command line arguments are used. It means that if the arguments contain an option, the option is True and will be switched on when the browser starts. I have found the list of Chrome browser options with descriptions here.The usage example is listed below.

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="IESettings" type="System.Configuration.NameValueSectionHandler"/>
    <section name="ChromeSettings" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>
  <appSettings>
    <add key="emailTo" value="me@gmail.com;My_collegue@gmail.com;my_boss@gmail.com"/>
    <add key="testSessionName" value="Tested Application build 001"/>
    <add key="browserType" value="Firefox"/>
  </appSettings>
  <IESettings>
    <add key="IgnoreZoomLevel" value="true" />
  </IESettings>
  <ChromeSettings>
    <add key="--start-maximized" value="true" />
  </ChromeSettings>
</configuration>

BaseTest.cs

using Logger;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.IO;
using MSTest = Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
  public class BaseTest
  {

    . . .
    
  IWebDriver SetUpDriverInstance(string browserType)
  {
    switch (browserType)
    {
      case "Firefox":
        return new FirefoxDriver();
      case "Internet Explorer":
        var IEoptions = new InternetExplorerOptions();
        var ieSettings = ConfigurationManager.GetSection("IESettings") as NameValueCollection;
        if (ieSettings != null)
        {
          IEoptions.IgnoreZoomLevel = ieSettings["IgnoreZoomLevel"].ToString(CultureInfo.InvariantCulture) == "true";
          IEoptions.IntroduceInstabilityByIgnoringProtectedModeSettings = ieSettings["IntroduceInstabilityByIgnoringProtectedModeSettings"] == "true";
        }
        return new InternetExplorerDriver(IEoptions);
      case "Chrome":
        var options = new ChromeOptions();
        var chromeSettings = ConfigurationManager.GetSection("ChromeSettings") as NameValueCollection;
        var optionsList = new List<string>();
        if (chromeSettings != null)
          for (var i = 0; i < chromeSettings.Count; i++)
          if(chromeSettings[i] == "true")
          optionsList.Add(chromeSettings.GetKey(i));
          options.AddArguments(optionsList);
        return new ChromeDriver(options);
      default:
        Report.AddError(browserType + " web driver instance cannot be initialized. Test will by terminated. Verify configuration parameters.");
        throw new Exception();
    }
   }
}
. . .
}

Setting up Mozilla Firefox

All the preferences for the Mozilla Firefox browser may be adjusted through FirefoxProfile class located in OpenQA.Selenium.Firefox namespace. This is a very powerful tool which allows you to set up almost everything in the browser – UI, add-ons, behavior, connections, extensions, scripting and many other things. But you should be careful because some of the settings may cause the browser’s crash if incorrect values will be put into.

A very big part of Firefox settings described here. But keep in mind that not all of the features described on the site may be available for your version of the Firefox though the main setting is general for all versions. Personal features of a concrete browser may be seen on its ‘about:config’ page (just type the command in the address bar). The list of settings available for the specific instance of the Firefox browser will be displayed.

clip_image001

To adjust Firefox browser you have to know not only the name and the value of a feature but its type as well. Fortunately, there may be only three kinds of feature types: boolean, integer and string.

I utilized the following approach (maybe not the most elegant) – I wrote all values in App.config file as strings and then parsed the strings inside the code.

App.config:

<appender name="stash" class="ch.qos.logback.core.rolling.RollingFileAppender">
	<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
		<level>info</level>
	</filter>
	<file>provisioning_service.json</file>
	<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
		<fileNamePattern>provisioning_service.json.%d{yyyy-MM}</fileNamePattern>
		<maxHistory>30</maxHistory>
	</rollingPolicy>
	<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
		<providers>
			<timestamp/>
			<loggerName/>
			<logLevel/>
			<stackTrace/>
			<message/>
			<nestedField>
				<fieldName>properties</fieldName>
				<providers>
					<mdc/>
				</providers>
			</nestedField>
			<threadName/>
		</providers>
	</encoder>
</appender>

BaseTest.cs

namespace Tests {
 public class BaseTest { ...
  IWebDriver SetUpDriverInstance(string browserType) {
   switch (browserType) {
    case "Firefox":
     //new instance of browser profile var profile = new FirefoxProfile(); //retrieving settings from config file var firefoxSettings = ConfigurationManager.GetSection("FirefoxSettings") as NameValueCollection; //if there are any settings
     if (firefoxSettings != null)
      //loop through all of them
      for (var i = 0; i < firefoxSettings.Count; i++) //and verify all of them
       switch (firefoxSettings[i]) { //if current settings value is "true"
        case "true":
         profile.SetPreference(firefoxSettings.GetKey(i), true);
         break;
         //if "false"
        case "false":
         profile.SetPreference(firefoxSettings.GetKey(i), false);
         break;
         //otherwise
        default:
         int temp;
         //an attempt to parse current settings value to an integer. Method TryParse returns True if the attempt is successful (the string is integer) or return False (if the string is just a string and cannot be cast to a number) if (Int32.TryParse(firefoxSettings.Get(i), out temp)) profile.SetPreference(firefoxSettings.GetKey(i), temp); else
         profile.SetPreference(firefoxSettings.GetKey(i), firefoxSettings[i]);
         break;
       }
     return new FirefoxDriver(profile);
    case "Internet Explorer":
     var IEoptions = new InternetExplorerOptions();
     var ieSettings = ConfigurationManager.GetSection("IESettings") as NameValueCollection;
     if (ieSettings != null) {
      IEoptions.IgnoreZoomLevel = ieSettings["IgnoreZoomLevel"].ToString(CultureInfo.InvariantCulture) == "true";
      IEoptions.IntroduceInstabilityByIgnoringProtectedModeSettings = ieSettings["IntroduceInstabilityByIgnoringProtectedModeSettings"] == "true";
     }
     return new InternetExplorerDriver(IEoptions);
    case "Chrome":
     var options = new ChromeOptions();
     var chromeSettings = ConfigurationManager.GetSection("ChromeSettings") as NameValueCollection;
     var optionsList = new List < string > ();
     if (chromeSettings != null)
      for (var i = 0; i < chromeSettings.Count; i++)
       if (chromeSettings[i] == "true") optionsList.Add(chromeSettings.GetKey(i));
     options.AddArguments(optionsList);
     return new ChromeDriver(options);
    default:
     Report.AddError(browserType + " web driver instance cannot be initialized. Test will by terminated. Verify configuration parameters.");
     throw new Exception();
   }
  }
 }...
}

Environment adjustments via Registry                 Table Of Content                   Running tests on Android

Leave a Reply

Your email address will not be published. Required fields are marked *


Notice: Undefined offset: 0 in /home/chyqruxavcln/public_html/learnseleniumtesting.com/wp-content/plugins/cardoza-facebook-like-box/cardoza_facebook_like_box.php on line 924