Contribute Media
A thank you to everyone who makes this possible: Read More

Introduction to Property-Based Testing

Translations: en en

Description

Has testing got you down? Ever spent a day writing tests, only to discover that you missed a bug because of some edge case you didn’t know about? Does it ever feel like writing tests is just a formality - that you already know your test cases will pass?

Property-based testing might be just what you need!

After this introduction to property-based testing, you’ll be comfortable with Hypothesis, a friendly but powerful property-based testing library. You’ll also known how to check and enforce robust properties in your code, and will have hands-on experience finding real bugs.

Where traditional example-based tests require you to write out each exact scenario to check - for example, assert divide(3, 4) == 0.75, property-based tests are generalised and assisted. You describe what kinds of inputs are allowed, write a test that should pass for any of them, and Hypothesis does the rest!

from hypothesis import given, strategies as st

@given(a=st.integers(), b=st.integers()) def test_divide(a, b): result = a / b assert a == b * result There’s the obvious ZeroDivisionError, fixable with b = st.integers().filter(lambda b: b != 0), but there’s another bug lurking. Can you see it? Hypothesis can!

Details

Improve this page