I try to use mock
to write some unit-tests in python.
For example I have the following class:
class TCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
And I only want to test the handle
method. Without having to assume anything about socketserver.BaseRequestHandler
. I for example want to assert that handle
calls recv
with the argument 1024
. Is it possible to do such thing with mock? I.e. replacing the base class socketserver.BaseRequestHandler
with a mock? Or am I off track with that idea?
With the answer of ecatmur (thank you!) I first tried the following:
patcher = patch.object(TCPHandler, '__bases__', (Mock,))
with patcher:
patcher.is_local = True
handler = TCPHandler()
handler.handle()
But now handle
is not called anylonger and dir(handler)
gives:
['assert_any_call', 'assert_called_once_with', 'assert_called_with', 'assert_has_calls', 'attach_mock', 'call_args', 'call_args_list', 'call_count', 'called', 'configure_mock', 'method_calls', 'mock_add_spec', 'mock_calls', 'reset_mock', 'return_value', 'side_effect']
type(handler)
gives
<class 'mock.TCPHandler'>
Which I interpret that patching the base class also turns my derived class into a mock.
I now gave another idea a try:
mock = MagicMock()
TCPHandler.handle(mock)
#assertions
However the mock seems not to be called.
See Question&Answers more detail:
os