我的目标是修补类的__new__
方法,以控制它在测试用例中创建的确切对象。请参见下面的代码。
两个测试test_1
和test_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