how to make a calculator 2

I want to use assertRaises to make sure test_division from the calculator project raises ZeroDivisionError


preview

These are the tests I have by the end of the chapter


open the project

  • I change directory to the calculator folder

    cd calculator
    

    the terminal shows I am in the calculator folder

    .../pumping_python/calculator
    
  • I use pytest-watcher to run the tests

    uv run pytest-watcher . --now
    

    the terminal shows

    rootdir: .../pumping_python/calculator
    configfile: pyproject.toml
    collected 4 items
    
    tests/test_calculator.py ....                                 [100%]
    
    ======================== 4 passed in X.YZs =========================
    
  • I hold ctrl on the keyboard, then click on tests/test_calculator.py to open it in the editor


test catching ZeroDivisionError in test_calculator.py


RED: make it fail


I add a new assertion to show that the divide function raises ZeroDivisionError when I try to divide a number by 0

42    def test_division(self):
43        self.assertEqual(
44            src.calculator.divide(
45                self.random_first_number,
46                self.random_second_number
47            ),
48            self.random_first_number/self.random_second_number
49        )
50        src.calculator.divide(self.random_first_number, 0)
51
52
53# Exceptions seen

the terminal shows ZeroDivisionError

ZeroDivisionError: float division by zero

GREEN: make it pass


I add assertRaises

48            self.random_first_number/self.random_second_number
49        )
50        with self.assertRaises(ZeroDivisionError):
51            src.calculator.divide(self.random_first_number, 0)
52
53
54# Exceptions seen

the test passes


close the project

  • I close test_calculator.py in the editor

  • I click in the terminal, then use q on the keyboard to leave the tests. The terminal goes back to the command line

  • I change directory to the parent of calculator

    cd ..
    

    the terminal shows

    .../pumping_python
    

    I am back in the pumping_python directory


review

I can use assertRaises to catch Exceptions in tests and tested these

code from the chapter

Do you want to see all the CODE I typed in this chapter?


what is next?

you know

Would you like to test handling Exceptions in programs?


rate pumping python

If this has been a 7 star experience for you, please CLICK HERE to leave a 5 star review of pumping python. It helps other people get into the book too