का उपयोग कर urllib2.urlopen नकली करने में सक्षम नहीं नीचे मेरी api.py मॉड्यूलपायथन के mock.patch
# -*- 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
का एक कोड का टुकड़ा मैं ऊपर मॉड्यूल के unittest
में urllib2.urlopen
उपहास करने के लिए कोशिश कर रहा हूँ है। मैं
# -*- 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'
लिखा है के बाद मैं unittest चलाने के लिए, मैं एक अपवाद
<urlopen error unknown url type: <MagicMock name='Request().get_type()' id='159846220'>>
मैं क्या याद आ रही है मिल सकता है? कृपया मेरी मदद करें।
मैंने परिवर्तन किए। '_api.call_api ('https://google.com') का मान' 'जो "mocked" से मेल नहीं खाता है। क्यूं कर? अनुलेख मैंने test_api.py –
Hussain
में 'assert' के साथ अंतिम पंक्ति को अपडेट किया है मुझे आपके परीक्षण को फिर से लिखना चाहिए .... बहुत अधिक विवरण गलत हैं। –
@ हुसैन अब यह ठीक होना चाहिए –