The -3.50 refund your round-trip test will miss
Hypothesis can generate hundreds of order lines, but the parser bug surfaces only when results are checked against an independent calculation.
In brief
- Hypothesis runs 100 examples per test by default; settings(max_examples=...) can raise that to several hundred.
- Round-trip is a strong property, but an error made identically in both directions still slips through, so add an independent check.
- Use @example to pin a customer's real broken lines. Hypothesis saves past failures in .hypothesis/examples and replays them on the next run.
A refund line in a customer’s order file says -3.50, and the parser reads it as -2.50. In this hypothetical case the hand-written tests stay green, and so does the round-trip test. The error surfaces only when the customer’s accountants reconcile the books at month end.
A parser for customer data deserves more testing than its simple appearance suggests. You may write it from a handful of sample files, but it then has to run for months on data you have never seen.
Hypothesis is a Python library for property-based testing. Instead of guessing each example in advance, you describe a whole range of scenarios and let the machine probe the possibilities.
This guide follows a single example from start to finish. You will write an order-line parser, generate several hundred structured lines, see how a seemingly strict property still misses a bug, then pin a customer’s real broken line into the test.
What do you need before you start?
You need Python 3, pytest and Hypothesis installed in a virtualenv (usually with pip install hypothesis pytest). The data format is invented for this guide: each line holds an order ID, a date and an amount, separated by semicolons, such as ORD-00042;2024-03-07;12.50. The code is simplified for illustration and is not a production parser.
Step 1: A parser that looks right
# parser.py: simplified for illustration
from dataclasses import dataclass
@dataclass
class Order:
order_id: str
date: str
amount_cents: int
def parse_line(line: str) -> Order:
order_id, date, amount = line.strip().split(";")
whole, _, frac = amount.partition(".")
cents = int(whole) * 100 + int((frac + "00")[:2])
return Order(order_id, date, cents)
def format_line(o: Order) -> str:
return f"{o.order_id};{o.date};{o.amount_cents // 100}.{o.amount_cents % 100:02d}"
Given 12.50, the amount comes out as 1250. Given 12, it comes out as 1200. Unit tests on a few sample lines will all pass, and therein lies the trap.
Step 2: Describe the data with a strategy
The hardest part of property-based testing is generating complex inputs. Hillel Wayne has observed that the literature on PBT rarely covers this part.
To combine several strategies, use @composite: the decorated function takes draw as its first parameter and calls it to get a value from each smaller strategy.
Text fields are generated by st.from_regex with fullmatch=True, so that the entire generated string matches the pattern.
# test_parser.py
from hypothesis import given, settings, strategies as st
from parser import Order, parse_line, format_line
@st.composite
def orders(draw):
order_id = draw(st.from_regex(r"ORD-[0-9]{5}", fullmatch=True))
date = draw(st.from_regex(r"20[0-9]{2}-[01][0-9]-[0-3][0-9]", fullmatch=True))
cents = draw(st.integers(min_value=-10_000_000, max_value=10_000_000))
return Order(order_id, date, cents)
@settings(max_examples=500)
@given(orders())
def test_round_trip(order):
assert parse_line(format_line(order)) == order
The @given decorator turns an ordinary function into a Hypothesis test. Each test runs 100 examples by default; max_examples=500 raises that number. Run pytest and the test is green.
If you would rather start from a test skeleton, the hypothesis write command (Ghostwriter) generates one. Ghostwriter’s documentation calls round-trip a very powerful property, especially when configuration options are varied along with the object.
Step 3: Why is the test green when the parser is wrong?
Send -250 cents around the loop. Python’s // rounds down, so -250 // 100 gives -3, while % takes the sign of the divisor, so -250 % 100 gives 50. format_line therefore writes -3.50, and parse_line reads it back as -300 + 50 = -250. Both directions make the same mistake and so agree with each other, while to a human reader -3.50 means -350.
The remedy is a second property with an independent check. Generate the amount string directly, the way the customer writes it, then compare the result with Decimal, a calculation that shares no logic with the parser:
from decimal import Decimal
@st.composite
def raw_lines(draw):
order_id = draw(st.from_regex(r"ORD-[0-9]{5}", fullmatch=True))
date = draw(st.from_regex(r"20[0-9]{2}-[01][0-9]-[0-3][0-9]", fullmatch=True))
amount = draw(st.from_regex(r"-?[0-9]{1,6}\.[0-9]{2}", fullmatch=True))
return f"{order_id};{date};{amount}", amount
@settings(max_examples=500)
@given(raw_lines())
def test_amount_matches_decimal(case):
line, amount = case
assert parse_line(line).amount_cents == int(Decimal(amount) * 100)
This time the test is red. Hypothesis runs a “simplification” process behind the scenes, so the counterexample you get is usually a short line with a small negative amount rather than the messy string it first stumbled on. One look at it shows that the minus sign is to blame.
Step 4: Fix the bug and pin the customer’s real line
Move the amount parsing into its own function that handles the sign first, then make format_line symmetrical: write the sign separately and format the absolute value.
def parse_amount(s: str) -> int:
sign = -1 if s.startswith("-") else 1
whole, _, frac = s.lstrip("-").partition(".")
return sign * (int(whole) * 100 + int((frac + "00")[:2]))
def parse_line(line: str) -> Order:
order_id, date, amount = line.strip().split(";")
return Order(order_id, date, parse_amount(amount))
def format_line(o: Order) -> str:
sign = "-" if o.amount_cents < 0 else ""
a = abs(o.amount_cents)
return f"{o.order_id};{o.date};{sign}{a // 100}.{a % 100:02d}"
Check it by hand: -250 cents is now written as -2.50, and parse_amount("-2.50") returns -(200 + 50) = -250. Both the round-trip and Decimal tests should be green.
Next, put the refund line the customer sent into the test with @example. Hypothesis always runs these explicitly declared inputs before it generates random data:
from hypothesis import example
@example(("ORD-00042;2024-03-07;-3.50", "-3.50"))
@settings(max_examples=500)
@given(raw_lines())
def test_amount_matches_decimal(case):
...
From now on, every broken file a customer sends should leave behind an @example line. Together they become a record of the project’s lessons, kept in the code and still there after you have moved on to another customer.
Step 5: Tune the number of runs and the time limit
Real parsers often run heavy regexes, look up tables or normalize Unicode. Hypothesis sets a default deadline of 200 milliseconds per example, so a slow parser will be reported as failing even when its result is correct. When that happens, relax the deadline in settings deliberately and note the reason, rather than switching it off altogether.
Hypothesis also saves examples that have failed in the .hypothesis/examples folder of the current working directory and replays them on the next run. If a failure appears and then vanishes, do not be quick to dismiss it as random. Look in that folder first.
What are the most common mistakes?
The most common is a strategy narrower than the real data: generating only positive numbers when the customer issues refunds, or only ASCII when customer names contain accents. Base the strategy on sample files and what the customer tells you, rather than on what the parser currently accepts.
The second is an assertion that repeats the parser’s own logic, the round-trip trap from step 3. The third is treating Hypothesis as a replacement for unit tests. Its documentation states clearly that it is a complement, so business cases the customer has confirmed still need to be written as explicit example tests.
What does this skill look like on a customer site?
On the day you first receive a customer’s files, before writing the parser, ask the questions that will later become regexes in your strategy. How are negative numbers written? Do dates ever lack a leading zero? Does the order ID prefix ever change? Each answer is a line in @composite, and each “not sure” is a case to include in the strategy.
On a résumé, describe this skill through concrete results instead of just writing “Python”. A line such as “wrote property-based tests for customer data parsers, pinning N failure cases from production” shows a recruiter that you have handled real data, and you can put a demo repo right beside it.
In an interview, recounting the round-trip trap from step 3 is a quick way to show that you understand what a test actually proves.
Sooner or later the parser will meet data you have not seen. Your job is to have a few hundred generated lines meet it before the customer’s accountants do.
Was this article useful?
Thanks for the feedback!