from hypothesis import given
from hypothesis.strategies import integers
defsum(a: int, b: int) -> int:return a + b
@given(integers(), integers())deftest_sum_commutes(a: int, b: int):assertsum(a, b) == sum(b, a)
Hypothesis provides:
A given decorator to randomly generate fixtures
A package, hypothesis.strategies, providing methods to generate random data of the most common types
Methods to generate your own testing strategies for more complicated data
Integration with pytest: useful test failure messages
An exercise in TDD with dates
Because if you have imported datetime, you have struggled with dates.
Festa Major in Sant Esteve Sesrovires: First Sunday of August.
Problem: print the date of the next Festa Major.
Code skeleton
import datetime as dt
defnext_festa_major(date: dt.date) -> dt.date:return date
if __name__ == "__main__":
today = dt.date.today()
next_fm: dt.date = next_festa_major(today)
print(f"Today is {today}. The next Festa Major will be on {next_fm}")
import hypothesis.strategies as st
dates = st.dates(max_value=dt.date(3000, 1, 1))
@given(dates)deftest_next_festa_major_is_after_given_date(date: dt.date):assert date <= next_festa_major(date)