断言派生类方法是在正确的ord中调用的

2024-04-29 10:19:37 发布

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

我试图验证基地。运行这个以正确的顺序调用派生类的方法(派生方法_1;1st | 2nd | 3rd])。如输出所示,测试不起作用。我该怎么解决这个问题?在

class Base(object):
  __metaclass__ = abc.ABCMeta

  def __init__(self, parameters):
   self.parameters = parameters;

  @abc.abstractmethod
  def must_implement_this(self):
   return

  def run_this(self):
   self.must_implement_this()
   if(self.parameters):
    first = getattr(self, "derived_method_1st")
    first()
    second = getattr(self, "derived_method_2nd")
    second()
    third = getattr(self, "derived_method_3rd")
    third()

class Derived(Base):
  def must_implement_this(self):
   pass
  def derived_method_1st(self):
   pass
  def derived_method_2nd(self):
   pass
  def derived_method_3rd(self):
   pass

mocked = MagicMock(wraps=Derived(True))
mocked.run_this()
mocked.assert_has_calls([call.derived_method_1st(), call.derived_method_2nd(), call.derived_method_3rd()])

输出

^{pr2}$

Tags: 方法selfbasedefpassimplementcallthis
1条回答
网友
1楼 · 发布于 2024-04-29 10:19:37

wraps实例不兼容。这里发生的是mocked.run_this返回一个新的mock对象,它“包装”Derived(True).run_this,其中后者是绑定到原始Derived()实例的绑定方法。在

因此,该方法将调用绑定到原始实例而不是模拟的self.derived_method_*方法。在

您可以在specmock上修补run_this方法:

mock = MagicMock(spec=Derived)
instance = mock()
instance.run_this = Derived.run_this.__get__(instance)  # bind to mock instead
instance.parameters = True  # adjust as needed for the test
instance.run_this()

演示:

^{pr2}$

相关问题 更多 >