Unit Testing

Friday 16th September 2022

Testing

A software system can best be designed if the testing is interlaced with the designing instead of being used after the design.

A simulation which matches the requirements contains the control which organizes the design of the system.

Through successive repetitions of this process of interlaced testing and design the model ultimately becomes the software system itself.

Alan Perlis, Design Group Chairman
§4.3.3. NATO "Software Engineering" Conference, October 1968

This was the very software engineering conference.

Why do we test?

Because...

Software is fragile

Writing code isn't like writing a book:

Just one tiny mistake can have a huge impact.

Even worse, that impact might not be obvious until much later - when things suddenly fall over!

We make mistakes!

In a 2014 study, researchers found that most failures are caused by simple, common programming mistakes:

58% of them are trivial mistakes or can be exposed by statement coverage testing

Ding Yuan et al
"Simple Testing Can Prevent Most Critical Failures..."
11th USENIX Symposium 2014

I would like to meet a developer who has never made any of these errors:

Other people make mistakes!

Even when your code works perfectly, it may easily get broken by someone (future you?) making changes to code later.

There are several different scenarios:

We want to KNOW when code breaks

One of the most important advances in human thought is that of the empirical scientific method:

  1. Have an idea; normally this is a model that predicts a certain result
  2. Design a test (experiment) that can measure your idea's expected result.
  3. Publish your test so that others can replicate it.
  4. Refine your idea based on your results.

This creates a feedback loop which allows us to iteratively improve our ideas.

We should strive to emulate this process in our code.

We need to agree what "working" MEANS.

How do we know when our code actually meets our requirements?

How do we agree with our stakeholders on what our code should actually do?

Testing approaches such as BDD and specification tests can give us a shared language that can explicitly state what 'working' is - and can be used automatically to ensure that this doesn't change unintentionally.

So, do we need testing?

By implementing Continuous Delivery, a development/release philosophy largely based on Test Driven Development, the online betting company Paddy Power was able to deliver huge benefits:

Product quality has improved significantly. The number of open bugs for the applications has decreased by more than 90 percent.

Lianping Chen, Paddy Power,
Continuous Delivery: Huge Benefits, but Challenges Too
InfoQ, 2015

Types of Testing

Types of Testing

There are a number of types of test, including:

Definitions are somewhat wooly, and there can be some overlap!

Unit Tests

Unit tests are written to verify a single component does what is intended.

Integration Tests

Integration tests demonstrate that different pieces of the system work together.

Regression Tests

Regression tests are run to prove that new changes don't break old functionality, or introduce new bugs.

Acceptance Tests

Acceptance tests ensure that a given feature or use case works correctly.

The focus is on the behaviour or requirement.

Testing Philosophies

Disclaimer

The following few slides present my own opinions, or at least the reasoning behind them.

Test Driven Development

Test Driven Development, or TDD, is built on the idea that you should write your tests FIRST, then your code.

There are a number of reasons to do this:

Conversely, writing tests after code:

TDD process:

  1. Write your test
  2. Run your test: it should FAIL. This tests the test.
  3. Write your code
  4. Run the test again.
  5. Repeat steps 3 & 4 until the test passes!

Behaviour Driven Development

Behaviour-driven development started life as an NLP exercise to stem the abuse of the word “test” in “test-driven development”.

Dan North, Originator of BDD
There's more to BDD than evolving TDD, 2006

BDD is an effort to try to pick the best language to encourage our brains to follow good TDD practice: changing our mindsets by changing the words we choose.

In recent years, tools like Gherkin/Cucumber and Specflow have taken this idea to extremes, allowing executable specifications to be written in natural language.

This lends itself particularly well to "functional" acceptance tests: specifications written from the perspective of external users.

This has a lot of value, BUT many people fall in to the trap of thinking that this is all BDD is.

BDD can lend a discipline and framework that can improve testing on multiple levels.

BDD Terms

There are some terms that BDD encourages replacing:

Specification
instead of "Test Suite"
Scenario
instead of "Test"

It also recommends a particular pattern for expressing tests:

Given
Defines the pre-conditions, or context of the scenario
GIVEN there are 10 hot dogs
When
Specifies the behaviour that we want to model
WHEN I eat 8 hot dogs
Then
Specifies the expected result
THEN there are 2 hot dogs left
THEN I feel sick...

BDD and "Ubiquitous Language"

It's not just about development and testing!

One of the recommendations of BDD is to develop a "Ubiquitous Language" for your project.

This should be agreed with and used by all stakeholders, not just developers.

Each meaningful concept in the project should use the same word or term.

Some will see this as plain common sense, others pedantry; however there are some clear advantages:

Testing XSLT with XSpec

XSpec

XSpec was introduced at XML Prague in 2009 by Jeni Tennison.

Open source and community run, it is currently hosted on github:

XSpec is a unit test and behaviour-driven development (BDD) framework for XSLT, XQuery, and Schematron. It is based on the Spec framework of RSpec, which is a BDD framework for Ruby.

XSpec consists of a syntax for describing the behaviour of XSLT, XQuery, or Schematron code, and some code that enables you to test the code against those descriptions.

https://github.com/xspec/xspec

XSpec Example


      <x:scenario label="Should find the deepest node">
        <x:call function="re:find-deepest">
          <x:param name="node">
            <a>
              <b>
                <c>
                  <d>
                    <f/>
                    <g>
                      <h/>
                    </g>
                  </d>
                </c>
              </b>
              <i>
                <j/>
              </i>
            </a>
          </x:param>
        </x:call>
        <x:expect label="deepest node should be 'h'"><h/></x:expect>
      </x:scenario>
    

XSpec Vocabulary

XSpec attempts to treat tests as documentation.

We can see echos of the classic BDD "Given, When, Then" paradigm.

The basic unit of the XSpec test is the scenario:


      <x:scenario label="Should find the deepest node">
        ...
      </x:scenario>
    

We can see that @label here is describing what the underlying requirement is here.

Starting with the word "Should" is not mandatory, but does help us form the right expression.

XSpec and BDD: Given & When

In this example, both the preconditions (GIVEN a node a) and the modelled behaviour (WHEN called with function re:find-deepest) are given by x:call:


      <x:call function="re:find-deepest">
        <x:param name="node">
          <a>
            ...
          </a>
        </x:param>
      </x:call>
    

(we will see shortly that there are similar alternative elements)

XSpec and BDD: Then

The result(s) that we expect (THEN the result should be 21) from the test is specified using x:expect


      <x:expect label="deepest node should be 'h'"><h/></x:expect>
    

XSpec Syntax

XSpec uses the namespace http://www.jenitennison.com/xslt/xspec, usually prefixed as x

The root element of every XSpec document is x:description.

The stylesheet being tested can be specified using a relative URI as the value of @stylesheet.


      <x:description stylesheet="my.xsl">
        ...
      </x:description>
    

Scenarios

x:description contains a number of x:scenario elements.

Each scenario can have a @label which describes what is being tested.

Scenarios can be nested indefinitely: this can be very useful when grouping similar behaviours to be tested:


      <x:description stylesheet="my.xsl">
        <x:scenario label="Should transform emphasis elements">
          <x:scenario label="With @role='italic'">...</x:scenario>
          <x:scenario label="With @role='bold'">...</x:scenario>
        </x:scenario>
      </x:description>
    

Types of Scenario

There are three different types of scenario, each testing a different type of behaviour:

Matching
These scenario describe the expected behaviour of applying templates in a given mode on some content.
x:context
Function
These scenario describe the expected behaviour of calling a given function
x:call[@function]
Named Template
These scenario describe the expected behaviour of calling a given named template
x:call[@template]

Matching Scenario: providing context

The content that we're looking to test can be provided either using a reference to an external file:


      <x:context href="docbook-para.xml"/>
    

Or directly in the element:


      <x:context>
        <para>I am a docbook paragraph!</para>
      </x:context>
    

Note that, in the latter case, the content does not have to be a valid docbook instance; it only has to be well-formed, and provide the necessary content for the test.

Context options

A number of options may be specified:


      <x:context href="docbook.xml" select="(//para)[1]" mode="toHTML">
        <x:param name="units" select="metric" tunnel="yes"/>
      </x:context>
    

Function Scenario

Testing functions requires specifying which function is being called using x:call/@function.

Function arguments are specified using x:param, either in the order they are defined:


      <x:call function="re:count-characters-in-string">
        <x:param select="a"/>
        <x:param select="banana"/>
      </x:call>
    

Or using the @position attribute (the following is equivalent):


      <x:call function="re:count-characters-in-string">
        <x:param select="banana" position="2"/>
        <x:param select="a" position="1"/>
      </x:call>
    

Named Template Scenario

Named templates must be specified using xsl:call/@template.

Unlike function scenario, any x:param elements must have a @name corresponding to the named template being tested.

An optional context may also be provided:


      <x:context>
        <div>
          <h1>An Unexpected Guest</h1>
          <p>...</p>
        </div>
      </x:context>
      <x:call template="makeTitle">
        <x:param name="ordinal" select="'Chapter'" tunnel="yes"/>
      </x:call>
    

Great Expectations

We use the x:expect element to define what we expect a result to be.

Expectations can be expressed using sequence constructors (note that the symbol '...' means that corresponding nodes don't need to be compared):


      <x:expect label="Transforms to p">
        <p>...</p>
      </x:expect>
    

As an external file


      <x:expect label="Transforms to p" href="docbook-para.html"/>
    

As atomic values:


      <x:expect label="count 3 'a's" select="3"/>
    

Or as a boolean test:


      <x:expect label="@result is exactly divisible by 9" test="@result mod 9 eq 0"/>
    

Specifying descendant nodes

Combine a sequence constructor or @href with @select to return a descendant node to compare the result to.

You can ensure that you have retrieved the appropriate node using the @as attribute to define a type.


      <x:expect label="should use the title from Chapter 1" href="chapter1.xml" select="/chapter/title[1]" as="element(title)"/>
    

Best practice is to use @select and @as together: this is to avoid false positive comparisons where @select = ().

Specifying nodes in the result to test

If @test is not a boolean, you can use it to specify a descendant node to use instead of the test result:


      <x:expect label="test the emphasis on 'dynamic' in the result is transformed to i" test="p/i">
        <i>dynamic</i>
      </x:expect>
    

XSpec Gotchas

Whitespace

Note that whitespace-only nodes may be discarded where defined in-line.

For instance, the (significant) whitespace in a sentence like the following would be lost:


      <x:context>
        <p><i>Sweet</i> <b>Lord!</b></p>
      </x:context>
    

Avoid this by importing the content using @href:


      <x:context href="sweet.xml"/>
    

Result Documents

Because XSpec is actually just XSLT under the hood, it can run into some limitations.

One of those is that it is hard to test the results of xsl:result-document.

This appears to be a limitation, but you can turn it into an advantage. Use it to help design your code.

xsl:result-document is a feature of your XSLT implementation, not your code: test it as part of your integration testing, not your unit testing.

Try to separate the concerns in your code: populate your document separately from serialising it.

Testing XQuery with XSpec

XSpec and XQuery

As well as testing XSLT, XSpec can also be used to test XQuery!

Our Function

Our library module and function under test:


module namespace lib1 = "http://my.com/lib1";

declare function lib1:calc(
        $label as xs:string, $x as xs:integer, $y as xs:integer) as element(result) {
    
    <result label="{$label}">
    { $x div $y }
    </result>
};

        

Our XSpec

Our XSpec Specification expressed in XML:


<?xml version="1.0" encoding="UTF-8"?>
<x:description xmlns:x="http://www.jenitennison.com/xslt/xspec"
    xmlns:lib1="http://my.com/lib1"
    query="http://my.com/lib1"
    query-at="lib1.xqm">
    
    <x:scenario label="Calc applies a label">
        <x:call function="lib1:calc">
            <x:param select="'label1'"/>
            <x:param select="1"/>
            <x:param select="1"/>
        </x:call>
        
        <x:expect label="should apply a label to the result" test="$x:result/string(@label)" select="'label1'"/>
    </x:scenario>
    
    <x:scenario label="Calc divides two integers">
        <x:call function="lib1:calc">
            <x:param select="'label1'"/>
            <x:param select="10"/>
            <x:param select="5"/>
        </x:call>
        
        <x:expect label="should divide two integers">
            <result label="label1">2</result>
        </x:expect>
    </x:scenario>
    
</x:description>

        

Our Results

Testing XQuery with XQSuite

XQSuite

XQSuite online documentation.

Our Function

Our library module and function under test:


module namespace lib1 = "http://my.com/lib1";

declare function lib1:calc(
        $label as xs:string, $x as xs:integer, $y as xs:integer) as element(result) {
    
    <result label="{$label}">
    { $x div $y }
    </result>
};

        

Our XQSuite Test Suite

Our XQSuite Test Suite expressed in XQuery:

xquery version "3.0";

module namespace l1t = "http://test.my.com/lib1";
declare namespace test = "http://exist-db.org/xquery/xqsuite";
import module namespace lib1 = "http://my.com/lib1"
    at "file:///Users/aretter/code/exist-for-release/exist-core/src/test/xquery/lib1.xqm";

declare
    %test:assertEquals("label1")
function l1t:applies-label() {
    lib1:calc('label1', 1, 1)/string(@label)
};

declare
    %test:assertEquals("<result label='label1'>2</result>")
function l1t:divides-two-integers() {
    lib1:calc('label1', 10, 5)
};