Python - provide a function as an argument to another function to improve its testability


Python tip:

You can provide a function as an argument to another function to improve its testability.

For example, you can provide input as a function in a real application and mock the function in test

def get_user_expense(get_input):
    raw_input = get_input(
        "Enter your expense (date;description;amount) (e.g. 2021-03-21;Gasoline;75.43): "
    )
    date, description, amount = raw_input.split(";")
    return date, description, amount


# test
def test_get_user_expense():
    assert get_user_expense(lambda *args: "2021-03-21;Gasoline;75.43") == (
        "2021-03-21",
        "Gasoline",
        "75.43",
    )


# real application
def main():
    date, description, amount = get_user_expense(input)
    print(date, description, amount)