如何修补类的新方法

2024-04-23 22:37:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是修补类“__new__方法,以便控制它在测试用例中创建的确切对象。请参阅下面的代码

两个测试test_1test_2在单独运行时都能正常工作。但是,当它们都连续运行时,test_2会出现以下故障:

TypeError: object.__new__() takes exactly one argument (the type to instantiate)

即使我存储了原始的__new__方法指针,并在test_1的末尾将其还原(pytest无论如何都会处理这个问题),它仍然会产生相同的结果

知道这是怎么回事吗?为了实现我的目标,工作方法是什么

import pytest


# The class:
class A:
    def __init__(self, x):
        self.x = x


def test_1(mocker):
    """First test patches the new method."""
    # Create object:
    a = A(x=3)
    # Make sure new method always returns this object:
    mocker.patch.object(A, "__new__", return_value=a)
    # Switch off the initializer (so it doesn't overwrite values in the pre-made object):
    mocker.patch.object(A, "__init__", return_value=None)
    # Do the test:
    res = A(x=1)
    assert res.x == 3


def test_2():
    """Second test uses the class as intended."""
    A(2)  # <- Fails (when run right after test_1)

更新

感谢@OctaveL指出,使用此类定义,测试工作正常:

class A(object):
    def __new__(cls, *_, **__):
        return super(A, cls).__new__(cls)

    def __init__(self, x):
        self.x = x

Tags: the方法testself目标newreturnobject