Skip to content

Instantly share code, notes, and snippets.

@agritheory
Created April 27, 2018 11:31
Show Gist options
  • Save agritheory/2a0679e821a3998ad74cbd2ed7840623 to your computer and use it in GitHub Desktop.
Save agritheory/2a0679e821a3998ad74cbd2ed7840623 to your computer and use it in GitHub Desktop.
Hypothesis Example from NH Python project night 4/26/18
import unittest
import datetime as dt
from hypothesis import assume, given, example
from hypothesis.strategies import text, integers, floats, dates, composite, shared
# also discuss: from_regex, random and shared strategies: http://hypothesis.readthedocs.io/en/latest/data.html
class TestTransaction(unittest.TestCase):
@composite
def transaction_schema(draw):
credit = draw(shared(floats(min_value=0, max_value=100000), key="amounts"))
credit_account = draw(text())
debit = draw(shared(floats(min_value=0, max_value=100000), key="amounts"))
debit_account = draw(text())
ref_no = draw(integers())
date = draw(dates(min_value=dt.date.today())) # define min_value and max_value
assume(credit_account != debit_account)
return {"credit": credit,
"credit_account": credit_account,
"debit": debit,
"debit_account": debit_account,
"ref_no": ref_no,
"date": date}
example_transaction = {"credit": 17.76,
"credit_account": "Checking",
"debit": 17.76,
"debit_account": "Postage",
"ref_no": 456,
"date": dt.date.today()}
@given(transaction_schema())
@example(None, example_transaction) # "None" is required, takes the positition of "self"
def test_transaction(self, transaction):
# no blanks or None
disallowed_values = ("", None) # tuple for immutability
assert transaction["credit"] not in disallowed_values
assert transaction["debit"] not in disallowed_values
assert transaction["ref_no"] not in disallowed_values
assert transaction["date"] not in disallowed_values
# no negative numbers
assert transaction["credit"] >= 0.0
assert transaction["debit"] >= 0.0
# cannot be one-sided
assert (abs(transaction["credit"] - transaction["debit"]) < 0.0001)
# floats not integers
assert isinstance(transaction["credit"], float)
assert isinstance(transaction["debit"], float)
# no backdating
assert transaction["date"] >= dt.date.today()
# credit account and debit account cannot be the same
assert transaction["credit_account"] != transaction["debit_account"]
@example(None, 4, 5) # "None" is required, takes the positition of "self"
@given(x=integers(), y=integers())
def test_ints_cancel(self, x, y):
print(x, y)
assert (x + y) - y == x
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment