Difference between assertion and exception in Python

Introduction

Software quality assurance is extremely important in software development. The purpose of testing is to uncover serious defects before pushing products to production. Testing should be part of team culture and every member should participate.Test engineers can do black box, integration and system level testing. on the other hand, developers write unit tests. Testing can not guarantee the absence of bugs but it gives confidence to push software out of the door. One of the most important aspects of testing is input sanitization. Invalid input opens the door to security holes that can make the system vulnerable to attacks. With that being said, we are going to talk about exceptions and assertions in Python. These techniques can be used to implement unit testing and make sure that the code behaves as intended.

Let us start with assertions first…

What is an assertion?

An assertion is a (debugging) boolean expression to self check an assumption about the internal state of a function or object. If true, nothing happens otherwise, execution halts and an error is thrown. Assertion is a way to declare a condition that is impossible to occur. If it does that means the code is not just buggy but broken or unrecoverable. Assertions are typically used to do sanity checking that is too expensive for production use. The feedback given by an assertion is for the development team as opposed to the user. In the next section, we will mention scenarios in which assertions are a good choice to use…

When to use an assertion?

As we will see later, not only assertions but also exceptions are used to indicate that something wrong happened. When to use assertions or exceptions does not have rules written on stone. Sometimes the choice is a gray area. In this section, we will indicate few examples where assertions make more sense to use as opposed to exceptions.

  • Parameter types for a private function (ex. the power has to be an integer in exponential function)
  • Precondition (ex. positive number in a square root function)
  • Can not happen situations (ex. duplicates in a list, zero divisor)
  • Corner cases that are hard to occur but possible (depends on the application)
  • Automated unit testing (will provide an example later). What about exceptions?

What is an exception?

An exception is similar to an assertion but the meaning is different. An exception is an unexpected execution event that disrupts the normal flow of the program. Exceptions are used to signal an error condition where a corrective action can be taken (ex. file not found). Exceptions can be caught and recovered from as opposed to assertions. The next section gives few example scenarios where exceptions can be used…

When to use an exception?

When the program encounters an error during the course of execution, an exception should be raised with a meaningful error message. Here are a few examples…

  • Invalid input from user or external source
  • System failure such as file not found or network errors
  • When using public APIs

Definition of an assertion

The syntax for assertion in Python is as follows…

where condition is a boolean expression that evaluates to true or false. You can also provide an optional error message to indicate what happens when the assertion is triggered. Here is an example…

If you run the code snippet above, nothing is going to happen. If you change the value of x to 4 for example, you should get the following assertion error message…

Note that the assertion statement can be implemented as an exception as follows…

Note that assertions are checked only during debug mode. In other words, if you run the script above using optimization mode, the assertion statement is not going to get executed. For example…

Assertions and tuples

Using parenthesis with an assert statement can always yield true. This can be misleading, for example the following assert statement is NOT going to trigger an error message…

The reason why this is the case is because non empty tuples in Python evaluate to true when treated as boolean value. Take a look…

This is going to print

So watch out as you write your assertions. Let us now talk an example on unit testing using assertions…

Assertions and unit testing

Assertion should be used to complement unit testing not to replace it. In the example below, we are going to use the assert statement in a simple unit test…

Note that the unit test module in Python provides much more than jus an assert statement. Check the references section for more details.

Summary

  • Assertions are the conditions that are supposed to be true all the time otherwise the program must be broken
  • Assert statement is used as debugging tool as it halts the program at the point where an error occurs
  • Exceptions address the robustness of application while assertions address correctness

References

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *