Thursday, 9 December 2010

Test Driven Development and XML

Test Driven Development (TDD) is a way of writing code that says "first write the test, then make your code pass the test". It's useful for generating reliable code, since you build a library of regression tests as you go. The test cases also serve as documentation and examples of how to use the software.

I'm something of a TDD fan, so I've been using it with the Lua scripts for Clonemaster. For instance, a simple test for the classes I've been specifying looks like this:


function test_single_snippet()
        --
        -- UML to describe the scene
        --
        local scene = [[
        <scene Name="hello">
         <narrative Name="hello_world">
          <snippet>
           Hello, World.
          </snippet>
         </narrative>
        </scene>
        ]]

        --
        -- load the scene into a Narrative object
        --
        local narrator = Narrator:new()
        narrator:load(scene)

        --
        -- Just one narrative in the scene
        -- They should not be null. Anything else should be
        --
        assert(narrator.scene ~= nil)
        assert(narrator.scene.narratives.hello_world ~= nil)
        assert(narrator.scene.narratives.doesnt_exist == nil)

        --
        -- create a test interface for the narrative,
        -- and then press play.
        --
        -- play() will run the scene forward to the first
        -- cut or choice, and then return. If there's more to do,
        -- play() will return true false otherwise.
        --
        -- In this case there should be more to do
        --
        stage = TestStage:new()
        rc = narrator:play(stage)

        --
        -- We expect play() to return false here,
        -- because there is nothing else to do
        --
        assert_false(rc)
end

So, when I run that, all the assertions have to be true and none of the methods called can raise errors if the test is to pass. And that simple test manages to test that the XML scene definition is parsed without raising errors; that the scene creates its narratives correctly, that the play method works for simple cases and that we can detect the end of a scene correctly.

There are test cases for all the other narrative items as well. I won't publish them here, but you can look at them in svn: svn://pinkpetal.co.cc:3693/whm_svn/branches/clonemaster/Resources/Tests

There are a pile of other test files in there too, for other classes which I'll get to as they become relevant. So far we've hardly scratched the surface.

No comments: