dimanche 31 juillet 2016

How to mock object from third party library at specific time

I'm trying to mock the reponse from urllib2.urlopen from the Clarifay Python client.

The reason for this is that I don't want to expend an API call while testing, since I want to check that everything works ok but just fake the response to the server when I try to tag images using their client.

Problem is that urllib2.urlopen is used BEFORE I make use of their method to tag images (mostly to check API configuration, Oauth credential, etc) which kinda breaks my whole thing since I cannot go forward.

So this is my testing code:

    # Patch the actual code that clarifai client uses
    with patch('clarifai.client.mime_util.urllib2.urlopen') as mock_get:
        # Configure the mock to return a response with an OK status code.
        fd = open('fixtures/dummy_clarifai_result.json', 'r')
        dummy_response = json.load(fd)
        fd.close()
        mock_get.return_value = dummy_response
        response = self.tagger.process_images_clarifai(folder_name='sample_images')
        self.assertIsNotNone(response)
        self.assertTrue(response.empty)

The clarifai client calls the mime_util module to actually call this method, that I'm interested to mock the response

def post_multipart_request(url, multipart_message, headers={}):
    data, headers = message_as_post_data(multipart_message, headers)
    req = RequestWithMethod(url, 'POST', data, headers)
    f = urllib2.urlopen(req)
    response = f.read()
    f.close()
    return response

As I said, before the call to this method actually happens, the urlib2.urlopen is called in-between. Now I wonder if I can tell somehow to mock the object not the whole time but just when I want it...I really doubt it since just calling the tagging method executes this calling tree that in-between calls urlopen...

Also tried to mock directly that method (post_multipart_request) but I keep on getting errors with the path at the patch annotation...

Thanks!

Aucun commentaire:

Enregistrer un commentaire