5.19. How to Handle Exceptions Raised in Test Scripts

Some of Squish's functions raise catchable exceptions on failure. We can write our test scripts so that they can catch these exceptions and respond accordingly—for example, by recording a test failure in the test log.

The exception handling mechanism works the same way for each scripting language, no matter what function raised the exception, so we only need to look at one example to see how it is done.

Python

    try:
        checkBox = waitForObject(":Make Payment.Check Signed_QCheckBox")
        test.passes("Found the checkbox as expected")
    except LookupError, err:
        test.fail("Unexpectedly failed to find the checkbox", str(err))
JavaScript

    try {
        checkBox = waitForObject(":Make Payment.Check Signed_QCheckBox");
        test.pass("Found the checkbox as expected");
    } catch (err) {
        test.fail("Unexpectedly failed to find the checkbox", err);
    }
Perl

    eval {
        my $checkBox = waitForObject(":Make Payment.Check Signed_QCheckBox");
        test::pass("Found the checkbox as expected");
    };
    test::fail("Unexpectedly failed to find the checkbox", "$@") if $@;
Ruby

  begin
    checkBox = waitForObject(":Make Payment.Check Signed_QCheckBox")
    Test.pass("Found the checkbox as expected")
  rescue Squish::LookupError => err
    Test.fail("Unexpectedly failed to find the checkbox", err)
  end
Tcl

    if {[catch {
        set checkBox [waitForObject ":Make Payment.Check Signed_QCheckBox"]
        } result]} {
        test fail "Unexpectedly failed to find the checkbox" $result
    } else {
        test pass "Found the checkbox as expected"
    }

The waitForObject function tries to find the specified object. If the object is not accessible—perhaps because it isn't visible—within the timeout period, the function raises a catchable exception. In this example, we call the test.pass function if the object (a checkbox in this example) is found within the timeout period, and the test.fail function if the object isn't found and giving the exception (in string form) as the details text.

In most cases and for most languages Squish simply raises the language's base class exception (e.g., Exception in Python and StandardError in Ruby). However, for Python and Ruby, when an object can't be found a more specific LookupError (Squish::LookupError in Ruby) is raised.

[Note]Python-specific

Notice that we must use the test.passes function instead of test.pass to avoid a name clash with Python's built-in pass statement.