我會回答我自己的問題。在下面的代碼中,我使用Michael Foord的mock庫。
import unittest
from google.appengine.ext import testbed, ndb
from mock import patch, Mock
class MyTestCase(unittest.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
# mock urlrfetch service
uf = self.testbed.get_stub('urlfetch')
uf._Dynamic_Fetch = Mock()
@patch('google.appengine.api.urlfetch.urlfetch_service_pb.URLFetchResponse')
def test_make_request(self, URLFetchResponse):
# mocking rpc response object
response = URLFetchResponse.return_value
response.contentwastruncated.return_value = False
response.statuscode.return_value = 200
response.content.return_value = 'Hello world!'
ctx = ndb.get_context()
fut = ctx.urlfetch('http://google.com')
result = fut.get_result()
self.assertEquals(result.content, 'Hello world!')
def tearDown(self):
self.testbed.deactivate()
一種更簡單的方法,包括:'self.testbed.init_urlfetch_stub(urlmatchers = [(拉姆達地址:url.startswith( 「http://example.com」,self.get_example_com))'爲一個例子見urlfetch_to_gcs_stub實現。 – rmmh 2018-01-25 00:16:09