Reputation: 3
I have some code I'd like to quickly test. This code includes a line that needs to query a server and obtain a True/False answer:
result = server.queryServer(data)
Is there a way to override this function call so that it just calls a local function that always returns True (so that I can debug without running the server)?
Upvotes: 0
Views: 574
Reputation: 1125248
What you want is called mocking, replacing existing objects with temporary objects that act differently just for a test.
Use the unittest.mock
library to do this. It will create the temporary objects for you, and give you the tools to replace the object, and restore the old situation, for the duration of a test.
The module provides patchers to do the replacement. For example, you could use a context manager:
from unittest import mock
with mock.patch('server.queryServer') as mocked_queryServer:
mocked_queryServer.return_value = True # always return True when called
# test your code
# ...
# afterwards, check if the mock has been called at least once.
mocked_queryServer.assert_called()
I added an assertion at the end there; mock objects not only let you replace functions transparently, they then also record what happens to them, letting you check if your code worked correctly by calling the mock.
Upvotes: 1