I have a function which searches a Bank for a specific Account object. If it finds a matching account, the function replaces the Account object with None. If it finds no match, it returns. This works perfectly in IDLE.
My unittest for this function keeps returning ValueError: <Mock id='2350965017280'> is not in list.
Here is the function:
def removeAccountFromBank(self, account):
target_index = accounts.index(account)
accounts[target_index] = None
return
Here is my test (using unittest):
def test_removeAccountFromBank(self):
account = Mock()
bank = Bank()
accounts = [None, (account), None]
print(accounts)
bank.removeAccountFromBank(account)
self.assertEqual(bank.get_accounts(), [None, None, None])
I expected this test to pass, but here is the result I got:
The print statement correctly shows the account: [None, <Mock id='2350965017280'>, None]
But I get an error when the function tries to find the account using index:
in removeAccountFromBank target_index = accounts.index(account) ValueError: <Mock id='2350965017280'> is not in list
I am confused about why the accounts.index part is returning a ValueError. I also tried printing the accounts.index(account) and it returns the correct index of 1.
MagicMockinstead of aMock. Better yet, if you are creating a realBankobject, what stops you from creating a realAccountobject?accountsis a local variable in thetest_removeAccountFromBankmethod. It is not the same variable asaccountsin theremoveAccountFromBankmethod.accountsin a containing lexical scope. (Which means it still doesn't refer to the localaccountsintest_removeAccountFromBank, because that's only wherebank.removeAccountFromBankis called, not defined.removeAccountFromBankmethod. This method is called by aCloseAccountmethod that calls apromptForAccountNumbermethod to get the account number, and search for the account. I am not sure how to replicate returning the existing account for a unittest.