Like mock ndb.get_context (). Urlfetch?

In my tests, I would like to mock the urlfetch

provided by the NDB package, so no real HTTP requests are made during the tests.

urlfetch()

returns Future

, so I feel like I need to know the internals of the NDB in order to mock it properly ... Also I thought I could mock it somehow google.appengine.api.urlfetch.create_rpc()

... But I haven't made any progress far ...

How can i do this?

Thank.

+3


source to share


1 answer


I will answer my own question. In the code below, I am using the Michael Foord mock library.



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()

      

+5


source







All Articles