Monday, November 23, 2009

User Extensions with the Selenium Toolkit for .NET

As I mentioned in my last post, new to version 0.81 the Selenium Toolkit for .NET now provides a simple mechanism to add user-defined extensions to Selenium.

Some background

A user-extension for Selenium is a JavaScript file that becomes embedded into Selenium’s Test Runner.  Typically, the script extends Selenium’s core JavaScript to add new commands, but it also can be used to extend existing functionality, or add custom locator strategies.  Both Selenium IDE and RC allow extensions to be added.

For the purposes of this discussion, here’s a crude example of a selenium extension: 
Selenium.prototype.getMyValue = function(locator, text) {
    return locator;
};

The toolkit takes a straight forward approach to including extensions: it combines the files listed in the configuration file (in order of appearance) into a single file and then configures the Selenium RC to use it. 

Incidentally, if you ever need to verify that your extensions were loaded, you can simply view the JavaScript file at this url: http://localhost:4444/selenium-server/core/scripts/user-extensions.js

The ISelenium interface of the Selenium API does not directly expose a mechanism to execute custom commands.  Instead, we need to send our custom command using a command processor (ICommandProcessor), which isn’t exposed by default so a custom implementation of the ISelenium interface is required.  The Selenium documentation provides a pretty good overview of how to do this, and the remainder of this post demonstrates how to integrate this approach with the toolkit.

Create a customized ISelenium

One of the new features added to the toolkit in this release is the ability to supply your own mechanism for instantiating the ISelenium instance. The factory is a basic class with a Create method.  Simply implement the ISeleniumFactoryProvider interface and then wire it up into the configuration settings (see below).  If no setting is provided in the config, a default factory is used.

This example below shows a custom ISeleniumFactoryProvider that creates a customized ISelenium instance that exposes the ICommandProcessor:

namespace Custom
{
    using Selenium;
    using SeleniumToolkit.Core;

    public class SeleniumFactory : ISeleniumFactoryProvider
    {
        public ISelenium Create(string host,
                                int port,
                                string browserProfile,
                                string baseUrl)
         {
             ICommandProcessor processor = new HttpCommandProcessor(host, port, browserProfile, baseUrl);
             return new CustomSelenium(processor);       
         }
    }

    public class CustomSelenium : DefaultSelenium
    {
        public CustomSelenium(ICommandProcessor processor) 
            : base(processor)
        {
            CommandProcessor = processor
        }

        public ICommandProcessor CommmandProcessor
        {
            get;
            protected set;
        }
    }
}

Tweak your Settings

After you’ve compiled your custom factory, you’ll need to reference your JavaScript file in the userExtensions element and specify your custom factory using the factoryType attribute of the Selenium Node.

<Selenium
    factoryType="Custom.SeleniumFactory, CustomProject"
    >
   <userExtensions>
       <add name="example"
            path="myextension.js" />
   </userExtensions>
</Selenium>

Putting it all together

With the configuration settings in place, now all we need to do is cast the Browser.Current instance to our custom type.

namespace Custom.Test
{
    using NUnit.Framework;
    using Selenium;
    using SeleniumToolkit;

    [WebFixture]
    public class Example
    {
        [WebTest]
        public void ShowUsage()
        {
            CustomSelenium browser = Browser.Current as CustomSelenium;

            string[] inputArgs = { "Hello World" };
            string result = browser.CommandProcessor.DoCommand("getMyValue", inputArgs);
            Assert.AreEqual("Hello World", result);
        }
    }
}

Happy coding.

submit to reddit

Thursday, November 19, 2009

Selenium Toolkit for .NET 0.81 Now Available

I’m happy to announce the next release for the Selenium Toolkit for .NET is now available for download.  This release adds minor fixes to the runtime and enhanced configuration support.

New for this release

This release includes several new enhancements:

  • NUnit 2.5.2 Support
  • Custom Browser Profiles and Aliases
  • User Extensions support
  • Proxy Server support

NUnit 2.5.2 Support

This release represents an upgrade for the NUnit addin to latest version NUnit (2.5.2).  NUnit 2.5.2 includes several performance and user interface enhancements which improve the development experience, including data driven tests and source-code browser for exceptions.

As part of a dependency issue with the NUnit framework, addins are specific to the runtime they’re compiled against, so you must have NUnit 2.5.2 installed in order to use the addin.  If you have NUnit 2.4.8, you’ll have to upgrade.  If you haven’t been able to use the toolkit because you weren’t using NUnit 2.4.8, please download and send in some feedback.

Custom Browser Profiles and Aliases

One of the key goals of the toolkit is to minimize duplication and environment specific settings in your tests so that the impact of moving between environments is minimized.  The toolkit now supports the concept of browser aliases where custom profiles can be defined as a lookup table in the configuration settings.

Before:

[WebFixture]
public class ExampleTest
{
    [WebTest(DefaultBrowser=@"*custom \"C:\PathToFireFox\FireFox.exe\" -no-remote -profile \"C:\PathToProfile\"")]
    public void OpenCustomProfile()
    {
        // ....
    }
}

After:

The dependency on the physical folder path can now be externalized to the configuration file, which can be modified to suit each environment without having to alter the tests.

[WebFixture]
public void ExampleWithBrowserAlias
{
    [WebTest(DefaultBrowser="ff-profile-1")]
    public void OpenCustomProfile()
    {
        // ....
    }
}

And the configuration settings....

<configuration>
    <!-- snip -->

    <Selenium
        BrowserUrl="http://www.bryancook.net"
        >
        <browsers>
            <add key="ff-profile-1"
                 value="*custom &quot;C:\FireFoxPath&quot; -no-remote -profile &quot;PathToProfile&quot;"
                />
        </browsers>
    </Selenium>

</configuration>

User Extensions support

Selenium provides an extensibility model that allows you to extend its functionality through custom JavaScript files.  This release provides two key enhancements to enable this functionality:

  • Configuration element that allows you to specify JavaScript files and directories to be concatenated into the user-extensions.js file; and
  • Factory model that allows you to create your own implementations of the ISelenium interface.  A custom implementation allows you to execute your own custom commands, and will likely play an integral role in the WebDriver backed Selenium implementation planned for Selenium 2.0.

Expect a blog post soon that demonstrates this functionality, but in the meantime you can find details on the configuration settings here.

Proxy Server Support

While not as exciting or as interesting as custom user extensions, this release includes some additional configuration settings for users running Selenium-RC against a web-site that is only accessible through a proxy server.  See the configuration settings  for more details.

Download now

Enough already!  Go download the latest release and try it out.  As always, feedback is always welcome.

Happy coding.

submit to reddit

Wednesday, November 11, 2009

Add Syntax Highlighter to Live Writer Templates

Been tweaking my blog template slowly over the past year, and while I’ve got plans to switch to 960.gs format, my most recent change has been how I highlight my code snippets: like everyone else on the planet, I’m now using Alex Gorbatchev’s SyntaxHighlighter in combination with Anthony Bouch’s PreCode.

Up to this point, I’ve been using CSharpFormat with Omar Shahine’s Insert Code plugin.  This solution has worked well for me up to this point, but it’s the features of SyntaxHighlighter (line numbers, collapsible blocks, etc) and the quality of PreCode’s editing features that have made me switch.

The key difference between the two solutions is that CSharpFormat adornes your code with HTML blocks that are immediately visible in Live Writer (and my RSS feed); SyntaxHighlighter highlights your code at runtime using JavaScript.

While I can live without the RSS feed highlighting, I really miss seeing my code highlighted in Live Writer.  After updating my blogger template, I noticed that Live Writer ignores your JavaScript when it updates your editing template.

Fortunately, Live Writer’s editing template is stored locally as HTML, here:

C:\Users\bcook\AppData\Roaming\Windows Live Writer\blogtemplates\<guid>\index.html

Simply open the file in your editor, and paste in your JavaScript:

<!-- syntax highlighter --> 
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shCore.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushCSharp.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushCss.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushJScript.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushXml.js' type='text/javascript'></script> 
<script type='text/javascript'> 
  SyntaxHighlighter.config.bloggerMode = true;
  SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf';
  SyntaxHighlighter.all();
</script>

Tuesday, November 10, 2009

Implementing a Strategy Pattern using the Unity Framework

My current project is using Unity and has had some interesting challenges to work through.  One of the design challenges we encountered involved several components that were nearly identical in appearance except for a few minor functional details.  We decided to implement a strategy pattern where the variances were different strategies that were applied to common context.

For the sake of argument, let’s say we’re talking about a Financial Calculator that supports different types of financial calculations (FPV, Payment, etc)

public class Calculator : ICalculator
{
    public Calculator(IFormula formula)
    {
	_formula = formula;
    }

    public CalcResult Calculate(CalcArgs input)
    {
        return _formula.Process(input);
    }

    IFormula _formula;
}

public interface IFormula
{
    CalcResult Process(CalcArgs input);
}

public class FutureValue : IFormula
{
    public CalcResult Process(CalcArgs input)
    {
        // ...
    }
}

public class PresentValue: IFormula
{
    public CalcResult Process(CalcArgs input)
    {
        // ...
    }
}

In my last post, I showed how Unity needs some additional configuration in order to resolve ambiguous types – Unit won’t be able to resolve our Calculator unless we specify which IFormula we want to use.  This scenario is a bit different because we want to be able to use both the FutureValue and PresentValue formulas at runtime. 

We have a couple of options to choose from, each with their own pitfalls:

  • Container overloading
  • Named Instances

Container Overloading

At a basic level, we’re limited to registering a type only once per container.  Fortunately, Unity supports the ability to spawn a child container that can used to replace registered types with alternate registrations.  By swapping out our types, we can create alternate runtimes that can be scoped to specific areas of our application.

[TestMethod]
public void CanOverloadContainer()
{
    // create the container and register the
    //    PresentValue formula
    var container = new UnityContainer();
    container.RegisterType<IFormula, PresentValue>();

    // verify we can resolve PresentValue
    var formula1 = container.Resolve<IFormula>();
    Assert.IsInstanceOfType(formula1, typeof(PresentValue));

    // create a child container, and replace
    //    the formula with FutureValue formula
    var childContainer = container.CreateChildContainer();
    childContainer.RegisterType<IFormula, FutureValue>();

    // verify that we resolve the new formula
    var formula2 = childContainer.Resolve<IFormula>();
    Assert.IsInstanceOfType(formula2, typeof(FutureValue));
}

This approach provides a clean separation between the container and the various combinations of our strategy pattern.  If you can compose your application of controllers that can extend and manipulate child containers, this is your best bet as each container provides a small targeted service to the application as a whole.

However, if the variations must live in close contact with one another and you can’t separate them into different containers, you’ll need a different strategy.

Named Instances

Unity provides the ability to register a type more than once, with a caveat that each type is given a unique name within the container.  This feels more like a hack than a best practice, but it provides a simple solution to registering the various combinations of ICalculator types side-by-side.  Since our variations are based on the types passed in through the constructor, we can provide Unity the construction information it needs using InjectionConstructor and ResolvedParameter objects.  To resolve our objects, we must specify the unique name when resolving.

[TestMethod]
public void CanConstructUsingConstructorInfo()
{
    var container = new UnityContainer();

    container.RegisterType<ICalculator, Calculator>("FutureValue",
                            new InjectionConstructor(new ResolvedParameter<FutureValue>())
                            );

    container.RegisterType<ICalculator, Calculator>("PresentValue",
                            new InjectionConstructor(new ResolvedParameter<PresentValue>())
                            );

    var calc1 = container.Resolve<ICalculator>("FutureValue");
    var calc2 = container.Resolve<ICalculator>("PresentValue");
}

At this point, I need to step aside and point out that there is a potential problem with this approach.  We’ve created a mechanism that allows our type to be easily resolved directly from the container using it’s unique name.  There is temptation to pass the container into our code and resolve these objects by name.  This is a slippery slope that will quickly tie your application code and tests directly to Unity.  I will blog more about this in an upcoming post, but here are some better alternatives:

Resolved Parameters

Rather than manually resolving the named instance from the container, configure the container to use your named instance:

public class Example
{
    public Example(ICalculator calculator)
    {
        Calculator = calculator;
    }

    public ICalculator Calculator
    {
        get;
        set;
    }
}

[TestClass]
public class ExampleTest
{
    [TestMethod]
    public void ConfigureExampleForNamedInstance()
    {
        var container = new UnityContainer();
        container.RegisterType<ICalculator, Calculator>("FutureValue",
                                    new InjectionConstructor(
                                            new ResolvedParameter<FutureValue>())
                                    );

        container.RegisterType<Example>(
                                    new InjectionConstructor(
                                            new ResolvedParameter<ICalculator>("FutureValue"))
                                    );

        Example ex = container.Resolve<Example>();
    }
}
Dependency Attributes

Unity supports special attributes that can be applied to your code to provide configuration guidance.  This can make instrumenting your code much easier, but it has a downside of brining the dependency injection framework into your code.  This isn’t necessarily the end of the world, but can limit us if we want to reuse this class with a different dependency or overload it in another container.

public class Example
{
    public Example(
                [Dependency("FutureValue")]
                ICalculator calculator
                  )
    {
        Calculator = calculator;
    }

    public ICalculator Calculator
    {
        get;
        set;
    }
}

Alternatively, the DependencyAttribute can be applied to Properties as well for Setter injection.  Personally, I find this reads better than using attributes in the constructor, and I’ll save my points about Setter injection for another post.

public class Example
{
    [Dependency("FutureValue")]
    public ICalculator Calculator
    {
        get; set;
    }
}

Conclusion

Although inversion of control promotes use of interfaces to decouple our implementations, we often use abstract classes and composition to construct our objects.  In the case of composition, we need to provide Unity with the appropriate information to construct our objects.  Wherever possible, we should defer construction logic to configuration settings rather than instrumenting the code with container information.

submit to reddit

Monday, November 09, 2009

Simple Dependency Injection using the Unity Framework

My current project is using Unity as an Inversion of Control / Dependency Injection framework.  We’ve had a few challenges and lessons learned while using it.  This is my first post on the topic, and I want to provide a quick look:

Unity is slightly different than most dependency injection frameworks that I’ve seen.  Most dependency injection frameworks, such as Spring.NET (when I last used it), require you to explicitly define the dependencies for your objects in configuration files.  Unity also uses configuration files, but it also can construct any object at runtime by examining its constructor.

Let’s take a simple example where I have a product catalog service that provides simple searching for products by category.  The service is backed by a simple and crude ProductRepository object.

public class ProductCatalog
{
    public ProductCatalog(ProductRepository repository)
    {
        _repository = repository;
    }

    public List<Product> GetProductsByCategory(string category)
    {
        return _repository.GetAll()
                          .Where(p => p.Category == category)
                          .ToList();
    }

    private ProductRepository _repository;
}

public class ProductRepository
{
    public ProductRepository()
    {
        _products = new List<Product>()
            {
            new Product() { Id = "1", Name = "Snuggie", Category = "Seen on TV" },
            new Product() { Id = "2", Name = "Slap Chop", Category = "Seen on TV" }
            };
    }

    public virtual List<Product> GetAll()
    {
        return _products;
    }

    private List<Product> _products;
}

public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
}

With no configuration whatsoever, I can query Unity to resolve my ProductCatalog in a single line of code.  Unity will inspect the constructor of the ProductCatalog and discover that it is dependent on the ProductRepository.  Since the ProductRepository does not require any additional dependencies in its constructor, Unity will construct the repository and assign it to the catalog for me.

[Test]
public void CanResolveWithoutConfiguration()
{
    var container = new Microsoft.Practices.Unity.UnityContainer();

    var catalog = container.Resolve<ProductCatalog>();

    var products = catalog.GetProductsByCategory("Seen on TV");

    Assert.AreEqual(2, products.Count);
}

Aside from the fact that this is a crude example, a production system would be extremely limited because the product catalog is tightly coupled to our repository implementation.  Although we could subclass the product repository, a better solution would decouple the two classes by introducing an interface for the product repository.

public interface IProductRepository
{
    List<Product> GetAll();
}

public class ProductRepository : IProductRepository
{
    // ...
}

public class ProductCatalog
{
    public ProductCatalog(IProductRepository repository)
    {
        // ...
    }

    // ...
}

This is a much more ideal solution as our components are now loosely coupled, but Unity no longer has enough information to automatically resolve the ProductCatalog’s dependencies.  To fix this issue, we need to provide this information to the Unity container.  This can be done through configuration files, or by manipulating the container directly:

[Test]
public void CanResolveWithRegisteredType()
{
    var container = new Microsoft.Practices.Unity.UnityContainer();
    
    container.RegisterType<IProductRepository, ProductRepository>();

    var catalog = container.Resolve<ProductCatalog>();

    var products = catalog.GetProductsByCategory("Seen on TV");

    Assert.AreEqual(2, products.Count);
}

Note that while I’m using the Unity container in my tests, it's completely unnecessary. I can simply mock out my dependencies (IProductRepository), pass them in, and test normally.

Conclusion

This demonstrates how Unity is able to resolve simple types without extensive configuration.  By designing our objects to have their dependencies passed in they possess no knowledge of the dependency injection framework, making them lean, more portable and easy to test.

submit to reddit