Bocco Aniefiok
Bocco Aniefiok

Reputation: 1

How can i create a unit test for a function that asks user for input

I'm new to unit testing. I'm working on an ATM program. I want to make a unit test for the deposit operation. I have checked online but i am not getting an answer to my problem. This is my first time of posting here. Thank you for the assistance in advance

This is my code below

def deposit_operation(user):

    amount_to_deposit = int(input('ENTER AMOUNT YOU WANT TO DEPOSIT: ')
    # amount should be in multiples of 1,000
    if amount_to_deposit % 1000 != 0:
        print('AMOUNT YOU WANT TO DEPOSIT MUST BE IN MULTIPLES OF 1000 NAIRA NOTES')
        deposit_operation(user)
    else:
        user[4] = user[4] + amount_to_deposit
        print(f'*** YOUR NEW BALANCE IS: {user[4]} NAIRA ****')

        perform_another_operation(user)

Upvotes: 0

Views: 1123

Answers (1)

Jared Smith
Jared Smith

Reputation: 21926

You separate out the parts that do I/O like take user input from the parts that do operations on the input.

def get_user_input():
    while True:
        user_input = input("Enter the amount to deposit: ")
        try:
            return validate_user_input(user_input)
        except:
            print("Input must be a number that is a multiple of 1000")

def validate_user_input(value):
    try:
        parsed = int(user_input)
        if parsed % 1000 == 0:
            return parsed
        else:
            raise Exception()
    except:
        raise ValueError("Input must be a number that is a multiple of 1000")

def update_account(user, amount):
    user[4] = user[4] + amount
    return user

if __name__ == "__main__":
    user = ...
    update_account(user, get_user_input())

Now you can test the validation logic and the account update logic independently and you don't need to test get_user_input at all. No complicated mocking, just good decomposition.

from unittest import TestCase

class TestAtm(TestCase):

    def test_validate_user_input(self):
        with self.assertRaises(Exception):
            validate_user_input("1")

        with self.assertRaises(Exception):
            validate_user_input("pizza")

        assert(validate_user_input("1000") == 1000)

    def test_update_amount(self):
        # Test that acct gets updated

Also, please don't use lists to store positional data like that. Use a dictionary or a namedtuple or a dataclass or an actual user class. Trying to remember that the 5th index is the account value is asking for bugs.

Upvotes: 1

Related Questions