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

时间:2015-09-23 11:36:23

标签: python python-unittest

我试图验证 Base.run_this 的实现是否按正确顺序调用派生类(derived_method_ [1st | 2nd | 3rd])的方法。如输出所示,测试无效。我该如何解决这个问题?

printBill(printBills, lastBillNo, type, taxType, outletId, date, function (printableObjects) {
    //Do something with that array - printableObjects
}

输出

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()])

1 个答案:

答案 0 :(得分:0)

wraps实例不兼容。这里发生的是mocked.run_this返回一个新的模拟对象'wraps'Derived(True).run_this,其中后者是原始 Derived()实例的绑定方法。 / p>

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

您可以使用run_this模拟spec方法修补:

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()]
相关问题