Getting Started with Selenium 0

The past few days have been spent getting Selenium setup and running as part of our CI builds. We only have a few proof-of-concept tests right now, but the power and potential is apparent. We have no automated unit testing right now and very little code in our code behinds so functional testing is as good as we’re going to get. Also, with the amount of AJAX that is currently in our pages, and the additional amount we see in them in the near future, Selenium’s method of control the browser helps us make sure our pages do and continue to behave like we expect.

Getting setup with Selenium was incredibly simple. The Selenium IDE Firefox plugin makes creating your first Selenium test a snap. Download it and install it and you’re off. I’m not going to walk you through creating the tests, because the Selenium web site has a pretty decent movie that’ll take care of you.

The output of the test recorder are HTML files that contain the instructions, aka “Selenese”, to re-execute the tests through both the IDE and Selenium core. Selenese is very simple by design. While we could run the Selenese tests through the core in our Continuous Integration server, I’ve decided to use the IDE to export the C# source for the tests I create. This allows my to put the Selenium test into an NUnit test harness, refactor some of the common setup and config, and also run the tests via Selenium Remote Control(RC). I know the refactoring goes against the Selenese simplicity, but I want to run my tests locally and with different credentials without changing every test. Also, running in RC lets me run the tests without having to watch the pages in the browser fly by and, someone day, concurrently run all the browsers I care about.

Here’s an example of what one of those tests might look like 

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using Selenium;

namespace SeleniumTests{

   [TestFixture] public class NewTest {
	private ISelenium selenium;
	private StringBuilder verificationErrors;

	[SetUp] public void SetupTest() {
		selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.google.com/");
		selenium.Start();
		verificationErrors = new StringBuilder();
	}

	[TearDown] public void TeardownTest() {
		try {
			selenium.Stop();
		} catch (Exception) {
			// Ignore errors if unable to close the browser
		}
		Assert.AreEqual("", verificationErrors.ToString());
	}

	[Test] public void TheNewTest() {
		selenium.Open("/");
		selenium.Type("q", "fooberry");
		selenium.Click("btnG");
		selenium.WaitForPageToLoad("30000");
	      Assert.IsTrue(selenium.IsElementPresent("css=a[href=\"http://www.fooberry.com/\"]"));
	}
   }
}

Getting this to run in the Team Build is as easy as getting the regular NUnit tests running. First we would want to parameterize those tests a bit so we can pass different hosts, ports and credentials (if present). That’s not too hard and should be obvious.

We’re trying multiple CI builds. One build just compiles and runs the unit test code, which is currently this single test….baby steps.

[TestFixture] public class TheMostAwesomestUnitTestInTheWorld {
    [Test] public void ValidateOurCoreBeliefs() {
        Assert.That(true, Is.True);
    }
}

The other build compiles and runs both the unit tests and integration tests. We suspect this build will take a while and the sooner we could get feedback about the quality of the build, the better. We could push this build to a separate build agent too, but for right now they are all just backing up in the same queue.

The only missing piece of the puzzle so far is the Remote Control Server. The RC Server is a Java application that has to run on a machine with access to which ever browser you plan to test. Starting the server is simple enough. Just make sure Firefox.exe is in the path. If you forget, you’ll get a nice warning about it.

java -jar selenium-server.jar

It’s up an running and when you run the above unit test, you see the browser window fly by and the server log all the actions it’s performing on the browser.

Great! …if you want to stay logged into your server with the console open, but I didn’t. Luckily, creating a Windows service is pretty easy. There is a great tutorial out there that walks you through how to setup a similar Java application as a service. Just substitute the Selenium RC Server for the FitNesse server. Note that when I tried to install the Windows Server 2003 Resource Kit, on both Vista and Windows Server 2008, I got a compatibility warning. I ignored the warning since I was only using the two files and it worked great.

Now you can start and stop the Selenium RC Server via a Windows service, keep it running when you log out and start automatically when the server starts up.

Have fun.

Automating the Build (Step 1 cont’d) 1

After the disappointing ending to my previous post, I now have much success to report. Once we had the correct path to the MSTest.exe on the build server, I was able to publish the results of my NUnit tests. There are a few things to note.

  1. You still need MSTest.exe on the build server. I guess that is OK since we, at our organization, want to allow for the ability to run MSTests as well. I’m not 100% sure that happens on the build server or the TFS server.
  2. As of now, if the NUnit tests fail, it will not run the MSTest. This is because we are executing the NUnit tests in the AfterCompile target as suggested in the NUnit for Team Build example. I’m not really sure why you would do both in the same solution, but if you do, you won’t see failures from both. Only one at a time. I’m looking into getting both to run, but that isn’t going to be much of a priority since we won’t need to run both in the same solution.

I am really excited that we have this running with such little effort. Thanks has to go to the NUnit for Team Build guys.

One to step two when time allows.

Automating the Build (Step 1) 2

We are starting to automate and standardize our build process. I think the idea that F5 is not a a build strategy is finally surfacing as a real problem. The first step in my mind is to come to some convention on the structure. Doing so would make configuration a lot simpler. We can default the convention and you can overwrite if you feel the need.

Microsoft has some guidance on the subject of how to structure the source when using TFS. I’m not really sure how the choice of source control factors into that decision, but we’ll just go with it. The structure I’m playing with now is very similar to their recommendation.

/Fooberry/
          1.0.0/  <-- the build file goes here
                docs/
                source/
                       application/ <-- the source for the ui
                       application.tests/ <-- the UI tests
                       core/
                       core.tests/
                       ...I'm not settled on how this level
                          will look. It isn't important for
                          now. I'm more concerned with the
                          files needed to build.
                libs/
                    my.company.build/
                    msbuild.community.tasks/
                    nunit/
                    nxslt/
                    nunit4teambuild/
                    n*...all shared libs and tools
               ...maybe some other dirs here eventually
          main/ <-- the trunk copy just like the 1.0.0 tree
/SomeOtherApp/

The main point here is that all the tools we use are inside the source control for every app and every branch of that app. It may seem like a waste of disk space, but what it allows is all configuration information to be relative to the build root. A specific branch can upgrade to a new NUnit and all the other builds don’t need to worry about backwards computability.

A folder that may look a little odd is my.company.build. I would like this folder to hold as much of the automated build extensions as possible. There are going to be a few additional steps that we need to add to the out of the box TFSBuild.proj. The plan is to put all the new targets in a my.company.build.targets file along with any custom tasks that we need to build. Once we have that, we can stick the following line into the TFSBuild.proj and we snap on all our custom steps.

<Import Project="$(SolutionRoot)\libs\my.company\my.company.build.targets"/>

Getting the import setup was a little bit of pain. Running locally, $(SolutionRoot) doesn’t map to the correct path. The path to the targets file was mapping someplace crazy. This has a really bad smell, but I was overjoyed that it worked remotely, so I didn’t care too much for now. It’s only day one. We will need to build locally eventually. That’s on the TODO list already.

I have a bit of a confession. I wish that was the manner in which I started this process, but I didn’t realize that we could externalize the build steps to my.company.build until after I started filling out the steps. This is is how, in my opinion, frameworks are most successfully built. We extract the code that could be made common instead of head out to write something that will solve everyone’s problem, even though you don’t know what their problem might be.

So to start on the first build step; running NUnit tests. After a quick Google search,
Nunit4TeamBuild on CodePlex outlined the steps we needed to take.

  1. Run Nunit-console and produce an XML log file
  2. Convert the Nunit XML output to an MSTest test results file (with a .trx extension)
  3. Use MSTest /publish to push merge the trx file with an existing build

Sounds pretty straight forward. There are a few more dependancies. It uses the MSBuild Community Tasks and nxslt2 (There is a new nxslt3 which uses .Net 3.5…not sure what that gains us though).

The documentation for Nunit4TeamBuild recommends adding an AfterCompile target to execute the NUnit tests. We can put this in our my.company.build.targets file. There are just a few housekeeping items first. The example proj file has hard coded paths to the MSBuild Commnuity Tasks, NUnit and NXslt. To make those relative, assign the….

<PropertyGroup>
   <MSBuildCommunityTasksPath>$(SolutionRoot)\libs\community.msbuild.tasks\</MSBuildCommunityTasksPath>
   <NUnitPath>$(SolutionRoot)\libs\nunit\</NUnitPath>
</PropertyGroup>

<Import Project="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.Targets"/>

When we go to invoke the NUnit task, we need to be sure and give the ToolPath of $(NUnitPath).

<NUnit ContinueOnError   = "true'
        Assemblies       = "@(TestAssemblies)"
        OutputXmlFile    = "$(OutDir)nunit_results.xml"
        ToolPath         = "$(NUnitPath)">
   <Output TaskParameter = "ExitCode"
           PropertyName  = "NUnitResult" />
 </NUnit>

*Note: I’m playing with the formatting of the XML. I’m trying out this style for now.

So that takes care of the NUnit and the MSBuild Community Tasks. The next tool that needs a relative path is NXslt. The example project shows invoking the command line executable via the Exec task.

<Exec Command="C:\path\to\nxslt\nxslt2.exe &quot;$(OutDir)nunit_results.xml&quot; &quot;$(SolutionRoot)\nunit transform.xslt&quot; -o &quot;$(OutDir)nunit_results.trx&quot;"/>

While that works, NXslt comes bundled with an MSBuild task that can replace it with something more elegant. To use the task, add the Using

 <UsingTask AssemblyFile = "$(NXsltTaskAssembly)"
            TaskName     = "Nxslt" />

And replace that Exec with the following:

<Nxslt In    = "$(OutDir)nunit_results.xml"
         Style = "$(SolutionRoot)\libs\nunit4teambuild\nunit transform.xslt"
         Out   = "$(OutDir)nunit_results.trx" />

One more to go. MSTest.exe is invoked to publish the newly formatted results. This one might be more difficult to keep relative. Right now, this is pointing (or trying to point) to the MSTest.exe under Program Files. With all that said, I’m unable to find where MSTest is on the build server. Having no access to it makes it a little difficult. Unfortunately I cannot guarantee that the final step will actually work. I hope to have more news to report next week.