Read my book

I wrote books about Webpack and React. Check them out!

Sunday, November 29, 2009

The Usage of Assertions

I recently found this nice article about usage of assertions with unit tests. The author proposes two interesting questions at the end of his post:
  1. So can assertions be useful even in code that is well unit-tested?
  2. Are there any rules we can use to choose which things might be more productively tested using such asserts, rather than in unit tests?
I think it's clear that the answer to both is a definite yes. It's important to understand that unit tests treat the code as a black box. You only see the interface, not the actual implementation. Assertions on the other hand treat the code as a white box and deal with the implementation directly. On this basis it can be stated that essentially assertions complement unit tests.

To answer the latter question I prefer to paraphrase this wiki article that states one should consider using assertions in the following cases:
  • checking parameter types, classes, or values
  • checking data structure invariants
  • checking "can't happen" situations (duplicates in a list, contradictory state variables.)
  • after calling a function, to make sure that its return is reasonable
Naturally statically typed languages force you to assert types. This does not mean you cannot do it in a dynamically typed language, such as Python. In fact doing so may provide performance benefits.

At the simplest level you can check type using isinstance. On the long run checking types this way may get just plain boring. Alternatively it's possible to use decorator or docstring based solutions. I haven't found any actual example for the latter case but it might be possible to get inspired by Contracts for Python. Besides parameter types it should be easy to assert the return type as well.

So how to gain the performance benefits I hinted about before? Simply use Pyrex or Cython. The basic idea is that you provide some extra information in your code based on which either of these solutions generates a high performance C extension. To get started, check out this tutorial to Cython.