我的目标是在不调用其初始值设定项的情况下测试类(因为初始值设定项有一些副作用,我想防止该测试发生)
我可以通过test_1
中的代码实现这一点,它本身就可以很好地工作。但是,它似乎以某种方式污染了init/new方法,因为test_2
在test_1
之后运行时失败,原因是:
TypeError: object.__new__() takes exactly one argument (the type to instantiate)
单独运行每个测试时,它们都通过
你知道这里发生了什么吗?我如何解决这个问题,也就是说,在模拟和测试之后如何正确地重置init/new方法
import pytest
# The class to test:
class A:
def __init__(self, x):
self.x = x
def test_1(mocker):
"""First test uses the class without triggering the initializer."""
# Create object without triggering the initializer:
a = A.__new__(A)
# Store away the old methods:
new_orig = A.__new__
init_orig = A.__init__
# Mock new/init methods:
mocker.patch.object(A, "__new__", return_value=a)
mocker.patch.object(A, "__init__", return_value=None)
# Do the test:
res = A()
# ...
# Restore new/init methods:
A.__init__ = init_orig
A.__new__ = new_orig
def test_2():
"""Second test uses the class as intended."""
A(2)
如果您只想避免调用
__init__
,那么可以使用以下代码,而无需在__new__
中进行修补也不需要存储新的/init方法
相关问题 更多 >
编程相关推荐