lundi 1 février 2016

Mocking imported socket

I have a module set up with the following __init__.py:

from client.client import Client
from client.clientui import ClientUI

__author__ = 'ToothlessRebel'

__all__ = [
    'Client',
    'ClientUI'
]

The class itself is defined as follows (partial):

from socket import socket

class Client:
    socket = None

    def __init__(self, master):
        ...
        self.socket = socket()
        ...

    def send(self, command):
    if self.connect:
        total_successful = 0
        while total_successful < command.__len__():
            successful = self.socket.send(bytes(command[total_successful:] + "\r\n", "UTF-8"))
            if successful == 0:
                raise RuntimeError("Unable to send message.")
            total_successful = total_successful + successful
    else:
        self.ui.parse_output("No connection -- please reconnect to send commands.\n")

I'm trying to test the class. I was hoping to mock the socket so that my testing need not make actual connections to the resource. My test in full is:

import mock
import unittest
import client


class TestClient(unittest.TestCase):
    def test_send(self):
        mock_client.connect = True
        mock_client.send('Testing')
with mock.patch('client.Client'):
    myClient = client.Client(None)
    myClient.socket.send.assert_called_with('Testing)


if __name__ == '__main__':
    unittest.main()

I can't seem to get the socket.send() method to be called. I imagine it's something to do with the module's import of socket but I'm not sure what. At least I get an AssertionError for the method not being called. I tried using assert_called_with(mock.ANY) as well, to no avail.

If I try to emulate this answer with:

with mock.patch('client.Client.socket'):
    mock_client = client.Client(None)
    mock_client.socket.send.assert_called_with('Testing')

I get the following error:

AttributeError: class 'client.client.Client' does not have the attribute 'socket'

Aucun commentaire:

Enregistrer un commentaire