gpt4 book ai didi

python - 如何在 python 中创建/实现/测试新异常?

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:46 25 4
gpt4 key购买 nike

对于如何在 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)

关于python - 如何在 python 中创建/实现/测试新异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14700236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com