How can I mock a Python class that has two imports without changing the code in any of the imported modules? Suppose I import a web utilities library that imports HTTPClient () - how can I write a unit test that mocks HTTPClient to return a value without changing the web_utils.py file? I want to use data manipulation in the DataHandler (rather than mock it), but I don't want the HTTPClient to actually connect to the network.
Is it possible? Given that Python has a monkey fix, this certainly seems to be the case. Or is there an alternative / better way? I still understand the mocking process, much less changing the import.
from abc.client import SomeHTTPClient
def get_client():
tc = SomeHTTPClient(endpoint='url')
return tc
class DataHandler(object):
def post_data(someURL, someData):
newData = massage(someData)
client = get_client()
some_response = client.request(someURL, 'POST', newData)
return some_response
from someLib.web_utils import DataHandler
dh = DataHandler()
reply = dh.post_data(url, data)
from django.test.testcases import TestCase
from mock import Mock
class Mocking_Test(TestCase):
def test_mock(self):
from someLib import web_utils
fakeClient = Mock()
fakeClient.request = web_utils.SomeHTTPClient.request
web_utils.SomeHTTPClient = fakeClient
dh = DataHandler()
reply = dh.post_data(url='somewhere', data='stuff')
- get_client(). , @spicavigo - , , SomeHTTPClient. - ( " , " ). , , Mock(), , . , .