gpt4 book ai didi

python - 如何测试单例 __del__() 方法?

转载 作者:行者123 更新时间:2023-12-01 07:17:38 25 4
gpt4 key购买 nike

我正在使用单例对象来管理数据库连接。我正在运行一系列依赖于该对象的测试。另外,我也必须测试该对象,因此我必须删除它并检查它的 __del__ 方法是否正确执行。

当我测试它时,因为我删除了单例,所以其他测试失败,因为它们无法再访问它。我需要在删除后恢复它,或者避免删除它并以其他方式测试删除方法。更改固定范围可能会导致执行时间增加,因此这是最后的手段。

我的单例是这样的:

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')

最佳答案

使用 deepcopy 制作单例对象的副本授予一个没有共享引用的单独对象,这可能会影响预期的行为。

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 中复制对象的更多详细信息 here .

正如 Azat 所指出的请注意深度复制的局限性:

  • Can't copy types like: module, method, stack trace, stack frame, file, socket, window, array, or any similar types.

请记住,您始终可以定义自定义 __copy__()__deepcopy__(),以防您在复制对象时需要更详尽或更复杂的处理。

关于python - 如何测试单例 __del__() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57872335/

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