Search code examples
pythonmockingpatchassert

Python, can't assert if method called from another class


I have the following code in Python:

class A():
    def doSomething(self, bClass):
        print(bClass.theThing)

class B():
    def __init__(self, theThing):
        self.theThing = theThing

def foo():
    a = A()
    b = B("that thing")
    a.doSomething(b)

I have those classes and the function foo() stored in testing.py and I want to test that the A's method was called with:

import testing, unittest
from unittest.mock import patch

class TheTestClass(unittest.TestCase):
    def test(self):
            with patch('testing.A.doSomething') as do:
                testing.foo()
                do.assert_any_call()

But I always get 'doSomething() call not found'. I would be happier if I could understand why but at this point anything is welcome


Solution

  • After many hours I started figuring this out. Like jwjhdev said assert_called_with() expects something and in my case a class but so does assert_any_call(). For some reason I was thinking assert_any_call() would just work but what I was thinking was assert_called() which just works without arguments. In the end I figured it out by adding a return b to the foo() function and:

    def foo():
        a = A()
        b = B("that thing")
        a.doSomething(b)
        return b
    
    class TheTestClass(unittest.TestCase):
        def test(self):
                with patch('testing.A.doSomething') as do:
                    b = testing.foo()
                    do.assert_any_call(b)