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.