0

How can I check if method is called inside another method, when those methods are from different classes?

If they are from same class, I can do this:

from unittest import mock

class A():
  def method_a(self):
    pass

  def method_b(self):
    self.method_a()

a = A()
a.method_a = mock.MagicMock()
a.method_b()
a.method_a.assert_called_once_with()

But if method_a would be from different class, then it would raise AssertionError that it was not called.

How could I do same check if I would have these classes instead (and I want to check if method_b calls method_a)?:

class A():
  def method_a(self):
    pass

class B():
  def method_b(self):
    A().method_a()
Andrius
  • 19,658
  • 37
  • 143
  • 243

1 Answers1

1

You have to simply stub A within the same context as B, and validate against the way it would have been called. Example:

>>> class B():
...   def method_b(self):
...     A().method_a()
... 
>>> A = mock.MagicMock()
>>> A().method_a.called
False
>>> b = B()
>>> b.method_b()
>>> A().method_a.called
True
>>> 
metatoaster
  • 17,419
  • 5
  • 55
  • 66