0

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.

7
  • Try using a MagicMock instead of a Mock. Better yet, if you are creating a real Bank object, what stops you from creating a real Account object? Commented Apr 28, 2024 at 15:37
  • 1
    accounts is a local variable in the test_removeAccountFromBank method. It is not the same variable as accounts in the removeAccountFromBank method. Commented Apr 28, 2024 at 15:43
  • @chepner I tested with a real Account object just now and it returned ValueError (with no further info). I'm not familiar with MagicMock yet, unfortunately, and Mock has worked well for my other unittests similar to this one. Commented Apr 28, 2024 at 15:44
  • @JohnGordon It's not a local variable, but a free variable to refers to a variable named accounts in a containing lexical scope. (Which means it still doesn't refer to the local accounts in test_removeAccountFromBank, because that's only where bank.removeAccountFromBank is called, not defined. Commented Apr 28, 2024 at 15:53
  • @JohnGordon Okay, that makes sense given how accounts is being accessed by my removeAccountFromBank method. This method is called by a CloseAccount method that calls a promptForAccountNumber method to get the account number, and search for the account. I am not sure how to replicate returning the existing account for a unittest. Commented Apr 28, 2024 at 15:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.