[mac os high sierra 10.13.6, visual studio code 1.39.2]
I want to write the unit test that captures ZeroDivisionError exception.
When the code is written in format function_v1, both test_v1 and test_v2 work.
function_v1
def divide(x, y):
if y == 0:
raise ZeroDivisionError("Can not divide by zero!")
return x/y
===
import unittest
import intro.py #the file in which divide function is in
test_v1
class TestCalc(unittest.TestCase):
def test_divide(self):
self.assertRaises(ZeroDivisionError, intro.divide, 1, 0)
test_v2
class TestCalc(unittest.TestCase):
def test_divide(self):
with self.assertRaises(ZeroDivisionError):
intro.divide(1,0)
How can I write test_v1 and test_v2 so they work when the function is written like this:
function_v2
def divide(x, y):
try:
return x / y
except ZeroDivisionError:
print("Can not divide by zero!")
function_v2 & test_v1, and function_v2 & test_v2 should both show the tests passing, and not giving out the error messages and showing the tests failed.
Results of running the program:
For both function_v1 & test_v1, and function_v1 & test_v2:
Ran 1 test in 0.000s
OK
function_v2 & test_v1:
Can not divide by zero!
FAIL: test_divide (main.TestCalc)
Traceback (most recent call last):
File "/Users/az/Desktop/coreySchafer/test_calc.py", line 35, in test_divide
self.assertRaises(ZeroDivisionError, intro.divide, 1, 0)
AssertionError: ZeroDivisionError not raised by divide
Ran 1 test in 0.001s
FAILED (failures=1)
function_v2 & test_v2
Can not divide by zero!
FAIL: test_divide (main.TestCalc)
Traceback (most recent call last):
File "/Users/az/Desktop/coreySchafer/test_calc.py", line 33, in test_divide
intro.divide(1,0)
AssertionError: ZeroDivisionError not raised
Ran 1 test in 0.002s
FAILED (failures=1)