Original BankAccount Implementation
Initially, our BankAccount class was implemented as follows:Problem: Insufficient Funds Check
Upon inspection, thewithdraw method does not verify if the account has sufficient funds. For example, if the account has 500 is attempted, the operation should be blocked. To address this, we add a check in the withdraw method that raises an exception when necessary.
Updated BankAccount Implementation with Basic Exception
The revised BankAccount class adds a condition to thewithdraw method to raise an exception if the withdrawal amount exceeds the account balance:
Adjusting Tests for Exception Handling
The original parameterized test included a case where more money was withdrawn than deposited:Creating a Dedicated Test for Insufficient Funds
We use Pytest’sraises context manager for this purpose. For an account with an initial balance of zero (using the zero_bank_account fixture), attempting to withdraw money should trigger an exception:
bank_account fixture initializes an account with a balance (for instance, 50) to ensure that withdrawing $200 raises the expected exception. Running the tests now produces:
Introducing a Custom Exception: InsufficientFunds
For better clarity and maintainability in production code, we define a custom exception calledInsufficientFunds that inherits from Python’s built-in Exception class. This approach allows our tests to verify that the correct exception is raised.
Defining the Custom Exception
Updated BankAccount Class with Custom Exception
The BankAccount class is updated to raiseInsufficientFunds when an over-withdrawal is attempted:
Updating the Test for Insufficient Funds
We also update the insufficient funds test to assert that anInsufficientFunds exception is raised:
Specifying the exact exception type ensures that our code not only raises an error but also raises the correct, expected type. This improves test precision and code reliability.
Demonstrating the Importance of the Correct Exception Type
To highlight the importance of using a custom exception, consider a scenario whereZeroDivisionError is raised instead of InsufficientFunds. For example, changing the withdraw method as shown below would trigger a test failure: