mardi 31 mars 2015

Not able to mock urllib2.urlopen using Python's mock.patch

Below is a code snippet of my api.py module



# -*- coding: utf-8 -*-

from urllib2 import urlopen
from urllib2 import Request

class API:

def call_api(self, url, post_data=None, header=None):
is_post_request = True if (post_data and header) else False
response = None
try:
if is_post_request:
url = Request(url = url, data = post_data, headers = header)
# Calling api
api_response = urlopen(url)
response = api_response.read()
except Exception as err:
response = err

return response


I am trying to mock urllib2.urlopen in unittest of above module. I have written



# -*- coding: utf-8 -*-
# test_api.py

from unittest import TestCase
import mock

from api import API

class TestAPI(TestCase):

@mock.patch('urllib2.Request')
@mock.patch('urllib2.urlopen')
def test_call_api(self, urlopen, Request):
urlopen.read.return_value = 'mocked'
Request.get_host.return_value = 'google.com'
Request.type.return_value = 'https'
Request.data = {}
_api = API()
_api.call_api('https://google.com')


After I run the unittest, I get an exception



<urlopen error unknown url type: <MagicMock name='Request().get_type()' id='159846220'>>


What am I missing? Please help me out.


Aucun commentaire:

Enregistrer un commentaire