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
calculatorfoldercd calculatorthe terminal shows I am in the
calculatorfolder.../pumping_python/calculatorI use
pytest-watcherto run the testsuv run pytest-watcher . --nowthe 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.pyto 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
review
I can use assertRaises to catch Exceptions in tests and tested these
code from the chapter
what is next?
you know
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