对于如何在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)
那是不会发生的(即示例代码正确地测试了先前的异常。为了使这种事情发生,我需要更改什么?
最佳答案
只是一个小小的变化。使用assertRaises时,请确保不要直接调用该函数。相反,需要将其参数作为参数传递给assertRaises。这允许assertRaises测试方法在调用函数之前设置try / except。
def test_raise(self):
"""Learn how to create an exception and test its implementation."""
self.assertRaises(LearningError, addition_no_four, 2, 4)
您还可以通过使用assertRaises作为内容管理器来绕过此问题:
def test_raise(self):
"""Learn how to create an exception and test its implementation."""
with self.assertRaises(LearningError):
addition_no_four(2, 4)