Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to mock a base class with python mock library
    primarykey
    data
    text
    <p>I try to use <code>mock</code> to write some unit-tests in python.</p> <p>For example I have the following class:</p> <pre><code>class TCPHandler(socketserver.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() </code></pre> <p>And I only want to test the <code>handle</code> method. Without having to assume anything about <code>socketserver.BaseRequestHandler</code>. I for example want to assert that <code>handle</code> calls <code>recv</code> with the argument <code>1024</code>. Is it possible to do such thing with mock? I.e. replacing the base class <code>socketserver.BaseRequestHandler</code> with a mock? Or am I off track with that idea?</p> <hr> <p>With the answer of ecatmur (thank you!) I first tried the following:</p> <pre><code>patcher = patch.object(TCPHandler, '__bases__', (Mock,)) with patcher: patcher.is_local = True handler = TCPHandler() handler.handle() </code></pre> <p>But now <code>handle</code> is not called anylonger and <code>dir(handler)</code> gives:</p> <pre><code>['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'] </code></pre> <p><code>type(handler)</code> gives <code>&lt;class 'mock.TCPHandler'&gt;</code></p> <p>Which I interpret that patching the base class also turns my derived class into a mock. </p> <hr> <p>I now gave another idea a try:</p> <pre><code>mock = MagicMock() TCPHandler.handle(mock) #assertions </code></pre> <p>However the mock seems not to be called.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload