Python 如何测试Singleton _del _()方法?
我使用单例对象来管理数据库连接。我正在运行一套依赖于该对象的扩展测试。我还必须测试这个对象,所以我必须删除它并检查它的Python 如何测试Singleton _del _()方法?,python,pytest,Python,Pytest,我使用单例对象来管理数据库连接。我正在运行一套依赖于该对象的扩展测试。我还必须测试这个对象,所以我必须删除它并检查它的\uu del\uu方法是否正确执行 当我测试它时,因为我删除了单例,其他测试失败了,因为他们不能再访问它了。我需要在删除它之后恢复它,或者避免删除它并以其他方式测试删除方法。更改fixture范围可能会导致执行时间增加,因此这是最后的手段 我的单身是这样的: class Singleton(type): def __call__(cls, *args, **kwargs
\uu del\uu
方法是否正确执行
当我测试它时,因为我删除了单例,其他测试失败了,因为他们不能再访问它了。我需要在删除它之后恢复它,或者避免删除它并以其他方式测试删除方法。更改fixture范围可能会导致执行时间增加,因此这是最后的手段
我的单身是这样的:
class Singleton(type):
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "singleton_instance"):
cls.singleton_instance = super().__call__(*args, **kwargs)
return cls.singleton_instance
class SpecificSingle(metaclass=Singleton):
def __init__(self):
self.data = 'some complex data'
def __del__(self):
# complex logic before delete the object
del self.data
pass
以及一些模拟地雷的试验:
import pytest
@pytest.fixture(scope='session')
def use_the_single():
single = SpecificSingle()
yield single
del single
def test_delete(use_the_single):
use_the_single.__del__()
assert(use_the_single not in locals())
def test_something(use_the_single):
test = use_the_single.data
assert(test == 'some complex data')
使用创建singleton对象的副本将授予一个分离的对象,该对象没有可能影响预期行为的共享引用
from copy import deepcopy
def test_delete(use_the_single):
copied_single = deepcopy(use_the_single)
copied_single.__del__()
assert(copied_single not in locals())
您可以查看有关如何在python中复制对象的更多详细信息
正如deepcopy指出的,请注意deepcopy的局限性:
- 无法复制以下类型:模块、方法、堆栈跟踪、堆栈帧、文件、套接字、, 窗口、数组或任何类似类型
请记住,如果在复制对象时需要更详尽或复杂的处理,您始终可以定义自定义的
\uuuuuu copy\uuuuuu()
或\uuuu deepcopy\uuuuuuu()
。不清楚您的要求是什么。测试失败了?你的代码怎么了?你的问题是什么?@sanyash我的测试失败了,因为当我删除单例时,其中的数据会在文件和连接中执行close()之类的方法。之后,当其他测试尝试访问该对象时,它将被销毁。我想测试删除,不删除(或之后恢复)@AzatIbrakov我已经更新了答案,我想这就是你所指的。谢谢你指出这一点。