tcltest Part 6 – Test for Error Conditions

The Problem

We want to test functions which might return an error.

The Solution

tcltest provides a way to test functions which might return an error: the -returnCodes flag. Before we go into details with the -returnCodes, let’s take a look at the behavior when a function returns an error:

$ tclsh
% expr 5 / 0
divide by zero
% open zzzzz r
couldn't open "zzzzz": no such file or directory

In line 1, we started an interactive Tcl session. Line 2 and 4 triggers different kinds of errors, which we we will capture in our tests:

# negative.test

package require tcltest
namespace import ::tcltest::*

test divide_by_zero {} -body {

    expr {5 / 0}

} -returnCodes {error} -result "divide by zero"

test open_non_existing_file {} -body {

   open zzzzz r

} -returnCodes {error} -result {couldn't open "zzzzz": no such file or directory}

cleanupTests

Explanations:

  • Lines 8-10: We know that this expression will trigger an error, so we use the -returnCodes flags to specify this behavior. The -result flag in this case specifies the error message.
  • Likewise, lines 14-16 tests the situation when opening a non-existing file for reading.

Conclusion

Testing the error condition in tcltest is straight forward. All we need to know if when the error condition occur and its error message. In the next installment, we will discuss situations where we have to test functions while we don’t know the exact output.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s