1

I am writing a test for a library using unittest. Real usage of the library would look like:

from mylibrary import Connection

con = Connection()

@con.notification(int)
def my_callback(value):
    print('New value:', value)

con.add_notification(my_callback)

# A remote change will now trigger the callback

Now I want to mock the callback in a unit test so I can verify it got called with the expected arguments:

import unittest
from unittest import mock

class LibraryTestCase(unittest.TestCase):

    # ...

    def my_test(self):
        mock_callback = mock.MagicMock()
        self.con.add_notification(mock_callback)
        self.con.write(3.14)  # Trigger change

        mock_callback.assert_called_once()  # This succeeds

This verifies the callback got triggered, but the callback was not decorated (this is needed to specify the variable type). How can I decorate a mocked object?
Pseudo code to illustrate what I am looking for: (not related to decorated variables)

        @con.notification(int)
        mock_callback = mock.MagicMock() 

Let me emphasize the order: I want to use a real, unmodified decorator with a mock function.

Roberto
  • 958
  • 13
  • 33
  • 2
    Use the non-`@` form, `wrapped_callback = con.notification(int)(mock_callback)`. – jonrsharpe Apr 12 '21 at 13:24
  • the comment above is the answer. – jsbueno Apr 12 '21 at 13:26
  • Perfect, thank you. I didn't know there was a classical notation.I don't agree with the duplicate mark btw. @jonrsharpe I'll accept your answer if you want to post. Otherwise I'll post it myself later to wrap this up. – Roberto Apr 12 '21 at 13:30
  • How exactly is that _not_ related to decorated variables? You're trying to decorate a variable, and have said that the unsugared version is what you want. – jonrsharpe Apr 12 '21 at 14:51
  • Thank you for your feedback. The goal is not to have a decorated variable, the goal was to put a decorator for a mocked function. The decorated variable is just a pseudo-code illustration. – Roberto Apr 13 '21 at 06:20

0 Answers0