0

tl;dr: I know a code block I am testing with unittest is being executed because of a print statement, but a function directly after the print statement is failing an assert_called check. When running the code, the function is being called and exectued as expected. Unclear why test is failing.

Code in function being tested:

from path.to import deliver_error

def handle_error(ARGS):
  if HANDLE_ERROR_BOOL:
    print('calling deliver_error')
    deliver_error(ARGS)
  else:
    # do something else

Test code:

class TestSampleRegistration(unittest.TestCase):
    def setUp():
        # mock deliver_error
        mock_deliver_error_patch = patch("path.to.deliver_error", autospec=True)
        self.mock_deliver_error = mock_deliver_error_patch.start()
        self.addCleanup(mock_deliver_error_patch.stop)

    def test_handle_error(self):
        main.HANDLE_ERROR_BOOL = True
        handle_error(ARGS)
        self.mock_deliver_error.assert_called() # point of failure

Assertion failure:

AssertionError: Expected 'deliver_error' to have been called.

Captured stdout:

Captured stdout for test_main.MyTestClass.test_handle_error
  calling deliver_error

I KNOW:

  • HANDLE_ERROR_BOOL is correctly set (print statement executed and showing up in stdout)
  • deliver_error should be getting called since there is nothing between the print statement and the deliver_error call, and the print statement is being executed
  • when running the actual code the function is being executed as expected

So why is the assert_called test failing? Help very much appreciated, thank you!

TootToot
  • 1
  • 5
  • You mock the wrong reference, see [where to patch](https://docs.python.org/3/library/unittest.mock.html#id6). Instead of mocking `path.to.deliver_error` you have to mock `mymodule.deliver_error`, provided that `handle_error` lives in `mymodule`. I have answered a similar question [here](https://stackoverflow.com/q/62624390/12480730). – MrBean Bremen Jan 17 '21 at 20:09
  • Thank you @MrBeanBremen! That solved it. – TootToot Jan 20 '21 at 18:29

1 Answers1

0

Answering for the sake of others who might see this post:

As per MrBean Bremen's comment, the resolution was to update the mock from

class TestSampleRegistration(unittest.TestCase):
  def setUp():
    # mock deliver_error
    mock_deliver_error_patch = patch("path.to.deliver_error", autospec=True)
  

to

class TestSampleRegistration(unittest.TestCase):
  def setUp():
    # mock deliver_error
    mock_deliver_error_patch = patch("mymodule.deliver_error", autospec=True) 
TootToot
  • 1
  • 5