Getting started with IronPython – Part 3: unit testing

Welcome to the 3rd part of my quest to learn IronPython. In this part I’ll show how I’ve unit tested my application.

Previous parts of this series:

  1. Where to start – resources, environment and how I’ve started learning IronPython
  2. Let’s write some code – the project I’m writing along with my impressions of how things done

 

Being a TDD’er (Test Driven Developer) one of the first things I’ve searched from when I’ve started learning IronPython is unit testing framework, luckily for me I didn’t need to search too long.

magnifying glass - Dr. Pat

PyUnit – Python unit testing framework

IronPython has a good unit testing framework inherited from Python called PyUnit.

Writing unit tests using PyUnit is simple:

  1. import unittest class
  2. Create a class that inherits unittest.TestCase (test fixture)
  3. Write test methods using assertions methods

The following example is my first test in IronPython – check that the newly created board has two stores:

image

Because we’re using an open source dynamic language we have the source code for everything! Browsing the unittest.py file I found something interesting about the way assertEqual was implemented:

image

It seems the actual implementation is at the failUnlessEqual method:

image 

Likewise most of the asserts actual implementation is not the assert method but the failUnless method, in fact I could have written the test above this way:

image

Like other unit testing frameworks there is setUp and tearDown methods as well:

image

I especially like the way asserting exception was thrown is done. IronPython has an assertRaises/failUnlessRaises method to check that if a specific code snippets throws exception.

Running unit tests

Writing unit tests is only half of the fun - we need to be able to run them as well.

If all of the tests are located in the same file just add this code snippet at end of the file:

image

When passing the test file as argument to ipy.exe all of the tests inside that file will be run:

image

A successful run will look like this:

image

If your unit tests are divided between several files you can use test suites. Read more about it in Python unit testing framework documentation.

Unit testing alternatives

While learning about PyUnit I came across other alternatives for IronPython test automation:

  1. Alex Henderson (Bitter Coder) has written a framework that enables writing unit tests in IronPython and running them using NUnit. you can read about it in his blog.
  2. python-nose - nose provides an alternate test discovery and running process for unittest. Should make writing and running unit tests easier.

 

What’s next?

My unit tests are available for download here, as always I would appreciate feedback (either comments or email).

 

We’re almost there - in the post in this series I plan to explain the Minimax algorithm and its implementation.

Labels: