Arrange, act, assert
A test that is easy to read has three parts, in this order. Arrange the inputs, act by calling the code once, then assert on what came back. A test that acts twice is usually two tests, and each should be named after the behaviour it protects.
def split_bill(cents, people):
share, extra = divmod(cents, people)
return ([share + 1] * extra
+ [share] * (people - extra))
def test_shares_add_up():
cents, people = 1000, 3
shares = split_bill(cents, people)
assert sum(shares) == cents, shares
test_shares_add_up()
print(split_bill(1000, 3))Messages that help
pytest shows the values in a failed comparison, but it cannot know which input you were trying or why the value matters. Outside pytest, in a helper or a script, a bare assert says nothing at all. The expression after the comma is shown when the assert fails, and it is only evaluated then.
shares = [333, 333, 333]
try:
assert sum(shares) == 1000, shares
except AssertionError as error:
print("failed, the shares were", error)Your task
split_bill is written for you. Write test_shares_add_up and test_shares_differ_by_at_most_one_cent, both splitting 1000 cents between 3 people in arrange, act, assert order, and give each assert a message that shows the shares.
The explanation opens here once every check passes.