繁体   English   中英

断言派生类方法的调用顺序正确

[英]Assert that derived class methods are called in correct order

我正在尝试验证Base.run_this的实现是否以正确的顺序调用了派生类的方法(derived_method_ [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()])

输出量

AssertionError: Calls not found.
  Expected: [call.derived_method_1st(), call.derived_method_2nd(),   call.derived_method_3rd()]
  Actual: [call.run_this()]

wraps不适用于实例 此处发生的是mocked.run_this返回一个新的模拟对象,该对象“包装”了Derived(True).run_this ,后者是原始 Derived()实例的绑定方法。

这样,该方法将调用绑定到该原始实例(而不是模拟对象)的self.derived_method_*方法。

您可以run_thisspec模拟中修补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()

演示:

>>> 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()
>>> instance.mock_calls
[call.must_implement_this(),
 call.derived_method_1st(),
 call.derived_method_2nd(),
 call.derived_method_3rd()]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM