0

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

validate_user_input should raise an exception instead of making the caller distinguish between 0 and False in the return value. get_user_input should use a loop instead of recursion to repeat the request.
@chepner done. Anything else?
You don't need to initialize data to None. Use while True:, and break if validate_user_input returns successfully.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.