DEV Community

Your Tests Only Check the Examples You Thought Of and Someone Mentioned Property Based Testing

You wrote a function that splits a list of results into pages. You tested it with ten items and a page size of three, and with an empty list. All green.

A week later a user on the last page sees one result twice. Someone in the review says that property based testing would probably have found it, and you nod without knowing what that means. It is worth learning.

Example-Based Tests Only Check What You Choose

Most tests are example based. You choose an input, work out the expected output and check it. The weakness is that you choose the inputs, and you tend to choose the ones you were already thinking about when you wrote the code.

Properties Instead of Examples

Property based testing turns this around. Instead of examples, you describe something that should always be true, and a library generates many inputs to try to prove you wrong.

The idea comes from QuickCheck, a Haskell tool described by Koen Claessen and John Hughes in a paper in 2000. Today there are versions for most languages, such as Hypothesis for Python, fast-check for JavaScript and jqwik for Java.

For the pagination function, the properties might be these:

  • Joining all the pages back together gives the original list, in the same order.
  • No page is longer than the page size.
  • Only the last page can be shorter.

You do not say what the input is. You say what must hold for any input.

In Python with Hypothesis, you decorate the test with @given(st.lists(st.integers()), st.integers(min_value=1)), and the library supplies the list and the page size. By default it runs a hundred different examples each time.

Shrinking Finds the Smallest Failure

The clever part is called shrinking. When the library finds a failing input, it keeps simplifying it until it finds the smallest one that still fails. Instead of a list of forty numbers, you are shown a list of four and a page size of three. That is often enough to see the bug immediately.

Good Properties Take Practice

Good properties take practice. Some that work almost everywhere are a round trip, where saving and loading something gives back what you started with, and a comparison with a slower but obviously correct version of the same function.

Start small. Pick one function with a clear rule, write one property and see what it finds. Do not be surprised if the first thing it finds is a case you never thought to ask about.

  • Asael Shinder
Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.