我的目标是修补类“__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
目前没有回答
相关问题 更多 >
编程相关推荐