I'm new to coding and trying to test some functions I've made for a simple ATM program.
def pin_validation(pin):
if pin == user_pin:
return True
else:
return False
def log_in():
tries = 0
while tries < 3:
pin = input("Enter PIN: ")
if pin_validation(pin):
return True
else:
print("Incorrect PIN")
tries += 1
raise TypeError("Account locked")
return False
def withdraw_cash():
while True:
amount_to_withdraw = int(input("How much would you like withdraw: "))
if amount_to_withdraw > user_balance:
raise ValueError("Not enough funds in account")
else:
new_balance = user_balance - amount_to_withdraw
print("New balance is {}".format(new_balance))
return False
assert new_balance > 0
So far I've got the following for tests:
classTestATM(unittest.testcase):
def test_pin_validation(self):
test_input = 9876
test_result = pin_validation(test_input)
self.assertEqual(test_result, True)
How would I write tests for the other functions?
-
I would recommend using patching so that you can control what input returns. docs.python.org/3/library/unittest.mock.html this will let you test the other two. If you still have issues then you can edit your current post with what you have tried and we can try to help with that.NTamez8– NTamez82022年06月22日 10:21:14 +00:00Commented Jun 22, 2022 at 10:21
1 Answer 1
You can patch the inputs within your functions and use side_effect for the test cases with multiple inputs.
import unittest
import unittest.mock
classTestATM(unittest.testcase):
@unittest.mock.patch('builtins.input', side_effect=[1000, 1001, 1002])
def test_log_in(self):
self.assertFalse(log_in())
@unittest.mock.patch('builtins.input', side_effect=[500, 1000, 2000, 3000])
def test_withdraw_cash(self):
self.assertFalse(withdraw_cash())
Sign up to request clarification or add additional context in comments.
Comments
lang-py