Test Python with Hypothesis

Testing base on knowledge base

Each time you write test you straggle to choose good testing parameters.

There is temptation to use random values but it has some drawbacks. Lack of repeatability for first. And in fact it is not so good to find weak places in your application. You need a lot of runs to stumble upon ingenious data - you know like in Infinite monkey theorem

But do there is knowledge base for that just waiting for you use it.

class Employee:
    def __init__(self, salary):
        self.salary = salary

    def give_a_raise(self, increase):
        self.salary += increase


from hypothesis import given
from hypothesis import strategies as st


money_strategy = st.floats(min_value=1, max_value=1000000, allow_nan=False, allow_infinity=False)


@given(money_strategy, money_strategy, money_strategy)
def test_bonus_distribution(salary1, salary2, bonus_fund):
    e1 = Employee(salary1)
    e2 = Employee(salary2)
    increase1 = bonus_fund / 2
    increase2 = bonus_fund - increase1
    e1.give_a_raise(increase1)
    e2.give_a_raise(increase2)
    money_spent = e1.salary - salary1 + e2.salary - salary2
    assert bonus_fund == money_spent
test_finance.py F
test_finance.py:15 (test_bonus_distribution)
1.0000000000000002 != 1.0

Expected :1.0
Actual   :1.0000000000000002

The example is very simple one just to give you a taste. Of cause you know beforehand and without any tests that this code is bad one to manipulate with money. But just imagine some novice wrote it, used Hypothesis to test and bang! - through Hipothesis she gets advice from experts that actually this is not so good code.

Just think about that - this is not just test framework but expert knowledge base.