Di seguito è riportato un frammento di codice del mio modulo api.pyNon in grado di prendere in giro urllib2.urlopen usando mock.patch di Python
# -*- 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
Sto cercando di deridere urllib2.urlopen
in unittest
del modulo di cui sopra. Ho scritto
# -*- 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()
assert _api.call_api('https://google.com') == 'mocked'
Dopo ho eseguito l'unittest, ottengo un'eccezione
<urlopen error unknown url type: <MagicMock name='Request().get_type()' id='159846220'>>
Che cosa mi manca? Per favore aiutatemi.
Ho apportato le modifiche. Il valore di '_api.call_api ('https://google.com')' è '' che non corrisponde a "mocked". Perché? Post scriptum Ho aggiornato l'ultima riga con 'assert' in test_api.py –
Hussain
Dovrei riscrivere il test .... Troppi dettagli sono sbagliati. –
@Hussain ora dovrebbe essere OK –