簡體   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