2
我明顯對如何在python中引發異常有一些基本的誤解。我包括了我正在嘗試(和失敗)要做的最簡單的例子。我正在嘗試創建一個新的異常,並正確測試它是否正常工作。如何在python中創建/實現/測試新的異常?
import random
import unittest
# Create new class of exception
class LearningError(Exception):
pass
# Create function
def addition_no_four(first, second):
"""Add two numbers (as long as it isn't 4)."""
if (first == 4) or (second == 4):
raise LearningError("We don't take 4s!")
return first + second
# Properly working example code that tests raising errors
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
self.assertRaises(TypeError, random.shuffle, (1,2,3))
# My code which tests
class TestAddition(unittest.TestCase):
def test_addition(self):
"""Test whether it works for 2 numbers (not 4)."""
first = 2
second = 5
self.assertEqual(addition_no_four(first, second), 7)
def test_raise(self):
"""Learn how to create an exception and test its implementation."""
self.assertRaises(LearningError, addition_no_four(2, 4))
if __name__ == "__main__":
unittest.main()
哪個失敗,出現以下消息:
Traceback (most recent call last):
File "test.py", line 34, in test_raise
self.assertRaises(LearningError, addition_no_four(2, 4))
File "test.py", line 12, in addition_no_four
raise LearningError("We don't take 4s!")
LearningError: We don't take 4s!
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (errors=1)
這不會發生(即,示例代碼正確測試前一個異常什麼我需要改變,以使這種事情發生?
謝謝!我感覺自己即將失去理智。我想/希望這將是一個簡單的解決方案! – JBWhitmore