Q:

How to mock ndb.get_context().urlfetch?

In my tests I would like to mock urlfetch provided by NDB package, so no real http requests are made during tests execution.
urlfetch() returns Future, so it seems that I need to know NDB internals to mock it properly... Also I thought I could mock google.appengine.api.urlfetch.create_rpc() somehow... But I didn't make any progress so far...
How can I do this?
Thank you.

A:

I will answer my own question. In the code below I use mock library by Michael Foord.
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()

