我不想让一个名为destructe的Python对象返回一个错误。在
我一直在写单元测试,因为似乎单元测试在对象被删除之前就完成了。
在测试返回之前,我没有设法强制删除该对象,而且我无法在测试中直接调用__del__,原因有二:这不是我要测试的内容
这实际上导致对象被销毁两次,在我的例子中,析构函数释放了一些内存,因此当调用两次时,它会创建一个分段错误。
为了说明这一点,我创建了一个玩具示例,其中我有两个对象。第一个MyWrongObject,在析构函数中包含一个bug,第二个MyCorrectObject是正确的。
我已经为每个对象编写了测试。一个应该成功,另一个应该失败。在import unittest
import gc
class MyWrongObject(object):
def __init__(self):
self.del_calls = 0
def __del__(self):
if self.del_calls:
# Something really bad can happen here like a segmentation fault
# because we may free some memory twice
raise AssertionError("Already destroyed")
self.del_calls += 1
# Simulate an error
raise ValueError("Error while destroying the object")
class MyCorrectObject(object):
def __init__(self):
self.del_calls = 0
def __del__(self):
if self.del_calls:
# Something really bad can happen here like a segmentation fault
# because we may free some memory twice
raise AssertionError("Already destroyed")
self.del_calls += 1
# No error here
class TestDestructor(unittest.TestCase):
def test_my_correct_object_should_destroy_itself(self):
# Given
my_object = MyCorrectObject()
# When / Then
del my_object
gc.collect()
# This test should fail
def test_my_wrong_object_should_destroy_itself(self):
# Given
my_object = MyWrongObject()
# When / Then
del my_object
gc.collect()
在当前状态下,两个测试都成功,第二个测试在stdout中打印ValueError:
^{pr2}$
我无法以一致的方式编写这些测试(在两个测试中使用相同的代码),并且第一个测试通过,而第二个测试失败(在stdout中没有任何AssertionError)。在
谢谢你的帮助!在